From abc3a2cc3c5ec777fecb5e0eac551ad17bdb1c6e Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Sun, 25 Oct 2015 18:21:51 -0700 Subject: [PATCH 001/309] initial commit --- LICENSE.md | 206 ++++++++++ README.md | 77 ++++ addrbook.go | 813 ++++++++++++++++++++++++++++++++++++++ addrbook_test.go | 161 ++++++++ connection.go | 640 ++++++++++++++++++++++++++++++ listener.go | 213 ++++++++++ log.go | 7 + netaddress.go | 213 ++++++++++ peer.go | 133 +++++++ peer_set.go | 227 +++++++++++ peer_set_test.go | 168 ++++++++ pex_reactor.go | 255 ++++++++++++ secret_connection.go | 346 ++++++++++++++++ secret_connection_test.go | 202 ++++++++++ switch.go | 384 ++++++++++++++++++ switch_test.go | 234 +++++++++++ types.go | 74 ++++ upnp/README.md | 5 + upnp/log.go | 7 + upnp/probe.go | 111 ++++++ upnp/upnp.go | 380 ++++++++++++++++++ util.go | 15 + version.go | 3 + 23 files changed, 4874 insertions(+) create mode 100644 LICENSE.md create mode 100644 README.md create mode 100644 addrbook.go create mode 100644 addrbook_test.go create mode 100644 connection.go create mode 100644 listener.go create mode 100644 log.go create mode 100644 netaddress.go create mode 100644 peer.go create mode 100644 peer_set.go create mode 100644 peer_set_test.go create mode 100644 pex_reactor.go create mode 100644 secret_connection.go create mode 100644 secret_connection_test.go create mode 100644 switch.go create mode 100644 switch_test.go create mode 100644 types.go create mode 100644 upnp/README.md create mode 100644 upnp/log.go create mode 100644 upnp/probe.go create mode 100644 upnp/upnp.go create mode 100644 util.go create mode 100644 version.go diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 000000000..ec02173eb --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,206 @@ +Tendermint P2P +Copyright (C) 2015 Tendermint + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation, either version 3 of the License, or +(at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. + +You should have received a copy of the GNU General Public License +along with this program. If not, see . + +//-------------------------------------------------------------------------------- + +GNU GENERAL PUBLIC LICENSE + +Version 3, 29 June 2007 + +Copyright © 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +Preamble + +The GNU General Public License is a free, copyleft license for software and other kinds of works. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. + +When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. + +To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. + +Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. + +Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. + +Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and modification follow. + +TERMS AND CONDITIONS + +0. Definitions. +“This License” refers to version 3 of the GNU General Public License. + +“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. + +To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. + +A “covered work” means either the unmodified Program or a work based on the Program. + +To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +1. Source Code. +The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. + +A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + +The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + +a) The work must carry prominent notices stating that you modified it, and giving a relevant date. +b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. +c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. +d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + +a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. +b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. +c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. +d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. +e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + +“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + +a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or +b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or +c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or +d) Limiting the use for publicity purposes of names of licensors or authors of the material; or +e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or +f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. +All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +8. Termination. +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +11. Patents. +A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. + +A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. +If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + +13. Use with the GNU Affero General Public License. +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. + +14. Revised Versions of this License. +The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. + +Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS diff --git a/README.md b/README.md new file mode 100644 index 000000000..3fc02e2f2 --- /dev/null +++ b/README.md @@ -0,0 +1,77 @@ +# `tendermint/go-p2p` + +`tendermint/go-p2p` provides an abstraction around peer-to-peer communication.
+ +## Peer/MConnection/Channel + +Each peer has one `MConnection` (multiplex connection) instance. + +__multiplex__ *noun* a system or signal involving simultaneous transmission of +several messages along a single channel of communication. + +Each `MConnection` handles message transmission on multiple abstract communication +`Channel`s. Each channel has a globally unique byte id. +The byte id and the relative priorities of each `Channel` are configured upon +initialization of the connection. + +There are two methods for sending messages: +```go +func (m MConnection) Send(chID byte, msg interface{}) bool {} +func (m MConnection) TrySend(chID byte, msg interface{}) bool {} +``` + +`Send(chID, msg)` is a blocking call that waits until `msg` is successfully queued +for the channel with the given id byte `chID`. The message `msg` is serialized +using the `tendermint/wire` submodule's `WriteBinary()` reflection routine. + +`TrySend(chID, msg)` is a nonblocking call that returns false if the channel's +queue is full. + +`Send()` and `TrySend()` are also exposed for each `Peer`. + +## Switch/Reactor + +The `Switch` handles peer connections and exposes an API to receive incoming messages +on `Reactors`. Each `Reactor` is responsible for handling incoming messages of one +or more `Channels`. So while sending outgoing messages is typically performed on the peer, +incoming messages are received on the reactor. + +```go +// Declare a MyReactor reactor that handles messages on MyChannelID. +type MyReactor struct{} + +func (reactor MyReactor) GetChannels() []*ChannelDescriptor { + return []*ChannelDescriptor{ChannelDescriptor{ID:MyChannelID, Priority: 1}} +} + +func (reactor MyReactor) Receive(chID byte, peer *Peer, msgBytes []byte) { + r, n, err := bytes.NewBuffer(msgBytes), new(int64), new(error) + msgString := ReadString(r, n, err) + fmt.Println(msgString) +} + +// Other Reactor methods omitted for brevity +... + +switch := NewSwitch([]Reactor{MyReactor{}}) + +... + +// Send a random message to all outbound connections +for _, peer := range switch.Peers().List() { + if peer.IsOutbound() { + peer.Send(MyChannelID, "Here's a random message") + } +} +``` + +### PexReactor/AddrBook + +A `PEXReactor` reactor implementation is provided to automate peer discovery. + +```go +book := p2p.NewAddrBook(addrBookFilePath) +pexReactor := p2p.NewPEXReactor(book) +... +switch := NewSwitch([]Reactor{pexReactor, myReactor, ...}) +``` diff --git a/addrbook.go b/addrbook.go new file mode 100644 index 000000000..367ced8d9 --- /dev/null +++ b/addrbook.go @@ -0,0 +1,813 @@ +// Modified for Tendermint +// Originally Copyright (c) 2013-2014 Conformal Systems LLC. +// https://github.com/conformal/btcd/blob/master/LICENSE + +package p2p + +import ( + "encoding/binary" + "encoding/json" + "math" + "math/rand" + "net" + "os" + "sync" + "time" + + . "github.com/tendermint/go-common" +) + +const ( + // addresses under which the address manager will claim to need more addresses. + needAddressThreshold = 1000 + + // interval used to dump the address cache to disk for future use. + dumpAddressInterval = time.Minute * 2 + + // max addresses in each old address bucket. + oldBucketSize = 64 + + // buckets we split old addresses over. + oldBucketCount = 64 + + // max addresses in each new address bucket. + newBucketSize = 64 + + // buckets that we spread new addresses over. + newBucketCount = 256 + + // old buckets over which an address group will be spread. + oldBucketsPerGroup = 4 + + // new buckets over which an source address group will be spread. + newBucketsPerGroup = 32 + + // buckets a frequently seen new address may end up in. + maxNewBucketsPerAddress = 4 + + // days before which we assume an address has vanished + // if we have not seen it announced in that long. + numMissingDays = 30 + + // tries without a single success before we assume an address is bad. + numRetries = 3 + + // max failures we will accept without a success before considering an address bad. + maxFailures = 10 + + // days since the last success before we will consider evicting an address. + minBadDays = 7 + + // % of total addresses known returned by GetSelection. + getSelectionPercent = 23 + + // min addresses that must be returned by GetSelection. Useful for bootstrapping. + minGetSelection = 32 + + // max addresses returned by GetSelection + maxGetSelection = 2500 + + // current version of the on-disk format. + serializationVersion = 1 +) + +/* AddrBook - concurrency safe peer address manager */ +type AddrBook struct { + QuitService + + mtx sync.Mutex + filePath string + rand *rand.Rand + key string + ourAddrs map[string]*NetAddress + addrLookup map[string]*knownAddress // new & old + addrNew []map[string]*knownAddress + addrOld []map[string]*knownAddress + wg sync.WaitGroup + nOld int + nNew int +} + +const ( + bucketTypeNew = 0x01 + bucketTypeOld = 0x02 +) + +// Use Start to begin processing asynchronous address updates. +func NewAddrBook(filePath string) *AddrBook { + am := &AddrBook{ + rand: rand.New(rand.NewSource(time.Now().UnixNano())), + ourAddrs: make(map[string]*NetAddress), + addrLookup: make(map[string]*knownAddress), + filePath: filePath, + } + am.init() + am.QuitService = *NewQuitService(log, "AddrBook", am) + return am +} + +// When modifying this, don't forget to update loadFromFile() +func (a *AddrBook) init() { + a.key = CRandHex(24) // 24/2 * 8 = 96 bits + // New addr buckets + a.addrNew = make([]map[string]*knownAddress, newBucketCount) + for i := range a.addrNew { + a.addrNew[i] = make(map[string]*knownAddress) + } + // Old addr buckets + a.addrOld = make([]map[string]*knownAddress, oldBucketCount) + for i := range a.addrOld { + a.addrOld[i] = make(map[string]*knownAddress) + } +} + +func (a *AddrBook) OnStart() error { + a.QuitService.OnStart() + a.loadFromFile(a.filePath) + a.wg.Add(1) + go a.saveRoutine() + return nil +} + +func (a *AddrBook) OnStop() { + a.QuitService.OnStop() + a.wg.Wait() +} + +func (a *AddrBook) AddOurAddress(addr *NetAddress) { + a.mtx.Lock() + defer a.mtx.Unlock() + log.Info("Add our address to book", "addr", addr) + a.ourAddrs[addr.String()] = addr +} + +func (a *AddrBook) OurAddresses() []*NetAddress { + addrs := []*NetAddress{} + for _, addr := range a.ourAddrs { + addrs = append(addrs, addr) + } + return addrs +} + +func (a *AddrBook) AddAddress(addr *NetAddress, src *NetAddress) { + a.mtx.Lock() + defer a.mtx.Unlock() + log.Info("Add address to book", "addr", addr, "src", src) + a.addAddress(addr, src) +} + +func (a *AddrBook) NeedMoreAddrs() bool { + return a.Size() < needAddressThreshold +} + +func (a *AddrBook) Size() int { + a.mtx.Lock() + defer a.mtx.Unlock() + return a.size() +} + +func (a *AddrBook) size() int { + return a.nNew + a.nOld +} + +// Pick an address to connect to with new/old bias. +func (a *AddrBook) PickAddress(newBias int) *NetAddress { + a.mtx.Lock() + defer a.mtx.Unlock() + + if a.size() == 0 { + return nil + } + if newBias > 100 { + newBias = 100 + } + if newBias < 0 { + newBias = 0 + } + + // Bias between new and old addresses. + oldCorrelation := math.Sqrt(float64(a.nOld)) * (100.0 - float64(newBias)) + newCorrelation := math.Sqrt(float64(a.nNew)) * float64(newBias) + + if (newCorrelation+oldCorrelation)*a.rand.Float64() < oldCorrelation { + // pick random Old bucket. + var bucket map[string]*knownAddress = nil + for len(bucket) == 0 { + bucket = a.addrOld[a.rand.Intn(len(a.addrOld))] + } + // pick a random ka from bucket. + randIndex := a.rand.Intn(len(bucket)) + for _, ka := range bucket { + if randIndex == 0 { + return ka.Addr + } + randIndex-- + } + PanicSanity("Should not happen") + } else { + // pick random New bucket. + var bucket map[string]*knownAddress = nil + for len(bucket) == 0 { + bucket = a.addrNew[a.rand.Intn(len(a.addrNew))] + } + // pick a random ka from bucket. + randIndex := a.rand.Intn(len(bucket)) + for _, ka := range bucket { + if randIndex == 0 { + return ka.Addr + } + randIndex-- + } + PanicSanity("Should not happen") + } + return nil +} + +func (a *AddrBook) MarkGood(addr *NetAddress) { + a.mtx.Lock() + defer a.mtx.Unlock() + ka := a.addrLookup[addr.String()] + if ka == nil { + return + } + ka.markGood() + if ka.isNew() { + a.moveToOld(ka) + } +} + +func (a *AddrBook) MarkAttempt(addr *NetAddress) { + a.mtx.Lock() + defer a.mtx.Unlock() + ka := a.addrLookup[addr.String()] + if ka == nil { + return + } + ka.markAttempt() +} + +func (a *AddrBook) MarkBad(addr *NetAddress) { + a.mtx.Lock() + defer a.mtx.Unlock() + ka := a.addrLookup[addr.String()] + if ka == nil { + return + } + // We currently just eject the address. + // In the future, consider blacklisting. + a.removeFromAllBuckets(ka) +} + +/* Peer exchange */ + +// GetSelection randomly selects some addresses (old & new). Suitable for peer-exchange protocols. +func (a *AddrBook) GetSelection() []*NetAddress { + a.mtx.Lock() + defer a.mtx.Unlock() + + if a.size() == 0 { + return nil + } + + allAddr := make([]*NetAddress, a.size()) + i := 0 + for _, v := range a.addrLookup { + allAddr[i] = v.Addr + i++ + } + + numAddresses := MaxInt( + MinInt(minGetSelection, len(allAddr)), + len(allAddr)*getSelectionPercent/100) + numAddresses = MinInt(maxGetSelection, numAddresses) + + // Fisher-Yates shuffle the array. We only need to do the first + // `numAddresses' since we are throwing the rest. + for i := 0; i < numAddresses; i++ { + // pick a number between current index and the end + j := rand.Intn(len(allAddr)-i) + i + allAddr[i], allAddr[j] = allAddr[j], allAddr[i] + } + + // slice off the limit we are willing to share. + return allAddr[:numAddresses] +} + +/* Loading & Saving */ + +type addrBookJSON struct { + Key string + Addrs []*knownAddress +} + +func (a *AddrBook) saveToFile(filePath string) { + // Compile Addrs + addrs := []*knownAddress{} + for _, ka := range a.addrLookup { + addrs = append(addrs, ka) + } + + aJSON := &addrBookJSON{ + Key: a.key, + Addrs: addrs, + } + + jsonBytes, err := json.MarshalIndent(aJSON, "", "\t") + if err != nil { + log.Error("Failed to save AddrBook to file", "err", err) + return + } + err = WriteFileAtomic(filePath, jsonBytes) + if err != nil { + log.Error("Failed to save AddrBook to file", "file", filePath, "error", err) + } +} + +// Returns false if file does not exist. +// Panics if file is corrupt. +func (a *AddrBook) loadFromFile(filePath string) bool { + // If doesn't exist, do nothing. + _, err := os.Stat(filePath) + if os.IsNotExist(err) { + return false + } + + // Load addrBookJSON{} + r, err := os.Open(filePath) + if err != nil { + PanicCrisis(Fmt("Error opening file %s: %v", filePath, err)) + } + defer r.Close() + aJSON := &addrBookJSON{} + dec := json.NewDecoder(r) + err = dec.Decode(aJSON) + if err != nil { + PanicCrisis(Fmt("Error reading file %s: %v", filePath, err)) + } + + // Restore all the fields... + // Restore the key + a.key = aJSON.Key + // Restore .addrNew & .addrOld + for _, ka := range aJSON.Addrs { + for _, bucketIndex := range ka.Buckets { + bucket := a.getBucket(ka.BucketType, bucketIndex) + bucket[ka.Addr.String()] = ka + } + a.addrLookup[ka.Addr.String()] = ka + if ka.BucketType == bucketTypeNew { + a.nNew++ + } else { + a.nOld++ + } + } + return true +} + +/* Private methods */ + +func (a *AddrBook) saveRoutine() { + dumpAddressTicker := time.NewTicker(dumpAddressInterval) +out: + for { + select { + case <-dumpAddressTicker.C: + log.Info("Saving AddrBook to file", "size", a.Size()) + a.saveToFile(a.filePath) + case <-a.Quit: + break out + } + } + dumpAddressTicker.Stop() + a.saveToFile(a.filePath) + a.wg.Done() + log.Notice("Address handler done") +} + +func (a *AddrBook) getBucket(bucketType byte, bucketIdx int) map[string]*knownAddress { + switch bucketType { + case bucketTypeNew: + return a.addrNew[bucketIdx] + case bucketTypeOld: + return a.addrOld[bucketIdx] + default: + PanicSanity("Should not happen") + return nil + } +} + +// Adds ka to new bucket. Returns false if it couldn't do it cuz buckets full. +// NOTE: currently it always returns true. +func (a *AddrBook) addToNewBucket(ka *knownAddress, bucketIdx int) bool { + // Sanity check + if ka.isOld() { + log.Warn(Fmt("Cannot add address already in old bucket to a new bucket: %v", ka)) + return false + } + + addrStr := ka.Addr.String() + bucket := a.getBucket(bucketTypeNew, bucketIdx) + + // Already exists? + if _, ok := bucket[addrStr]; ok { + return true + } + + // Enforce max addresses. + if len(bucket) > newBucketSize { + log.Notice("new bucket is full, expiring old ") + a.expireNew(bucketIdx) + } + + // Add to bucket. + bucket[addrStr] = ka + if ka.addBucketRef(bucketIdx) == 1 { + a.nNew++ + } + + // Ensure in addrLookup + a.addrLookup[addrStr] = ka + + return true +} + +// Adds ka to old bucket. Returns false if it couldn't do it cuz buckets full. +func (a *AddrBook) addToOldBucket(ka *knownAddress, bucketIdx int) bool { + // Sanity check + if ka.isNew() { + log.Warn(Fmt("Cannot add new address to old bucket: %v", ka)) + return false + } + if len(ka.Buckets) != 0 { + log.Warn(Fmt("Cannot add already old address to another old bucket: %v", ka)) + return false + } + + addrStr := ka.Addr.String() + bucket := a.getBucket(bucketTypeNew, bucketIdx) + + // Already exists? + if _, ok := bucket[addrStr]; ok { + return true + } + + // Enforce max addresses. + if len(bucket) > oldBucketSize { + return false + } + + // Add to bucket. + bucket[addrStr] = ka + if ka.addBucketRef(bucketIdx) == 1 { + a.nOld++ + } + + // Ensure in addrLookup + a.addrLookup[addrStr] = ka + + return true +} + +func (a *AddrBook) removeFromBucket(ka *knownAddress, bucketType byte, bucketIdx int) { + if ka.BucketType != bucketType { + log.Warn(Fmt("Bucket type mismatch: %v", ka)) + return + } + bucket := a.getBucket(bucketType, bucketIdx) + delete(bucket, ka.Addr.String()) + if ka.removeBucketRef(bucketIdx) == 0 { + if bucketType == bucketTypeNew { + a.nNew-- + } else { + a.nOld-- + } + delete(a.addrLookup, ka.Addr.String()) + } +} + +func (a *AddrBook) removeFromAllBuckets(ka *knownAddress) { + for _, bucketIdx := range ka.Buckets { + bucket := a.getBucket(ka.BucketType, bucketIdx) + delete(bucket, ka.Addr.String()) + } + ka.Buckets = nil + if ka.BucketType == bucketTypeNew { + a.nNew-- + } else { + a.nOld-- + } + delete(a.addrLookup, ka.Addr.String()) +} + +func (a *AddrBook) pickOldest(bucketType byte, bucketIdx int) *knownAddress { + bucket := a.getBucket(bucketType, bucketIdx) + var oldest *knownAddress + for _, ka := range bucket { + if oldest == nil || ka.LastAttempt.Before(oldest.LastAttempt) { + oldest = ka + } + } + return oldest +} + +func (a *AddrBook) addAddress(addr, src *NetAddress) { + if !addr.Routable() { + log.Warn(Fmt("Cannot add non-routable address %v", addr)) + return + } + if _, ok := a.ourAddrs[addr.String()]; ok { + // Ignore our own listener address. + return + } + + ka := a.addrLookup[addr.String()] + + if ka != nil { + // Already old. + if ka.isOld() { + return + } + // Already in max new buckets. + if len(ka.Buckets) == maxNewBucketsPerAddress { + return + } + // The more entries we have, the less likely we are to add more. + factor := int32(2 * len(ka.Buckets)) + if a.rand.Int31n(factor) != 0 { + return + } + } else { + ka = newKnownAddress(addr, src) + } + + bucket := a.calcNewBucket(addr, src) + a.addToNewBucket(ka, bucket) + + log.Notice("Added new address", "address", addr, "total", a.size()) +} + +// Make space in the new buckets by expiring the really bad entries. +// If no bad entries are available we remove the oldest. +func (a *AddrBook) expireNew(bucketIdx int) { + for addrStr, ka := range a.addrNew[bucketIdx] { + // If an entry is bad, throw it away + if ka.isBad() { + log.Notice(Fmt("expiring bad address %v", addrStr)) + a.removeFromBucket(ka, bucketTypeNew, bucketIdx) + return + } + } + + // If we haven't thrown out a bad entry, throw out the oldest entry + oldest := a.pickOldest(bucketTypeNew, bucketIdx) + a.removeFromBucket(oldest, bucketTypeNew, bucketIdx) +} + +// Promotes an address from new to old. +// TODO: Move to old probabilistically. +// The better a node is, the less likely it should be evicted from an old bucket. +func (a *AddrBook) moveToOld(ka *knownAddress) { + // Sanity check + if ka.isOld() { + log.Warn(Fmt("Cannot promote address that is already old %v", ka)) + return + } + if len(ka.Buckets) == 0 { + log.Warn(Fmt("Cannot promote address that isn't in any new buckets %v", ka)) + return + } + + // Remember one of the buckets in which ka is in. + freedBucket := ka.Buckets[0] + // Remove from all (new) buckets. + a.removeFromAllBuckets(ka) + // It's officially old now. + ka.BucketType = bucketTypeOld + + // Try to add it to its oldBucket destination. + oldBucketIdx := a.calcOldBucket(ka.Addr) + added := a.addToOldBucket(ka, oldBucketIdx) + if !added { + // No room, must evict something + oldest := a.pickOldest(bucketTypeOld, oldBucketIdx) + a.removeFromBucket(oldest, bucketTypeOld, oldBucketIdx) + // Find new bucket to put oldest in + newBucketIdx := a.calcNewBucket(oldest.Addr, oldest.Src) + added := a.addToNewBucket(oldest, newBucketIdx) + // No space in newBucket either, just put it in freedBucket from above. + if !added { + added := a.addToNewBucket(oldest, freedBucket) + if !added { + log.Warn(Fmt("Could not migrate oldest %v to freedBucket %v", oldest, freedBucket)) + } + } + // Finally, add to bucket again. + added = a.addToOldBucket(ka, oldBucketIdx) + if !added { + log.Warn(Fmt("Could not re-add ka %v to oldBucketIdx %v", ka, oldBucketIdx)) + } + } +} + +// doublesha256( key + sourcegroup + +// int64(doublesha256(key + group + sourcegroup))%bucket_per_group ) % num_new_buckets +func (a *AddrBook) calcNewBucket(addr, src *NetAddress) int { + data1 := []byte{} + data1 = append(data1, []byte(a.key)...) + data1 = append(data1, []byte(groupKey(addr))...) + data1 = append(data1, []byte(groupKey(src))...) + hash1 := doubleSha256(data1) + hash64 := binary.BigEndian.Uint64(hash1) + hash64 %= newBucketsPerGroup + var hashbuf [8]byte + binary.BigEndian.PutUint64(hashbuf[:], hash64) + data2 := []byte{} + data2 = append(data2, []byte(a.key)...) + data2 = append(data2, groupKey(src)...) + data2 = append(data2, hashbuf[:]...) + + hash2 := doubleSha256(data2) + return int(binary.BigEndian.Uint64(hash2) % newBucketCount) +} + +// doublesha256( key + group + +// int64(doublesha256(key + addr))%buckets_per_group ) % num_old_buckets +func (a *AddrBook) calcOldBucket(addr *NetAddress) int { + data1 := []byte{} + data1 = append(data1, []byte(a.key)...) + data1 = append(data1, []byte(addr.String())...) + hash1 := doubleSha256(data1) + hash64 := binary.BigEndian.Uint64(hash1) + hash64 %= oldBucketsPerGroup + var hashbuf [8]byte + binary.BigEndian.PutUint64(hashbuf[:], hash64) + data2 := []byte{} + data2 = append(data2, []byte(a.key)...) + data2 = append(data2, groupKey(addr)...) + data2 = append(data2, hashbuf[:]...) + + hash2 := doubleSha256(data2) + return int(binary.BigEndian.Uint64(hash2) % oldBucketCount) +} + +// Return a string representing the network group of this address. +// This is the /16 for IPv6, the /32 (/36 for he.net) for IPv6, the string +// "local" for a local address and the string "unroutable for an unroutable +// address. +func groupKey(na *NetAddress) string { + if na.Local() { + return "local" + } + if !na.Routable() { + return "unroutable" + } + + if ipv4 := na.IP.To4(); ipv4 != nil { + return (&net.IPNet{IP: na.IP, Mask: net.CIDRMask(16, 32)}).String() + } + if na.RFC6145() || na.RFC6052() { + // last four bytes are the ip address + ip := net.IP(na.IP[12:16]) + return (&net.IPNet{IP: ip, Mask: net.CIDRMask(16, 32)}).String() + } + + if na.RFC3964() { + ip := net.IP(na.IP[2:7]) + return (&net.IPNet{IP: ip, Mask: net.CIDRMask(16, 32)}).String() + + } + if na.RFC4380() { + // teredo tunnels have the last 4 bytes as the v4 address XOR + // 0xff. + ip := net.IP(make([]byte, 4)) + for i, byte := range na.IP[12:16] { + ip[i] = byte ^ 0xff + } + return (&net.IPNet{IP: ip, Mask: net.CIDRMask(16, 32)}).String() + } + + // OK, so now we know ourselves to be a IPv6 address. + // bitcoind uses /32 for everything, except for Hurricane Electric's + // (he.net) IP range, which it uses /36 for. + bits := 32 + heNet := &net.IPNet{IP: net.ParseIP("2001:470::"), + Mask: net.CIDRMask(32, 128)} + if heNet.Contains(na.IP) { + bits = 36 + } + + return (&net.IPNet{IP: na.IP, Mask: net.CIDRMask(bits, 128)}).String() +} + +//----------------------------------------------------------------------------- + +/* + knownAddress + + tracks information about a known network address that is used + to determine how viable an address is. +*/ +type knownAddress struct { + Addr *NetAddress + Src *NetAddress + Attempts int32 + LastAttempt time.Time + LastSuccess time.Time + BucketType byte + Buckets []int +} + +func newKnownAddress(addr *NetAddress, src *NetAddress) *knownAddress { + return &knownAddress{ + Addr: addr, + Src: src, + Attempts: 0, + LastAttempt: time.Now(), + BucketType: bucketTypeNew, + Buckets: nil, + } +} + +func (ka *knownAddress) isOld() bool { + return ka.BucketType == bucketTypeOld +} + +func (ka *knownAddress) isNew() bool { + return ka.BucketType == bucketTypeNew +} + +func (ka *knownAddress) markAttempt() { + now := time.Now() + ka.LastAttempt = now + ka.Attempts += 1 +} + +func (ka *knownAddress) markGood() { + now := time.Now() + ka.LastAttempt = now + ka.Attempts = 0 + ka.LastSuccess = now +} + +func (ka *knownAddress) addBucketRef(bucketIdx int) int { + for _, bucket := range ka.Buckets { + if bucket == bucketIdx { + log.Warn(Fmt("Bucket already exists in ka.Buckets: %v", ka)) + return -1 + } + } + ka.Buckets = append(ka.Buckets, bucketIdx) + return len(ka.Buckets) +} + +func (ka *knownAddress) removeBucketRef(bucketIdx int) int { + buckets := []int{} + for _, bucket := range ka.Buckets { + if bucket != bucketIdx { + buckets = append(buckets, bucket) + } + } + if len(buckets) != len(ka.Buckets)-1 { + log.Warn(Fmt("bucketIdx not found in ka.Buckets: %v", ka)) + return -1 + } + ka.Buckets = buckets + return len(ka.Buckets) +} + +/* + An address is bad if the address in question has not been tried in the last + minute and meets one of the following criteria: + + 1) It claims to be from the future + 2) It hasn't been seen in over a month + 3) It has failed at least three times and never succeeded + 4) It has failed ten times in the last week + + All addresses that meet these criteria are assumed to be worthless and not + worth keeping hold of. +*/ +func (ka *knownAddress) isBad() bool { + // Has been attempted in the last minute --> good + if ka.LastAttempt.Before(time.Now().Add(-1 * time.Minute)) { + return false + } + + // Over a month old? + if ka.LastAttempt.After(time.Now().Add(-1 * numMissingDays * time.Hour * 24)) { + return true + } + + // Never succeeded? + if ka.LastSuccess.IsZero() && ka.Attempts >= numRetries { + return true + } + + // Hasn't succeeded in too long? + if ka.LastSuccess.Before(time.Now().Add(-1*minBadDays*time.Hour*24)) && + ka.Attempts >= maxFailures { + return true + } + + return false +} diff --git a/addrbook_test.go b/addrbook_test.go new file mode 100644 index 000000000..50986452e --- /dev/null +++ b/addrbook_test.go @@ -0,0 +1,161 @@ +package p2p + +import ( + "fmt" + "io/ioutil" + "math/rand" + "testing" +) + +func createTempFileName(prefix string) string { + f, err := ioutil.TempFile("", prefix) + if err != nil { + panic(err) + } + fname := f.Name() + err = f.Close() + if err != nil { + panic(err) + } + return fname +} + +func TestEmpty(t *testing.T) { + fname := createTempFileName("addrbook_test") + // t.Logf("New tempfile name: %v", fname) + + // Save an empty book & load it + book := NewAddrBook(fname) + book.saveToFile(fname) + + book = NewAddrBook(fname) + book.loadFromFile(fname) + + if book.Size() != 0 { + t.Errorf("Expected 0 addresses, found %v", book.Size()) + } +} + +func randIPv4Address() *NetAddress { + for { + ip := fmt.Sprintf("%v.%v.%v.%v", + rand.Intn(254)+1, + rand.Intn(255), + rand.Intn(255), + rand.Intn(255), + ) + port := rand.Intn(65535-1) + 1 + addr := NewNetAddressString(fmt.Sprintf("%v:%v", ip, port)) + if addr.Routable() { + return addr + } + } +} + +func TestSaveAddresses(t *testing.T) { + fname := createTempFileName("addrbook_test") + //t.Logf("New tempfile name: %v", fname) + + // Create some random addresses + randAddrs := []struct { + addr *NetAddress + src *NetAddress + }{} + for i := 0; i < 100; i++ { + addr := randIPv4Address() + src := randIPv4Address() + randAddrs = append(randAddrs, struct { + addr *NetAddress + src *NetAddress + }{ + addr: addr, + src: src, + }) + } + + // Create the book & populate & save + book := NewAddrBook(fname) + for _, addrSrc := range randAddrs { + book.AddAddress(addrSrc.addr, addrSrc.src) + } + if book.Size() != 100 { + t.Errorf("Expected 100 addresses, found %v", book.Size()) + } + book.saveToFile(fname) + + // Reload the book + book = NewAddrBook(fname) + book.loadFromFile(fname) + + // Test ... + + if book.Size() != 100 { + t.Errorf("Expected 100 addresses, found %v", book.Size()) + } + + for _, addrSrc := range randAddrs { + addr := addrSrc.addr + src := addrSrc.src + ka := book.addrLookup[addr.String()] + if ka == nil { + t.Fatalf("Expected to find KnownAddress %v but wasn't there.", addr) + } + if !(ka.Addr.Equals(addr) && ka.Src.Equals(src)) { + t.Fatalf("KnownAddress doesn't match addr & src") + } + } +} + +func TestPromoteToOld(t *testing.T) { + fname := createTempFileName("addrbook_test") + t.Logf("New tempfile name: %v", fname) + + // Create some random addresses + randAddrs := []struct { + addr *NetAddress + src *NetAddress + }{} + for i := 0; i < 100; i++ { + addr := randIPv4Address() + src := randIPv4Address() + randAddrs = append(randAddrs, struct { + addr *NetAddress + src *NetAddress + }{ + addr: addr, + src: src, + }) + } + + // Create the book & populate & save + book := NewAddrBook(fname) + for _, addrSrc := range randAddrs { + book.AddAddress(addrSrc.addr, addrSrc.src) + } + // Attempt all addresses. + for _, addrSrc := range randAddrs { + book.MarkAttempt(addrSrc.addr) + } + // Promote half of them + for i, addrSrc := range randAddrs { + if i%2 == 0 { + book.MarkGood(addrSrc.addr) + } + } + book.saveToFile(fname) + + // Reload the book + book = NewAddrBook(fname) + book.loadFromFile(fname) + + // Test ... + + if book.Size() != 100 { + t.Errorf("Expected 100 addresses, found %v", book.Size()) + } + + // TODO: do more testing :) + + selection := book.GetSelection() + t.Logf("selection: %v", selection) +} diff --git a/connection.go b/connection.go new file mode 100644 index 000000000..baa0dc1b4 --- /dev/null +++ b/connection.go @@ -0,0 +1,640 @@ +package p2p + +import ( + "bufio" + "fmt" + "io" + "math" + "net" + "runtime/debug" + "sync/atomic" + "time" + + flow "github.com/tendermint/flowcontrol" + . "github.com/tendermint/go-common" + "github.com/tendermint/go-wire" //"github.com/tendermint/log15" +) + +const ( + numBatchMsgPackets = 10 + minReadBufferSize = 1024 + minWriteBufferSize = 1024 + idleTimeoutMinutes = 5 + updateStatsSeconds = 2 + pingTimeoutSeconds = 40 + defaultSendRate = 51200 // 50Kb/s + defaultRecvRate = 51200 // 50Kb/s + flushThrottleMS = 100 + defaultSendQueueCapacity = 1 + defaultRecvBufferCapacity = 4096 + defaultSendTimeoutSeconds = 10 +) + +type receiveCbFunc func(chID byte, msgBytes []byte) +type errorCbFunc func(interface{}) + +/* +Each peer has one `MConnection` (multiplex connection) instance. + +__multiplex__ *noun* a system or signal involving simultaneous transmission of +several messages along a single channel of communication. + +Each `MConnection` handles message transmission on multiple abstract communication +`Channel`s. Each channel has a globally unique byte id. +The byte id and the relative priorities of each `Channel` are configured upon +initialization of the connection. + +There are two methods for sending messages: + func (m MConnection) Send(chID byte, msg interface{}) bool {} + func (m MConnection) TrySend(chID byte, msg interface{}) bool {} + +`Send(chID, msg)` is a blocking call that waits until `msg` is successfully queued +for the channel with the given id byte `chID`, or until the request times out. +The message `msg` is serialized using the `tendermint/wire` submodule's +`WriteBinary()` reflection routine. + +`TrySend(chID, msg)` is a nonblocking call that returns false if the channel's +queue is full. + +Inbound message bytes are handled with an onReceive callback function. +*/ +type MConnection struct { + BaseService + + conn net.Conn + bufReader *bufio.Reader + bufWriter *bufio.Writer + sendMonitor *flow.Monitor + recvMonitor *flow.Monitor + sendRate int64 + recvRate int64 + send chan struct{} + pong chan struct{} + channels []*Channel + channelsIdx map[byte]*Channel + onReceive receiveCbFunc + onError errorCbFunc + errored uint32 + + quit chan struct{} + flushTimer *ThrottleTimer // flush writes as necessary but throttled. + pingTimer *RepeatTimer // send pings periodically + chStatsTimer *RepeatTimer // update channel stats periodically + + LocalAddress *NetAddress + RemoteAddress *NetAddress +} + +func NewMConnection(conn net.Conn, chDescs []*ChannelDescriptor, onReceive receiveCbFunc, onError errorCbFunc) *MConnection { + + mconn := &MConnection{ + conn: conn, + bufReader: bufio.NewReaderSize(conn, minReadBufferSize), + bufWriter: bufio.NewWriterSize(conn, minWriteBufferSize), + sendMonitor: flow.New(0, 0), + recvMonitor: flow.New(0, 0), + sendRate: defaultSendRate, + recvRate: defaultRecvRate, + send: make(chan struct{}, 1), + pong: make(chan struct{}), + onReceive: onReceive, + onError: onError, + + // Initialized in Start() + quit: nil, + flushTimer: nil, + pingTimer: nil, + chStatsTimer: nil, + + LocalAddress: NewNetAddress(conn.LocalAddr()), + RemoteAddress: NewNetAddress(conn.RemoteAddr()), + } + + // Create channels + var channelsIdx = map[byte]*Channel{} + var channels = []*Channel{} + + for _, desc := range chDescs { + channel := newChannel(mconn, desc) + channelsIdx[channel.id] = channel + channels = append(channels, channel) + } + mconn.channels = channels + mconn.channelsIdx = channelsIdx + + mconn.BaseService = *NewBaseService(log, "MConnection", mconn) + + return mconn +} + +func (c *MConnection) OnStart() error { + c.BaseService.OnStart() + c.quit = make(chan struct{}) + c.flushTimer = NewThrottleTimer("flush", flushThrottleMS*time.Millisecond) + c.pingTimer = NewRepeatTimer("ping", pingTimeoutSeconds*time.Second) + c.chStatsTimer = NewRepeatTimer("chStats", updateStatsSeconds*time.Second) + go c.sendRoutine() + go c.recvRoutine() + return nil +} + +func (c *MConnection) OnStop() { + c.BaseService.OnStop() + c.flushTimer.Stop() + c.pingTimer.Stop() + c.chStatsTimer.Stop() + if c.quit != nil { + close(c.quit) + } + c.conn.Close() + // We can't close pong safely here because + // recvRoutine may write to it after we've stopped. + // Though it doesn't need to get closed at all, + // we close it @ recvRoutine. + // close(c.pong) +} + +func (c *MConnection) String() string { + return fmt.Sprintf("MConn{%v}", c.conn.RemoteAddr()) +} + +func (c *MConnection) flush() { + log.Debug("Flush", "conn", c) + err := c.bufWriter.Flush() + if err != nil { + log.Warn("MConnection flush failed", "error", err) + } +} + +// Catch panics, usually caused by remote disconnects. +func (c *MConnection) _recover() { + if r := recover(); r != nil { + stack := debug.Stack() + err := StackError{r, stack} + c.stopForError(err) + } +} + +func (c *MConnection) stopForError(r interface{}) { + c.Stop() + if atomic.CompareAndSwapUint32(&c.errored, 0, 1) { + if c.onError != nil { + c.onError(r) + } + } +} + +// Queues a message to be sent to channel. +func (c *MConnection) Send(chID byte, msg interface{}) bool { + if !c.IsRunning() { + return false + } + + log.Info("Send", "channel", chID, "conn", c, "msg", msg) //, "bytes", wire.BinaryBytes(msg)) + + // Send message to channel. + channel, ok := c.channelsIdx[chID] + if !ok { + log.Error(Fmt("Cannot send bytes, unknown channel %X", chID)) + return false + } + + success := channel.sendBytes(wire.BinaryBytes(msg)) + if success { + // Wake up sendRoutine if necessary + select { + case c.send <- struct{}{}: + default: + } + } else { + log.Warn("Send failed", "channel", chID, "conn", c, "msg", msg) + } + return success +} + +// Queues a message to be sent to channel. +// Nonblocking, returns true if successful. +func (c *MConnection) TrySend(chID byte, msg interface{}) bool { + if !c.IsRunning() { + return false + } + + log.Info("TrySend", "channel", chID, "conn", c, "msg", msg) + + // Send message to channel. + channel, ok := c.channelsIdx[chID] + if !ok { + log.Error(Fmt("Cannot send bytes, unknown channel %X", chID)) + return false + } + + ok = channel.trySendBytes(wire.BinaryBytes(msg)) + if ok { + // Wake up sendRoutine if necessary + select { + case c.send <- struct{}{}: + default: + } + } + + return ok +} + +func (c *MConnection) CanSend(chID byte) bool { + if !c.IsRunning() { + return false + } + + channel, ok := c.channelsIdx[chID] + if !ok { + log.Error(Fmt("Unknown channel %X", chID)) + return false + } + return channel.canSend() +} + +// sendRoutine polls for packets to send from channels. +func (c *MConnection) sendRoutine() { + defer c._recover() + +FOR_LOOP: + for { + var n int64 + var err error + select { + case <-c.flushTimer.Ch: + // NOTE: flushTimer.Set() must be called every time + // something is written to .bufWriter. + c.flush() + case <-c.chStatsTimer.Ch: + for _, channel := range c.channels { + channel.updateStats() + } + case <-c.pingTimer.Ch: + log.Info("Send Ping") + wire.WriteByte(packetTypePing, c.bufWriter, &n, &err) + c.sendMonitor.Update(int(n)) + c.flush() + case <-c.pong: + log.Info("Send Pong") + wire.WriteByte(packetTypePong, c.bufWriter, &n, &err) + c.sendMonitor.Update(int(n)) + c.flush() + case <-c.quit: + break FOR_LOOP + case <-c.send: + // Send some msgPackets + eof := c.sendSomeMsgPackets() + if !eof { + // Keep sendRoutine awake. + select { + case c.send <- struct{}{}: + default: + } + } + } + + if !c.IsRunning() { + break FOR_LOOP + } + if err != nil { + log.Warn("Connection failed @ sendRoutine", "conn", c, "error", err) + c.stopForError(err) + break FOR_LOOP + } + } + + // Cleanup +} + +// Returns true if messages from channels were exhausted. +// Blocks in accordance to .sendMonitor throttling. +func (c *MConnection) sendSomeMsgPackets() bool { + // Block until .sendMonitor says we can write. + // Once we're ready we send more than we asked for, + // but amortized it should even out. + c.sendMonitor.Limit(maxMsgPacketSize, atomic.LoadInt64(&c.sendRate), true) + + // Now send some msgPackets. + for i := 0; i < numBatchMsgPackets; i++ { + if c.sendMsgPacket() { + return true + } + } + return false +} + +// Returns true if messages from channels were exhausted. +func (c *MConnection) sendMsgPacket() bool { + // Choose a channel to create a msgPacket from. + // The chosen channel will be the one whose recentlySent/priority is the least. + var leastRatio float32 = math.MaxFloat32 + var leastChannel *Channel + for _, channel := range c.channels { + // If nothing to send, skip this channel + if !channel.isSendPending() { + continue + } + // Get ratio, and keep track of lowest ratio. + ratio := float32(channel.recentlySent) / float32(channel.priority) + if ratio < leastRatio { + leastRatio = ratio + leastChannel = channel + } + } + + // Nothing to send? + if leastChannel == nil { + return true + } else { + // log.Info("Found a msgPacket to send") + } + + // Make & send a msgPacket from this channel + n, err := leastChannel.writeMsgPacketTo(c.bufWriter) + if err != nil { + log.Warn("Failed to write msgPacket", "error", err) + c.stopForError(err) + return true + } + c.sendMonitor.Update(int(n)) + c.flushTimer.Set() + return false +} + +// recvRoutine reads msgPackets and reconstructs the message using the channels' "recving" buffer. +// After a whole message has been assembled, it's pushed to onReceive(). +// Blocks depending on how the connection is throttled. +func (c *MConnection) recvRoutine() { + defer c._recover() + +FOR_LOOP: + for { + // Block until .recvMonitor says we can read. + c.recvMonitor.Limit(maxMsgPacketSize, atomic.LoadInt64(&c.recvRate), true) + + /* + // Peek into bufReader for debugging + if numBytes := c.bufReader.Buffered(); numBytes > 0 { + log.Info("Peek connection buffer", "numBytes", numBytes, "bytes", log15.Lazy{func() []byte { + bytes, err := c.bufReader.Peek(MinInt(numBytes, 100)) + if err == nil { + return bytes + } else { + log.Warn("Error peeking connection buffer", "error", err) + return nil + } + }}) + } + */ + + // Read packet type + var n int64 + var err error + pktType := wire.ReadByte(c.bufReader, &n, &err) + c.recvMonitor.Update(int(n)) + if err != nil { + if c.IsRunning() { + log.Warn("Connection failed @ recvRoutine (reading byte)", "conn", c, "error", err) + c.stopForError(err) + } + break FOR_LOOP + } + + // Read more depending on packet type. + switch pktType { + case packetTypePing: + // TODO: prevent abuse, as they cause flush()'s. + log.Info("Receive Ping") + c.pong <- struct{}{} + case packetTypePong: + // do nothing + log.Info("Receive Pong") + case packetTypeMsg: + pkt, n, err := msgPacket{}, int64(0), error(nil) + wire.ReadBinaryPtr(&pkt, c.bufReader, &n, &err) + c.recvMonitor.Update(int(n)) + if err != nil { + if c.IsRunning() { + log.Warn("Connection failed @ recvRoutine", "conn", c, "error", err) + c.stopForError(err) + } + break FOR_LOOP + } + channel, ok := c.channelsIdx[pkt.ChannelID] + if !ok || channel == nil { + PanicQ(Fmt("Unknown channel %X", pkt.ChannelID)) + } + msgBytes, err := channel.recvMsgPacket(pkt) + if err != nil { + if c.IsRunning() { + log.Warn("Connection failed @ recvRoutine", "conn", c, "error", err) + c.stopForError(err) + } + break FOR_LOOP + } + if msgBytes != nil { + log.Debug("Received bytes", "chID", pkt.ChannelID, "msgBytes", msgBytes) + c.onReceive(pkt.ChannelID, msgBytes) + } + default: + PanicSanity(Fmt("Unknown message type %X", pktType)) + } + + // TODO: shouldn't this go in the sendRoutine? + // Better to send a ping packet when *we* haven't sent anything for a while. + c.pingTimer.Reset() + } + + // Cleanup + close(c.pong) + for _ = range c.pong { + // Drain + } +} + +//----------------------------------------------------------------------------- + +type ChannelDescriptor struct { + ID byte + Priority int + SendQueueCapacity int + RecvBufferCapacity int +} + +func (chDesc *ChannelDescriptor) FillDefaults() { + if chDesc.SendQueueCapacity == 0 { + chDesc.SendQueueCapacity = defaultSendQueueCapacity + } + if chDesc.RecvBufferCapacity == 0 { + chDesc.RecvBufferCapacity = defaultRecvBufferCapacity + } +} + +// TODO: lowercase. +// NOTE: not goroutine-safe. +type Channel struct { + conn *MConnection + desc *ChannelDescriptor + id byte + sendQueue chan []byte + sendQueueSize int32 // atomic. + recving []byte + sending []byte + priority int + recentlySent int64 // exponential moving average +} + +func newChannel(conn *MConnection, desc *ChannelDescriptor) *Channel { + desc.FillDefaults() + if desc.Priority <= 0 { + PanicSanity("Channel default priority must be a postive integer") + } + return &Channel{ + conn: conn, + desc: desc, + id: desc.ID, + sendQueue: make(chan []byte, desc.SendQueueCapacity), + recving: make([]byte, 0, desc.RecvBufferCapacity), + priority: desc.Priority, + } +} + +// Queues message to send to this channel. +// Goroutine-safe +// Times out (and returns false) after defaultSendTimeoutSeconds +func (ch *Channel) sendBytes(bytes []byte) bool { + timeout := time.NewTimer(defaultSendTimeoutSeconds * time.Second) + select { + case <-timeout.C: + // timeout + return false + case ch.sendQueue <- bytes: + atomic.AddInt32(&ch.sendQueueSize, 1) + return true + } +} + +// Queues message to send to this channel. +// Nonblocking, returns true if successful. +// Goroutine-safe +func (ch *Channel) trySendBytes(bytes []byte) bool { + select { + case ch.sendQueue <- bytes: + atomic.AddInt32(&ch.sendQueueSize, 1) + return true + default: + return false + } +} + +// Goroutine-safe +func (ch *Channel) loadSendQueueSize() (size int) { + return int(atomic.LoadInt32(&ch.sendQueueSize)) +} + +// Goroutine-safe +// Use only as a heuristic. +func (ch *Channel) canSend() bool { + return ch.loadSendQueueSize() < defaultSendQueueCapacity +} + +// Returns true if any msgPackets are pending to be sent. +// Call before calling nextMsgPacket() +// Goroutine-safe +func (ch *Channel) isSendPending() bool { + if len(ch.sending) == 0 { + if len(ch.sendQueue) == 0 { + return false + } + ch.sending = <-ch.sendQueue + } + return true +} + +// Creates a new msgPacket to send. +// Not goroutine-safe +func (ch *Channel) nextMsgPacket() msgPacket { + packet := msgPacket{} + packet.ChannelID = byte(ch.id) + packet.Bytes = ch.sending[:MinInt(maxMsgPacketSize, len(ch.sending))] + if len(ch.sending) <= maxMsgPacketSize { + packet.EOF = byte(0x01) + ch.sending = nil + atomic.AddInt32(&ch.sendQueueSize, -1) // decrement sendQueueSize + } else { + packet.EOF = byte(0x00) + ch.sending = ch.sending[MinInt(maxMsgPacketSize, len(ch.sending)):] + } + return packet +} + +// Writes next msgPacket to w. +// Not goroutine-safe +func (ch *Channel) writeMsgPacketTo(w io.Writer) (n int64, err error) { + packet := ch.nextMsgPacket() + log.Debug("Write Msg Packet", "conn", ch.conn, "packet", packet) + wire.WriteByte(packetTypeMsg, w, &n, &err) + wire.WriteBinary(packet, w, &n, &err) + if err != nil { + ch.recentlySent += n + } + return +} + +// Handles incoming msgPackets. Returns a msg bytes if msg is complete. +// Not goroutine-safe +func (ch *Channel) recvMsgPacket(packet msgPacket) ([]byte, error) { + // log.Debug("Read Msg Packet", "conn", ch.conn, "packet", packet) + if wire.MaxBinaryReadSize < len(ch.recving)+len(packet.Bytes) { + return nil, wire.ErrBinaryReadSizeOverflow + } + ch.recving = append(ch.recving, packet.Bytes...) + if packet.EOF == byte(0x01) { + msgBytes := ch.recving + ch.recving = make([]byte, 0, defaultRecvBufferCapacity) + return msgBytes, nil + } + return nil, nil +} + +// Call this periodically to update stats for throttling purposes. +// Not goroutine-safe +func (ch *Channel) updateStats() { + // Exponential decay of stats. + // TODO: optimize. + ch.recentlySent = int64(float64(ch.recentlySent) * 0.5) +} + +//----------------------------------------------------------------------------- + +const ( + maxMsgPacketSize = 1024 + packetTypePing = byte(0x01) + packetTypePong = byte(0x02) + packetTypeMsg = byte(0x03) +) + +// Messages in channels are chopped into smaller msgPackets for multiplexing. +type msgPacket struct { + ChannelID byte + EOF byte // 1 means message ends here. + Bytes []byte +} + +func (p msgPacket) String() string { + return fmt.Sprintf("MsgPacket{%X:%X T:%X}", p.ChannelID, p.Bytes, p.EOF) +} + +//----------------------------------------------------------------------------- + +// Convenience struct for writing typed messages. +// Reading requires a custom decoder that switches on the first type byte of a byteslice. +type TypedMessage struct { + Type byte + Msg interface{} +} + +func (tm TypedMessage) String() string { + return fmt.Sprintf("TMsg{%X:%v}", tm.Type, tm.Msg) +} diff --git a/listener.go b/listener.go new file mode 100644 index 000000000..1d7fb9569 --- /dev/null +++ b/listener.go @@ -0,0 +1,213 @@ +package p2p + +import ( + "fmt" + "net" + "strconv" + "time" + + . "github.com/tendermint/go-common" + "github.com/tendermint/go-p2p/upnp" +) + +type Listener interface { + Connections() <-chan net.Conn + InternalAddress() *NetAddress + ExternalAddress() *NetAddress + String() string + Stop() bool +} + +// Implements Listener +type DefaultListener struct { + BaseService + + listener net.Listener + intAddr *NetAddress + extAddr *NetAddress + connections chan net.Conn +} + +const ( + numBufferedConnections = 10 + defaultExternalPort = 8770 + tryListenSeconds = 5 +) + +func splitHostPort(addr string) (host string, port int) { + host, portStr, err := net.SplitHostPort(addr) + if err != nil { + PanicSanity(err) + } + port, err = strconv.Atoi(portStr) + if err != nil { + PanicSanity(err) + } + return host, port +} + +// skipUPNP: If true, does not try getUPNPExternalAddress() +func NewDefaultListener(protocol string, lAddr string, skipUPNP bool) Listener { + // Local listen IP & port + lAddrIP, lAddrPort := splitHostPort(lAddr) + + // Create listener + var listener net.Listener + var err error + for i := 0; i < tryListenSeconds; i++ { + listener, err = net.Listen(protocol, lAddr) + if err == nil { + break + } else if i < tryListenSeconds-1 { + time.Sleep(time.Second * 1) + } + } + if err != nil { + PanicCrisis(err) + } + // Actual listener local IP & port + listenerIP, listenerPort := splitHostPort(listener.Addr().String()) + log.Info("Local listener", "ip", listenerIP, "port", listenerPort) + + // Determine internal address... + var intAddr *NetAddress = NewNetAddressString(lAddr) + + // Determine external address... + var extAddr *NetAddress + if !skipUPNP { + // If the lAddrIP is INADDR_ANY, try UPnP + if lAddrIP == "" || lAddrIP == "0.0.0.0" { + extAddr = getUPNPExternalAddress(lAddrPort, listenerPort) + } + } + // Otherwise just use the local address... + if extAddr == nil { + extAddr = getNaiveExternalAddress(listenerPort) + } + if extAddr == nil { + PanicCrisis("Could not determine external address!") + } + + dl := &DefaultListener{ + listener: listener, + intAddr: intAddr, + extAddr: extAddr, + connections: make(chan net.Conn, numBufferedConnections), + } + dl.BaseService = *NewBaseService(log, "DefaultListener", dl) + dl.Start() // Started upon construction + return dl +} + +func (l *DefaultListener) OnStart() error { + l.BaseService.OnStart() + go l.listenRoutine() + return nil +} + +func (l *DefaultListener) OnStop() { + l.BaseService.OnStop() + l.listener.Close() +} + +// Accept connections and pass on the channel +func (l *DefaultListener) listenRoutine() { + for { + conn, err := l.listener.Accept() + + if !l.IsRunning() { + break // Go to cleanup + } + + // listener wasn't stopped, + // yet we encountered an error. + if err != nil { + PanicCrisis(err) + } + + l.connections <- conn + } + + // Cleanup + close(l.connections) + for _ = range l.connections { + // Drain + } +} + +// A channel of inbound connections. +// It gets closed when the listener closes. +func (l *DefaultListener) Connections() <-chan net.Conn { + return l.connections +} + +func (l *DefaultListener) InternalAddress() *NetAddress { + return l.intAddr +} + +func (l *DefaultListener) ExternalAddress() *NetAddress { + return l.extAddr +} + +// NOTE: The returned listener is already Accept()'ing. +// So it's not suitable to pass into http.Serve(). +func (l *DefaultListener) NetListener() net.Listener { + return l.listener +} + +func (l *DefaultListener) String() string { + return fmt.Sprintf("Listener(@%v)", l.extAddr) +} + +/* external address helpers */ + +// UPNP external address discovery & port mapping +func getUPNPExternalAddress(externalPort, internalPort int) *NetAddress { + log.Info("Getting UPNP external address") + nat, err := upnp.Discover() + if err != nil { + log.Info("Could not perform UPNP discover", "error", err) + return nil + } + + ext, err := nat.GetExternalAddress() + if err != nil { + log.Info("Could not get UPNP external address", "error", err) + return nil + } + + // UPnP can't seem to get the external port, so let's just be explicit. + if externalPort == 0 { + externalPort = defaultExternalPort + } + + externalPort, err = nat.AddPortMapping("tcp", externalPort, internalPort, "tendermint", 0) + if err != nil { + log.Info("Could not add UPNP port mapping", "error", err) + return nil + } + + log.Info("Got UPNP external address", "address", ext) + return NewNetAddressIPPort(ext, uint16(externalPort)) +} + +// TODO: use syscalls: http://pastebin.com/9exZG4rh +func getNaiveExternalAddress(port int) *NetAddress { + addrs, err := net.InterfaceAddrs() + if err != nil { + PanicCrisis(Fmt("Could not fetch interface addresses: %v", err)) + } + + for _, a := range addrs { + ipnet, ok := a.(*net.IPNet) + if !ok { + continue + } + v4 := ipnet.IP.To4() + if v4 == nil || v4[0] == 127 { + continue + } // loopback + return NewNetAddressIPPort(ipnet.IP, uint16(port)) + } + return nil +} diff --git a/log.go b/log.go new file mode 100644 index 000000000..ac1ff22a5 --- /dev/null +++ b/log.go @@ -0,0 +1,7 @@ +package p2p + +import ( + "github.com/tendermint/go-logger" +) + +var log = logger.New("module", "p2p") diff --git a/netaddress.go b/netaddress.go new file mode 100644 index 000000000..bdb42a004 --- /dev/null +++ b/netaddress.go @@ -0,0 +1,213 @@ +// Modified for Tendermint +// Originally Copyright (c) 2013-2014 Conformal Systems LLC. +// https://github.com/conformal/btcd/blob/master/LICENSE + +package p2p + +import ( + "fmt" + "net" + "strconv" + "time" + + . "github.com/tendermint/go-common" +) + +type NetAddress struct { + IP net.IP + Port uint16 + str string +} + +// TODO: socks proxies? +func NewNetAddress(addr net.Addr) *NetAddress { + tcpAddr, ok := addr.(*net.TCPAddr) + if !ok { + PanicSanity(fmt.Sprintf("Only TCPAddrs are supported. Got: %v", addr)) + } + ip := tcpAddr.IP + port := uint16(tcpAddr.Port) + return NewNetAddressIPPort(ip, port) +} + +// Also resolves the host if host is not an IP. +func NewNetAddressString(addr string) *NetAddress { + host, portStr, err := net.SplitHostPort(addr) + if err != nil { + PanicSanity(err) + } + ip := net.ParseIP(host) + if ip == nil { + if len(host) > 0 { + ips, err := net.LookupIP(host) + if err != nil { + PanicSanity(err) + } + ip = ips[0] + } + } + port, err := strconv.ParseUint(portStr, 10, 16) + if err != nil { + PanicSanity(err) + } + na := NewNetAddressIPPort(ip, uint16(port)) + return na +} + +func NewNetAddressIPPort(ip net.IP, port uint16) *NetAddress { + na := &NetAddress{ + IP: ip, + Port: port, + str: net.JoinHostPort( + ip.String(), + strconv.FormatUint(uint64(port), 10), + ), + } + return na +} + +func (na *NetAddress) Equals(other interface{}) bool { + if o, ok := other.(*NetAddress); ok { + return na.String() == o.String() + } else { + return false + } +} + +func (na *NetAddress) Less(other interface{}) bool { + if o, ok := other.(*NetAddress); ok { + return na.String() < o.String() + } else { + PanicSanity("Cannot compare unequal types") + return false + } +} + +func (na *NetAddress) String() string { + if na.str == "" { + na.str = net.JoinHostPort( + na.IP.String(), + strconv.FormatUint(uint64(na.Port), 10), + ) + } + return na.str +} + +func (na *NetAddress) Dial() (net.Conn, error) { + conn, err := net.Dial("tcp", na.String()) + if err != nil { + return nil, err + } + return conn, nil +} + +func (na *NetAddress) DialTimeout(timeout time.Duration) (net.Conn, error) { + conn, err := net.DialTimeout("tcp", na.String(), timeout) + if err != nil { + return nil, err + } + return conn, nil +} + +func (na *NetAddress) Routable() bool { + // TODO(oga) bitcoind doesn't include RFC3849 here, but should we? + return na.Valid() && !(na.RFC1918() || na.RFC3927() || na.RFC4862() || + na.RFC4193() || na.RFC4843() || na.Local()) +} + +// For IPv4 these are either a 0 or all bits set address. For IPv6 a zero +// address or one that matches the RFC3849 documentation address format. +func (na *NetAddress) Valid() bool { + return na.IP != nil && !(na.IP.IsUnspecified() || na.RFC3849() || + na.IP.Equal(net.IPv4bcast)) +} + +func (na *NetAddress) Local() bool { + return na.IP.IsLoopback() || zero4.Contains(na.IP) +} + +func (na *NetAddress) ReachabilityTo(o *NetAddress) int { + const ( + Unreachable = 0 + Default = iota + Teredo + Ipv6_weak + Ipv4 + Ipv6_strong + Private + ) + if !na.Routable() { + return Unreachable + } else if na.RFC4380() { + if !o.Routable() { + return Default + } else if o.RFC4380() { + return Teredo + } else if o.IP.To4() != nil { + return Ipv4 + } else { // ipv6 + return Ipv6_weak + } + } else if na.IP.To4() != nil { + if o.Routable() && o.IP.To4() != nil { + return Ipv4 + } + return Default + } else /* ipv6 */ { + var tunnelled bool + // Is our v6 is tunnelled? + if o.RFC3964() || o.RFC6052() || o.RFC6145() { + tunnelled = true + } + if !o.Routable() { + return Default + } else if o.RFC4380() { + return Teredo + } else if o.IP.To4() != nil { + return Ipv4 + } else if tunnelled { + // only prioritise ipv6 if we aren't tunnelling it. + return Ipv6_weak + } + return Ipv6_strong + } +} + +// RFC1918: IPv4 Private networks (10.0.0.0/8, 192.168.0.0/16, 172.16.0.0/12) +// RFC3849: IPv6 Documentation address (2001:0DB8::/32) +// RFC3927: IPv4 Autoconfig (169.254.0.0/16) +// RFC3964: IPv6 6to4 (2002::/16) +// RFC4193: IPv6 unique local (FC00::/7) +// RFC4380: IPv6 Teredo tunneling (2001::/32) +// RFC4843: IPv6 ORCHID: (2001:10::/28) +// RFC4862: IPv6 Autoconfig (FE80::/64) +// RFC6052: IPv6 well known prefix (64:FF9B::/96) +// RFC6145: IPv6 IPv4 translated address ::FFFF:0:0:0/96 +var rfc1918_10 = net.IPNet{IP: net.ParseIP("10.0.0.0"), Mask: net.CIDRMask(8, 32)} +var rfc1918_192 = net.IPNet{IP: net.ParseIP("192.168.0.0"), Mask: net.CIDRMask(16, 32)} +var rfc1918_172 = net.IPNet{IP: net.ParseIP("172.16.0.0"), Mask: net.CIDRMask(12, 32)} +var rfc3849 = net.IPNet{IP: net.ParseIP("2001:0DB8::"), Mask: net.CIDRMask(32, 128)} +var rfc3927 = net.IPNet{IP: net.ParseIP("169.254.0.0"), Mask: net.CIDRMask(16, 32)} +var rfc3964 = net.IPNet{IP: net.ParseIP("2002::"), Mask: net.CIDRMask(16, 128)} +var rfc4193 = net.IPNet{IP: net.ParseIP("FC00::"), Mask: net.CIDRMask(7, 128)} +var rfc4380 = net.IPNet{IP: net.ParseIP("2001::"), Mask: net.CIDRMask(32, 128)} +var rfc4843 = net.IPNet{IP: net.ParseIP("2001:10::"), Mask: net.CIDRMask(28, 128)} +var rfc4862 = net.IPNet{IP: net.ParseIP("FE80::"), Mask: net.CIDRMask(64, 128)} +var rfc6052 = net.IPNet{IP: net.ParseIP("64:FF9B::"), Mask: net.CIDRMask(96, 128)} +var rfc6145 = net.IPNet{IP: net.ParseIP("::FFFF:0:0:0"), Mask: net.CIDRMask(96, 128)} +var zero4 = net.IPNet{IP: net.ParseIP("0.0.0.0"), Mask: net.CIDRMask(8, 32)} + +func (na *NetAddress) RFC1918() bool { + return rfc1918_10.Contains(na.IP) || + rfc1918_192.Contains(na.IP) || + rfc1918_172.Contains(na.IP) +} +func (na *NetAddress) RFC3849() bool { return rfc3849.Contains(na.IP) } +func (na *NetAddress) RFC3927() bool { return rfc3927.Contains(na.IP) } +func (na *NetAddress) RFC3964() bool { return rfc3964.Contains(na.IP) } +func (na *NetAddress) RFC4193() bool { return rfc4193.Contains(na.IP) } +func (na *NetAddress) RFC4380() bool { return rfc4380.Contains(na.IP) } +func (na *NetAddress) RFC4843() bool { return rfc4843.Contains(na.IP) } +func (na *NetAddress) RFC4862() bool { return rfc4862.Contains(na.IP) } +func (na *NetAddress) RFC6052() bool { return rfc6052.Contains(na.IP) } +func (na *NetAddress) RFC6145() bool { return rfc6145.Contains(na.IP) } diff --git a/peer.go b/peer.go new file mode 100644 index 000000000..61e7cd688 --- /dev/null +++ b/peer.go @@ -0,0 +1,133 @@ +package p2p + +import ( + "fmt" + "io" + "net" + + . "github.com/tendermint/go-common" + "github.com/tendermint/go-wire" +) + +type Peer struct { + BaseService + + outbound bool + mconn *MConnection + + *NodeInfo + Key string + Data *CMap // User data. +} + +// NOTE: blocking +// Before creating a peer with newPeer(), perform a handshake on connection. +func peerHandshake(conn net.Conn, ourNodeInfo *NodeInfo) (*NodeInfo, error) { + var peerNodeInfo = new(NodeInfo) + var err1 error + var err2 error + Parallel( + func() { + var n int64 + wire.WriteBinary(ourNodeInfo, conn, &n, &err1) + }, + func() { + var n int64 + wire.ReadBinary(peerNodeInfo, conn, &n, &err2) + log.Notice("Peer handshake", "peerNodeInfo", peerNodeInfo) + }) + if err1 != nil { + return nil, err1 + } + if err2 != nil { + return nil, err2 + } + return peerNodeInfo, nil +} + +// NOTE: call peerHandshake on conn before calling newPeer(). +func newPeer(conn net.Conn, peerNodeInfo *NodeInfo, outbound bool, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{})) *Peer { + var p *Peer + onReceive := func(chID byte, msgBytes []byte) { + reactor := reactorsByCh[chID] + if reactor == nil { + PanicSanity(Fmt("Unknown channel %X", chID)) + } + reactor.Receive(chID, p, msgBytes) + } + onError := func(r interface{}) { + p.Stop() + onPeerError(p, r) + } + mconn := NewMConnection(conn, chDescs, onReceive, onError) + p = &Peer{ + outbound: outbound, + mconn: mconn, + NodeInfo: peerNodeInfo, + Key: peerNodeInfo.PubKey.KeyString(), + Data: NewCMap(), + } + p.BaseService = *NewBaseService(log, "Peer", p) + return p +} + +func (p *Peer) OnStart() error { + p.BaseService.OnStart() + _, err := p.mconn.Start() + return err +} + +func (p *Peer) OnStop() { + p.BaseService.OnStop() + p.mconn.Stop() +} + +func (p *Peer) Connection() *MConnection { + return p.mconn +} + +func (p *Peer) IsOutbound() bool { + return p.outbound +} + +func (p *Peer) Send(chID byte, msg interface{}) bool { + if !p.IsRunning() { + return false + } + return p.mconn.Send(chID, msg) +} + +func (p *Peer) TrySend(chID byte, msg interface{}) bool { + if !p.IsRunning() { + return false + } + return p.mconn.TrySend(chID, msg) +} + +func (p *Peer) CanSend(chID byte) bool { + if !p.IsRunning() { + return false + } + return p.mconn.CanSend(chID) +} + +func (p *Peer) WriteTo(w io.Writer) (n int64, err error) { + wire.WriteString(p.Key, w, &n, &err) + return +} + +func (p *Peer) String() string { + if p.outbound { + return fmt.Sprintf("Peer{%v %v out}", p.mconn, p.Key[:12]) + } else { + return fmt.Sprintf("Peer{%v %v in}", p.mconn, p.Key[:12]) + } +} + +func (p *Peer) Equals(other *Peer) bool { + return p.Key == other.Key +} + +func (p *Peer) Get(key string) interface{} { + return p.Data.Get(key) +} diff --git a/peer_set.go b/peer_set.go new file mode 100644 index 000000000..ccf26dc3b --- /dev/null +++ b/peer_set.go @@ -0,0 +1,227 @@ +package p2p + +import ( + "net" + "strings" + "sync" +) + +// IPeerSet has a (immutable) subset of the methods of PeerSet. +type IPeerSet interface { + Has(key string) bool + Get(key string) *Peer + List() []*Peer + Size() int +} + +//----------------------------------------------------------------------------- + +var ( + maxPeersPerIPRange = [4]int{11, 7, 5, 3} // ... +) + +// PeerSet is a special structure for keeping a table of peers. +// Iteration over the peers is super fast and thread-safe. +// We also track how many peers per IP range and avoid too many +type PeerSet struct { + mtx sync.Mutex + lookup map[string]*peerSetItem + list []*Peer + connectedIPs *nestedCounter +} + +type peerSetItem struct { + peer *Peer + index int +} + +func NewPeerSet() *PeerSet { + return &PeerSet{ + lookup: make(map[string]*peerSetItem), + list: make([]*Peer, 0, 256), + connectedIPs: NewNestedCounter(), + } +} + +// Returns false if peer with key (PubKeyEd25519) is already in set +// or if we have too many peers from the peer's IP range +func (ps *PeerSet) Add(peer *Peer) error { + ps.mtx.Lock() + defer ps.mtx.Unlock() + if ps.lookup[peer.Key] != nil { + return ErrSwitchDuplicatePeer + } + + // ensure we havent maxed out connections for the peer's IP range yet + // and update the IP range counters + if !ps.incrIPRangeCounts(peer.Host()) { + return ErrSwitchMaxPeersPerIPRange + } + + index := len(ps.list) + // Appending is safe even with other goroutines + // iterating over the ps.list slice. + ps.list = append(ps.list, peer) + ps.lookup[peer.Key] = &peerSetItem{peer, index} + return nil +} + +func (ps *PeerSet) Has(peerKey string) bool { + ps.mtx.Lock() + defer ps.mtx.Unlock() + _, ok := ps.lookup[peerKey] + return ok +} + +func (ps *PeerSet) Get(peerKey string) *Peer { + ps.mtx.Lock() + defer ps.mtx.Unlock() + item, ok := ps.lookup[peerKey] + if ok { + return item.peer + } else { + return nil + } +} + +func (ps *PeerSet) Remove(peer *Peer) { + ps.mtx.Lock() + defer ps.mtx.Unlock() + item := ps.lookup[peer.Key] + if item == nil { + return + } + + // update the IP range counters + ps.decrIPRangeCounts(peer.Host()) + + index := item.index + // Copy the list but without the last element. + // (we must copy because we're mutating the list) + newList := make([]*Peer, len(ps.list)-1) + copy(newList, ps.list) + // If it's the last peer, that's an easy special case. + if index == len(ps.list)-1 { + ps.list = newList + delete(ps.lookup, peer.Key) + return + } + + // Move the last item from ps.list to "index" in list. + lastPeer := ps.list[len(ps.list)-1] + lastPeerKey := lastPeer.Key + lastPeerItem := ps.lookup[lastPeerKey] + newList[index] = lastPeer + lastPeerItem.index = index + ps.list = newList + delete(ps.lookup, peer.Key) + +} + +func (ps *PeerSet) Size() int { + ps.mtx.Lock() + defer ps.mtx.Unlock() + return len(ps.list) +} + +// threadsafe list of peers. +func (ps *PeerSet) List() []*Peer { + ps.mtx.Lock() + defer ps.mtx.Unlock() + return ps.list +} + +//----------------------------------------------------------------------------- +// track the number of IPs we're connected to for each IP address range + +// forms an IP address hierarchy tree with counts +// the struct itself is not thread safe and should always only be accessed with the ps.mtx locked +type nestedCounter struct { + count int + children map[string]*nestedCounter +} + +func NewNestedCounter() *nestedCounter { + nc := new(nestedCounter) + nc.children = make(map[string]*nestedCounter) + return nc +} + +// Check if we have too many IPs in the IP range of the incoming connection +// Thread safe +func (ps *PeerSet) HasMaxForIPRange(conn net.Conn) (ok bool) { + ps.mtx.Lock() + defer ps.mtx.Unlock() + ip, _, _ := net.SplitHostPort(conn.RemoteAddr().String()) + ipBytes := strings.Split(ip, ".") + + c := ps.connectedIPs + for i, ipByte := range ipBytes { + if c, ok = c.children[ipByte]; !ok { + return false + } + if maxPeersPerIPRange[i] <= c.count { + return true + } + } + return false +} + +// Increments counts for this address' IP range +// Returns false if we already have enough connections +// Not thread safe (only called by ps.Add()) +func (ps *PeerSet) incrIPRangeCounts(address string) bool { + addrParts := strings.Split(address, ".") + + c := ps.connectedIPs + return incrNestedCounters(c, addrParts, 0) +} + +// Recursively descend the IP hierarchy, checking if we have +// max peers for each range and incrementing if not. +// Returns false if incr failed because max peers reached for some range counter. +func incrNestedCounters(c *nestedCounter, ipBytes []string, index int) bool { + ipByte := ipBytes[index] + child := c.children[ipByte] + if child == nil { + child = NewNestedCounter() + c.children[ipByte] = child + } + if index+1 < len(ipBytes) { + if !incrNestedCounters(child, ipBytes, index+1) { + return false + } + } + if maxPeersPerIPRange[index] <= child.count { + return false + } else { + child.count += 1 + return true + } +} + +// Decrement counts for this address' IP range +func (ps *PeerSet) decrIPRangeCounts(address string) { + addrParts := strings.Split(address, ".") + + c := ps.connectedIPs + decrNestedCounters(c, addrParts, 0) +} + +// Recursively descend the IP hierarchy, decrementing by one. +// If the counter is zero, deletes the child. +func decrNestedCounters(c *nestedCounter, ipBytes []string, index int) { + ipByte := ipBytes[index] + child := c.children[ipByte] + if child == nil { + log.Error("p2p/peer_set decrNestedCounters encountered a missing child counter") + return + } + if index+1 < len(ipBytes) { + decrNestedCounters(child, ipBytes, index+1) + } + child.count -= 1 + if child.count <= 0 { + delete(c.children, ipByte) + } +} diff --git a/peer_set_test.go b/peer_set_test.go new file mode 100644 index 000000000..1e16847c1 --- /dev/null +++ b/peer_set_test.go @@ -0,0 +1,168 @@ +package p2p + +import ( + "math/rand" + "strings" + "testing" + + . "github.com/tendermint/go-common" +) + +// Returns an empty dummy peer +func randPeer() *Peer { + return &Peer{ + Key: RandStr(12), + NodeInfo: &NodeInfo{ + Address: Fmt("%v.%v.%v.%v:46656", rand.Int()%256, rand.Int()%256, rand.Int()%256, rand.Int()%256), + }, + } +} + +func TestAddRemoveOne(t *testing.T) { + peerSet := NewPeerSet() + + peer := randPeer() + err := peerSet.Add(peer) + if err != nil { + t.Errorf("Failed to add new peer") + } + if peerSet.Size() != 1 { + t.Errorf("Failed to add new peer and increment size") + } + + peerSet.Remove(peer) + if peerSet.Has(peer.Key) { + t.Errorf("Failed to remove peer") + } + if peerSet.Size() != 0 { + t.Errorf("Failed to remove peer and decrement size") + } +} + +func TestAddRemoveMany(t *testing.T) { + peerSet := NewPeerSet() + + peers := []*Peer{} + N := 100 + maxPeersPerIPRange = [4]int{N, N, N, N} + for i := 0; i < N; i++ { + peer := randPeer() + if err := peerSet.Add(peer); err != nil { + t.Errorf("Failed to add new peer") + } + if peerSet.Size() != i+1 { + t.Errorf("Failed to add new peer and increment size") + } + peers = append(peers, peer) + } + + for i, peer := range peers { + peerSet.Remove(peer) + if peerSet.Has(peer.Key) { + t.Errorf("Failed to remove peer") + } + if peerSet.Size() != len(peers)-i-1 { + t.Errorf("Failed to remove peer and decrement size") + } + } +} + +func newPeerInIPRange(ipBytes ...string) *Peer { + ips := make([]string, 4) + for i, ipByte := range ipBytes { + ips[i] = ipByte + } + for i := len(ipBytes); i < 4; i++ { + ips[i] = Fmt("%v", rand.Int()%256) + } + ipS := strings.Join(ips, ".") + return &Peer{ + Key: RandStr(12), + NodeInfo: &NodeInfo{ + Address: ipS + ":46656", + }, + } +} + +func TestIPRanges(t *testing.T) { + peerSet := NewPeerSet() + + // test /8 + maxPeersPerIPRange = [4]int{2, 2, 2, 2} + peer := newPeerInIPRange("54", "1") + if err := peerSet.Add(peer); err != nil { + t.Errorf("Failed to add new peer") + } + peer = newPeerInIPRange("54", "2") + if err := peerSet.Add(peer); err != nil { + t.Errorf("Failed to add new peer") + } + peer = newPeerInIPRange("54", "3") + if err := peerSet.Add(peer); err == nil { + t.Errorf("Added peer when we shouldn't have") + } + peer = newPeerInIPRange("55", "1") + if err := peerSet.Add(peer); err != nil { + t.Errorf("Failed to add new peer") + } + + // test /16 + peerSet = NewPeerSet() + maxPeersPerIPRange = [4]int{3, 2, 1, 1} + peer = newPeerInIPRange("54", "112", "1") + if err := peerSet.Add(peer); err != nil { + t.Errorf("Failed to add new peer") + } + peer = newPeerInIPRange("54", "112", "2") + if err := peerSet.Add(peer); err != nil { + t.Errorf("Failed to add new peer") + } + peer = newPeerInIPRange("54", "112", "3") + if err := peerSet.Add(peer); err == nil { + t.Errorf("Added peer when we shouldn't have") + } + peer = newPeerInIPRange("54", "113", "1") + if err := peerSet.Add(peer); err != nil { + t.Errorf("Failed to add new peer") + } + + // test /24 + peerSet = NewPeerSet() + maxPeersPerIPRange = [4]int{5, 3, 2, 1} + peer = newPeerInIPRange("54", "112", "11", "1") + if err := peerSet.Add(peer); err != nil { + t.Errorf("Failed to add new peer") + } + peer = newPeerInIPRange("54", "112", "11", "2") + if err := peerSet.Add(peer); err != nil { + t.Errorf("Failed to add new peer") + } + peer = newPeerInIPRange("54", "112", "11", "3") + if err := peerSet.Add(peer); err == nil { + t.Errorf("Added peer when we shouldn't have") + } + peer = newPeerInIPRange("54", "112", "12", "1") + if err := peerSet.Add(peer); err != nil { + t.Errorf("Failed to add new peer") + } + + // test /32 + peerSet = NewPeerSet() + maxPeersPerIPRange = [4]int{11, 7, 5, 2} + peer = newPeerInIPRange("54", "112", "11", "10") + if err := peerSet.Add(peer); err != nil { + t.Errorf("Failed to add new peer") + } + peer = newPeerInIPRange("54", "112", "11", "10") + if err := peerSet.Add(peer); err != nil { + t.Errorf("Failed to add new peer") + } + peer = newPeerInIPRange("54", "112", "11", "10") + if err := peerSet.Add(peer); err == nil { + t.Errorf("Added peer when we shouldn't have") + } + peer = newPeerInIPRange("54", "112", "11", "11") + if err := peerSet.Add(peer); err != nil { + t.Errorf("Failed to add new peer") + } +} diff --git a/pex_reactor.go b/pex_reactor.go new file mode 100644 index 000000000..b6d8bf0e1 --- /dev/null +++ b/pex_reactor.go @@ -0,0 +1,255 @@ +package p2p + +import ( + "bytes" + "errors" + "fmt" + "math/rand" + "reflect" + "time" + + . "github.com/tendermint/go-common" + "github.com/tendermint/go-wire" +) + +var pexErrInvalidMessage = errors.New("Invalid PEX message") + +const ( + PexChannel = byte(0x00) + ensurePeersPeriodSeconds = 30 + minNumOutboundPeers = 10 +) + +/* +PEXReactor handles PEX (peer exchange) and ensures that an +adequate number of peers are connected to the switch. +*/ +type PEXReactor struct { + BaseReactor + + sw *Switch + book *AddrBook +} + +func NewPEXReactor(book *AddrBook) *PEXReactor { + pexR := &PEXReactor{ + book: book, + } + pexR.BaseReactor = *NewBaseReactor(log, "PEXReactor", pexR) + return pexR +} + +func (pexR *PEXReactor) OnStart() error { + pexR.BaseReactor.OnStart() + go pexR.ensurePeersRoutine() + return nil +} + +func (pexR *PEXReactor) OnStop() { + pexR.BaseReactor.OnStop() +} + +// Implements Reactor +func (pexR *PEXReactor) GetChannels() []*ChannelDescriptor { + return []*ChannelDescriptor{ + &ChannelDescriptor{ + ID: PexChannel, + Priority: 1, + SendQueueCapacity: 10, + }, + } +} + +// Implements Reactor +func (pexR *PEXReactor) AddPeer(peer *Peer) { + // Add the peer to the address book + netAddr := NewNetAddressString(peer.Address) + if peer.IsOutbound() { + if pexR.book.NeedMoreAddrs() { + pexR.RequestPEX(peer) + } + } else { + // For inbound connections, the peer is its own source + // (For outbound peers, the address is already in the books) + pexR.book.AddAddress(netAddr, netAddr) + } +} + +// Implements Reactor +func (pexR *PEXReactor) RemovePeer(peer *Peer, reason interface{}) { + // TODO +} + +// Implements Reactor +// Handles incoming PEX messages. +func (pexR *PEXReactor) Receive(chID byte, src *Peer, msgBytes []byte) { + + // decode message + _, msg, err := DecodeMessage(msgBytes) + if err != nil { + log.Warn("Error decoding message", "error", err) + return + } + log.Notice("Received message", "msg", msg) + + switch msg := msg.(type) { + case *pexRequestMessage: + // src requested some peers. + // TODO: prevent abuse. + pexR.SendAddrs(src, pexR.book.GetSelection()) + case *pexAddrsMessage: + // We received some peer addresses from src. + // TODO: prevent abuse. + // (We don't want to get spammed with bad peers) + srcAddr := src.Connection().RemoteAddress + for _, addr := range msg.Addrs { + pexR.book.AddAddress(addr, srcAddr) + } + default: + log.Warn(Fmt("Unknown message type %v", reflect.TypeOf(msg))) + } + +} + +// Asks peer for more addresses. +func (pexR *PEXReactor) RequestPEX(peer *Peer) { + peer.Send(PexChannel, &pexRequestMessage{}) +} + +func (pexR *PEXReactor) SendAddrs(peer *Peer, addrs []*NetAddress) { + peer.Send(PexChannel, &pexAddrsMessage{Addrs: addrs}) +} + +// Ensures that sufficient peers are connected. (continuous) +func (pexR *PEXReactor) ensurePeersRoutine() { + // Randomize when routine starts + time.Sleep(time.Duration(rand.Int63n(500*ensurePeersPeriodSeconds)) * time.Millisecond) + + // fire once immediately. + pexR.ensurePeers() + // fire periodically + timer := NewRepeatTimer("pex", ensurePeersPeriodSeconds*time.Second) +FOR_LOOP: + for { + select { + case <-timer.Ch: + pexR.ensurePeers() + case <-pexR.Quit: + break FOR_LOOP + } + } + + // Cleanup + timer.Stop() +} + +// Ensures that sufficient peers are connected. (once) +func (pexR *PEXReactor) ensurePeers() { + numOutPeers, _, numDialing := pexR.Switch.NumPeers() + numToDial := minNumOutboundPeers - (numOutPeers + numDialing) + log.Info("Ensure peers", "numOutPeers", numOutPeers, "numDialing", numDialing, "numToDial", numToDial) + if numToDial <= 0 { + return + } + toDial := NewCMap() + + // Try to pick numToDial addresses to dial. + // TODO: improve logic. + for i := 0; i < numToDial; i++ { + newBias := MinInt(numOutPeers, 8)*10 + 10 + var picked *NetAddress + // Try to fetch a new peer 3 times. + // This caps the maximum number of tries to 3 * numToDial. + for j := 0; j < 3; j++ { + try := pexR.book.PickAddress(newBias) + if try == nil { + break + } + alreadySelected := toDial.Has(try.IP.String()) + alreadyDialing := pexR.Switch.IsDialing(try) + alreadyConnected := pexR.Switch.Peers().Has(try.IP.String()) + if alreadySelected || alreadyDialing || alreadyConnected { + /* + log.Info("Cannot dial address", "addr", try, + "alreadySelected", alreadySelected, + "alreadyDialing", alreadyDialing, + "alreadyConnected", alreadyConnected) + */ + continue + } else { + log.Info("Will dial address", "addr", try) + picked = try + break + } + } + if picked == nil { + continue + } + toDial.Set(picked.IP.String(), picked) + } + + // Dial picked addresses + for _, item := range toDial.Values() { + go func(picked *NetAddress) { + _, err := pexR.Switch.DialPeerWithAddress(picked) + if err != nil { + pexR.book.MarkAttempt(picked) + } + }(item.(*NetAddress)) + } + + // If we need more addresses, pick a random peer and ask for more. + if pexR.book.NeedMoreAddrs() { + if peers := pexR.Switch.Peers().List(); len(peers) > 0 { + i := rand.Int() % len(peers) + peer := peers[i] + log.Info("No addresses to dial. Sending pexRequest to random peer", "peer", peer) + pexR.RequestPEX(peer) + } + } +} + +//----------------------------------------------------------------------------- +// Messages + +const ( + msgTypeRequest = byte(0x01) + msgTypeAddrs = byte(0x02) +) + +type PexMessage interface{} + +var _ = wire.RegisterInterface( + struct{ PexMessage }{}, + wire.ConcreteType{&pexRequestMessage{}, msgTypeRequest}, + wire.ConcreteType{&pexAddrsMessage{}, msgTypeAddrs}, +) + +func DecodeMessage(bz []byte) (msgType byte, msg PexMessage, err error) { + msgType = bz[0] + n := new(int64) + r := bytes.NewReader(bz) + msg = wire.ReadBinary(struct{ PexMessage }{}, r, n, &err).(struct{ PexMessage }).PexMessage + return +} + +/* +A pexRequestMessage requests additional peer addresses. +*/ +type pexRequestMessage struct { +} + +func (m *pexRequestMessage) String() string { + return "[pexRequest]" +} + +/* +A message with announced peer addresses. +*/ +type pexAddrsMessage struct { + Addrs []*NetAddress +} + +func (m *pexAddrsMessage) String() string { + return fmt.Sprintf("[pexAddrs %v]", m.Addrs) +} diff --git a/secret_connection.go b/secret_connection.go new file mode 100644 index 000000000..bec465e62 --- /dev/null +++ b/secret_connection.go @@ -0,0 +1,346 @@ +// Uses nacl's secret_box to encrypt a net.Conn. +// It is (meant to be) an implementation of the STS protocol. +// Note we do not (yet) assume that a remote peer's pubkey +// is known ahead of time, and thus we are technically +// still vulnerable to MITM. (TODO!) +// See docs/sts-final.pdf for more info +package p2p + +import ( + "bytes" + crand "crypto/rand" + "crypto/sha256" + "encoding/binary" + "errors" + "io" + "net" + "time" + + "golang.org/x/crypto/nacl/box" + "golang.org/x/crypto/nacl/secretbox" + "golang.org/x/crypto/ripemd160" + + . "github.com/tendermint/go-common" + "github.com/tendermint/go-crypto" + "github.com/tendermint/go-wire" +) + +// 2 + 1024 == 1026 total frame size +const dataLenSize = 2 // uint16 to describe the length, is <= dataMaxSize +const dataMaxSize = 1024 +const totalFrameSize = dataMaxSize + dataLenSize +const sealedFrameSize = totalFrameSize + secretbox.Overhead +const authSigMsgSize = (32 + 1) + (64 + 1) // fixed size (length prefixed) byte arrays + +// Implements net.Conn +type SecretConnection struct { + conn io.ReadWriteCloser + recvBuffer []byte + recvNonce *[24]byte + sendNonce *[24]byte + remPubKey crypto.PubKeyEd25519 + shrSecret *[32]byte // shared secret +} + +// Performs handshake and returns a new authenticated SecretConnection. +// Returns nil if error in handshake. +// Caller should call conn.Close() +// See docs/sts-final.pdf for more information. +func MakeSecretConnection(conn io.ReadWriteCloser, locPrivKey crypto.PrivKeyEd25519) (*SecretConnection, error) { + + locPubKey := locPrivKey.PubKey().(crypto.PubKeyEd25519) + + // Generate ephemeral keys for perfect forward secrecy. + locEphPub, locEphPriv := genEphKeys() + + // Write local ephemeral pubkey and receive one too. + // NOTE: every 32-byte string is accepted as a Curve25519 public key + // (see DJB's Curve25519 paper: http://cr.yp.to/ecdh/curve25519-20060209.pdf) + remEphPub, err := shareEphPubKey(conn, locEphPub) + if err != nil { + return nil, err + } + + // Compute common shared secret. + shrSecret := computeSharedSecret(remEphPub, locEphPriv) + + // Sort by lexical order. + loEphPub, hiEphPub := sort32(locEphPub, remEphPub) + + // Generate nonces to use for secretbox. + recvNonce, sendNonce := genNonces(loEphPub, hiEphPub, locEphPub == loEphPub) + + // Generate common challenge to sign. + challenge := genChallenge(loEphPub, hiEphPub) + + // Construct SecretConnection. + sc := &SecretConnection{ + conn: conn, + recvBuffer: nil, + recvNonce: recvNonce, + sendNonce: sendNonce, + shrSecret: shrSecret, + } + + // Sign the challenge bytes for authentication. + locSignature := signChallenge(challenge, locPrivKey) + + // Share (in secret) each other's pubkey & challenge signature + authSigMsg, err := shareAuthSignature(sc, locPubKey, locSignature) + if err != nil { + return nil, err + } + remPubKey, remSignature := authSigMsg.Key, authSigMsg.Sig + if !remPubKey.VerifyBytes(challenge[:], remSignature) { + return nil, errors.New("Challenge verification failed") + } + + // We've authorized. + sc.remPubKey = remPubKey + return sc, nil +} + +// Returns authenticated remote pubkey +func (sc *SecretConnection) RemotePubKey() crypto.PubKeyEd25519 { + return sc.remPubKey +} + +// Writes encrypted frames of `sealedFrameSize` +// CONTRACT: data smaller than dataMaxSize is read atomically. +func (sc *SecretConnection) Write(data []byte) (n int, err error) { + for 0 < len(data) { + var frame []byte = make([]byte, totalFrameSize) + var chunk []byte + if dataMaxSize < len(data) { + chunk = data[:dataMaxSize] + data = data[dataMaxSize:] + } else { + chunk = data + data = nil + } + chunkLength := len(chunk) + binary.BigEndian.PutUint16(frame, uint16(chunkLength)) + copy(frame[dataLenSize:], chunk) + + // encrypt the frame + var sealedFrame = make([]byte, sealedFrameSize) + secretbox.Seal(sealedFrame[:0], frame, sc.sendNonce, sc.shrSecret) + // fmt.Printf("secretbox.Seal(sealed:%X,sendNonce:%X,shrSecret:%X\n", sealedFrame, sc.sendNonce, sc.shrSecret) + incr2Nonce(sc.sendNonce) + // end encryption + + _, err := sc.conn.Write(sealedFrame) + if err != nil { + return n, err + } else { + n += len(chunk) + } + } + return +} + +// CONTRACT: data smaller than dataMaxSize is read atomically. +func (sc *SecretConnection) Read(data []byte) (n int, err error) { + if 0 < len(sc.recvBuffer) { + n_ := copy(data, sc.recvBuffer) + sc.recvBuffer = sc.recvBuffer[n_:] + return + } + + sealedFrame := make([]byte, sealedFrameSize) + _, err = io.ReadFull(sc.conn, sealedFrame) + if err != nil { + return + } + + // decrypt the frame + var frame = make([]byte, totalFrameSize) + // fmt.Printf("secretbox.Open(sealed:%X,recvNonce:%X,shrSecret:%X\n", sealedFrame, sc.recvNonce, sc.shrSecret) + _, ok := secretbox.Open(frame[:0], sealedFrame, sc.recvNonce, sc.shrSecret) + if !ok { + return n, errors.New("Failed to decrypt SecretConnection") + } + incr2Nonce(sc.recvNonce) + // end decryption + + var chunkLength = binary.BigEndian.Uint16(frame) // read the first two bytes + if chunkLength > dataMaxSize { + return 0, errors.New("chunkLength is greater than dataMaxSize") + } + var chunk = frame[dataLenSize : dataLenSize+chunkLength] + + n = copy(data, chunk) + sc.recvBuffer = chunk[n:] + return +} + +// Implements net.Conn +func (sc *SecretConnection) Close() error { return sc.conn.Close() } +func (sc *SecretConnection) LocalAddr() net.Addr { return sc.conn.(net.Conn).LocalAddr() } +func (sc *SecretConnection) RemoteAddr() net.Addr { return sc.conn.(net.Conn).RemoteAddr() } +func (sc *SecretConnection) SetDeadline(t time.Time) error { return sc.conn.(net.Conn).SetDeadline(t) } +func (sc *SecretConnection) SetReadDeadline(t time.Time) error { + return sc.conn.(net.Conn).SetReadDeadline(t) +} +func (sc *SecretConnection) SetWriteDeadline(t time.Time) error { + return sc.conn.(net.Conn).SetWriteDeadline(t) +} + +func genEphKeys() (ephPub, ephPriv *[32]byte) { + var err error + ephPub, ephPriv, err = box.GenerateKey(crand.Reader) + if err != nil { + PanicCrisis("Could not generate ephemeral keypairs") + } + return +} + +func shareEphPubKey(conn io.ReadWriteCloser, locEphPub *[32]byte) (remEphPub *[32]byte, err error) { + var err1, err2 error + + Parallel( + func() { + _, err1 = conn.Write(locEphPub[:]) + }, + func() { + remEphPub = new([32]byte) + _, err2 = io.ReadFull(conn, remEphPub[:]) + }, + ) + + if err1 != nil { + return nil, err1 + } + if err2 != nil { + return nil, err2 + } + + return remEphPub, nil +} + +func computeSharedSecret(remPubKey, locPrivKey *[32]byte) (shrSecret *[32]byte) { + shrSecret = new([32]byte) + box.Precompute(shrSecret, remPubKey, locPrivKey) + return +} + +func sort32(foo, bar *[32]byte) (lo, hi *[32]byte) { + if bytes.Compare(foo[:], bar[:]) < 0 { + lo = foo + hi = bar + } else { + lo = bar + hi = foo + } + return +} + +func genNonces(loPubKey, hiPubKey *[32]byte, locIsLo bool) (recvNonce, sendNonce *[24]byte) { + nonce1 := hash24(append(loPubKey[:], hiPubKey[:]...)) + nonce2 := new([24]byte) + copy(nonce2[:], nonce1[:]) + nonce2[len(nonce2)-1] ^= 0x01 + if locIsLo { + recvNonce = nonce1 + sendNonce = nonce2 + } else { + recvNonce = nonce2 + sendNonce = nonce1 + } + return +} + +func genChallenge(loPubKey, hiPubKey *[32]byte) (challenge *[32]byte) { + return hash32(append(loPubKey[:], hiPubKey[:]...)) +} + +func signChallenge(challenge *[32]byte, locPrivKey crypto.PrivKeyEd25519) (signature crypto.SignatureEd25519) { + signature = locPrivKey.Sign(challenge[:]).(crypto.SignatureEd25519) + return +} + +type authSigMessage struct { + Key crypto.PubKeyEd25519 + Sig crypto.SignatureEd25519 +} + +func shareAuthSignature(sc *SecretConnection, pubKey crypto.PubKeyEd25519, signature crypto.SignatureEd25519) (*authSigMessage, error) { + var recvMsg authSigMessage + var err1, err2 error + + Parallel( + func() { + msgBytes := wire.BinaryBytes(authSigMessage{pubKey, signature}) + _, err1 = sc.Write(msgBytes) + }, + func() { + readBuffer := make([]byte, authSigMsgSize) + _, err2 = io.ReadFull(sc, readBuffer) + if err2 != nil { + return + } + n := int64(0) // not used. + recvMsg = wire.ReadBinary(authSigMessage{}, bytes.NewBuffer(readBuffer), &n, &err2).(authSigMessage) + }) + + if err1 != nil { + return nil, err1 + } + if err2 != nil { + return nil, err2 + } + + return &recvMsg, nil +} + +func verifyChallengeSignature(challenge *[32]byte, remPubKey crypto.PubKeyEd25519, remSignature crypto.SignatureEd25519) bool { + return remPubKey.VerifyBytes(challenge[:], remSignature) +} + +//-------------------------------------------------------------------------------- + +// sha256 +func hash32(input []byte) (res *[32]byte) { + hasher := sha256.New() + hasher.Write(input) // does not error + resSlice := hasher.Sum(nil) + res = new([32]byte) + copy(res[:], resSlice) + return +} + +// We only fill in the first 20 bytes with ripemd160 +func hash24(input []byte) (res *[24]byte) { + hasher := ripemd160.New() + hasher.Write(input) // does not error + resSlice := hasher.Sum(nil) + res = new([24]byte) + copy(res[:], resSlice) + return +} + +// ripemd160 +func hash20(input []byte) (res *[20]byte) { + hasher := ripemd160.New() + hasher.Write(input) // does not error + resSlice := hasher.Sum(nil) + res = new([20]byte) + copy(res[:], resSlice) + return +} + +// increment nonce big-endian by 2 with wraparound. +func incr2Nonce(nonce *[24]byte) { + incrNonce(nonce) + incrNonce(nonce) +} + +// increment nonce big-endian by 1 with wraparound. +func incrNonce(nonce *[24]byte) { + for i := 23; 0 <= i; i-- { + nonce[i] += 1 + if nonce[i] != 0 { + return + } + } +} diff --git a/secret_connection_test.go b/secret_connection_test.go new file mode 100644 index 000000000..9bf1a7b1d --- /dev/null +++ b/secret_connection_test.go @@ -0,0 +1,202 @@ +package p2p + +import ( + "bytes" + "io" + "testing" + + . "github.com/tendermint/go-common" + "github.com/tendermint/go-crypto" +) + +type dummyConn struct { + *io.PipeReader + *io.PipeWriter +} + +func (drw dummyConn) Close() (err error) { + err2 := drw.PipeWriter.CloseWithError(io.EOF) + err1 := drw.PipeReader.Close() + if err2 != nil { + return err + } + return err1 +} + +// Each returned ReadWriteCloser is akin to a net.Connection +func makeDummyConnPair() (fooConn, barConn dummyConn) { + barReader, fooWriter := io.Pipe() + fooReader, barWriter := io.Pipe() + return dummyConn{fooReader, fooWriter}, dummyConn{barReader, barWriter} +} + +func makeSecretConnPair(tb testing.TB) (fooSecConn, barSecConn *SecretConnection) { + fooConn, barConn := makeDummyConnPair() + fooPrvKey := crypto.GenPrivKeyEd25519() + fooPubKey := fooPrvKey.PubKey().(crypto.PubKeyEd25519) + barPrvKey := crypto.GenPrivKeyEd25519() + barPubKey := barPrvKey.PubKey().(crypto.PubKeyEd25519) + + Parallel( + func() { + var err error + fooSecConn, err = MakeSecretConnection(fooConn, fooPrvKey) + if err != nil { + tb.Errorf("Failed to establish SecretConnection for foo: %v", err) + return + } + remotePubBytes := fooSecConn.RemotePubKey() + if !bytes.Equal(remotePubBytes[:], barPubKey[:]) { + tb.Errorf("Unexpected fooSecConn.RemotePubKey. Expected %v, got %v", + barPubKey, fooSecConn.RemotePubKey()) + } + }, + func() { + var err error + barSecConn, err = MakeSecretConnection(barConn, barPrvKey) + if barSecConn == nil { + tb.Errorf("Failed to establish SecretConnection for bar: %v", err) + return + } + remotePubBytes := barSecConn.RemotePubKey() + if !bytes.Equal(remotePubBytes[:], fooPubKey[:]) { + tb.Errorf("Unexpected barSecConn.RemotePubKey. Expected %v, got %v", + fooPubKey, barSecConn.RemotePubKey()) + } + }) + + return +} + +func TestSecretConnectionHandshake(t *testing.T) { + fooSecConn, barSecConn := makeSecretConnPair(t) + fooSecConn.Close() + barSecConn.Close() +} + +func TestSecretConnectionReadWrite(t *testing.T) { + fooConn, barConn := makeDummyConnPair() + fooWrites, barWrites := []string{}, []string{} + fooReads, barReads := []string{}, []string{} + + // Pre-generate the things to write (for foo & bar) + for i := 0; i < 100; i++ { + fooWrites = append(fooWrites, RandStr((RandInt()%(dataMaxSize*5))+1)) + barWrites = append(barWrites, RandStr((RandInt()%(dataMaxSize*5))+1)) + } + + // A helper that will run with (fooConn, fooWrites, fooReads) and vice versa + genNodeRunner := func(nodeConn dummyConn, nodeWrites []string, nodeReads *[]string) func() { + return func() { + // Node handskae + nodePrvKey := crypto.GenPrivKeyEd25519() + nodeSecretConn, err := MakeSecretConnection(nodeConn, nodePrvKey) + if err != nil { + t.Errorf("Failed to establish SecretConnection for node: %v", err) + return + } + // In parallel, handle reads and writes + Parallel( + func() { + // Node writes + for _, nodeWrite := range nodeWrites { + n, err := nodeSecretConn.Write([]byte(nodeWrite)) + if err != nil { + t.Errorf("Failed to write to nodeSecretConn: %v", err) + return + } + if n != len(nodeWrite) { + t.Errorf("Failed to write all bytes. Expected %v, wrote %v", len(nodeWrite), n) + return + } + } + nodeConn.PipeWriter.Close() + }, + func() { + // Node reads + readBuffer := make([]byte, dataMaxSize) + for { + n, err := nodeSecretConn.Read(readBuffer) + if err == io.EOF { + return + } else if err != nil { + t.Errorf("Failed to read from nodeSecretConn: %v", err) + return + } + *nodeReads = append(*nodeReads, string(readBuffer[:n])) + } + nodeConn.PipeReader.Close() + }) + } + } + + // Run foo & bar in parallel + Parallel( + genNodeRunner(fooConn, fooWrites, &fooReads), + genNodeRunner(barConn, barWrites, &barReads), + ) + + // A helper to ensure that the writes and reads match. + // Additionally, small writes (<= dataMaxSize) must be atomically read. + compareWritesReads := func(writes []string, reads []string) { + for { + // Pop next write & corresponding reads + var read, write string = "", writes[0] + var readCount = 0 + for _, readChunk := range reads { + read += readChunk + readCount += 1 + if len(write) <= len(read) { + break + } + if len(write) <= dataMaxSize { + break // atomicity of small writes + } + } + // Compare + if write != read { + t.Errorf("Expected to read %X, got %X", write, read) + } + // Iterate + writes = writes[1:] + reads = reads[readCount:] + if len(writes) == 0 { + break + } + } + } + + compareWritesReads(fooWrites, barReads) + compareWritesReads(barWrites, fooReads) + +} + +func BenchmarkSecretConnection(b *testing.B) { + b.StopTimer() + fooSecConn, barSecConn := makeSecretConnPair(b) + fooWriteText := RandStr(dataMaxSize) + // Consume reads from bar's reader + go func() { + readBuffer := make([]byte, dataMaxSize) + for { + _, err := barSecConn.Read(readBuffer) + if err == io.EOF { + return + } else if err != nil { + b.Fatalf("Failed to read from barSecConn: %v", err) + } + } + }() + + b.StartTimer() + for i := 0; i < b.N; i++ { + _, err := fooSecConn.Write([]byte(fooWriteText)) + if err != nil { + b.Fatalf("Failed to write to fooSecConn: %v", err) + } + } + b.StopTimer() + + fooSecConn.Close() + //barSecConn.Close() race condition +} diff --git a/switch.go b/switch.go new file mode 100644 index 000000000..409a0fa75 --- /dev/null +++ b/switch.go @@ -0,0 +1,384 @@ +package p2p + +import ( + "errors" + "fmt" + "net" + "time" + + . "github.com/tendermint/go-common" + "github.com/tendermint/go-crypto" + "github.com/tendermint/log15" +) + +type Reactor interface { + Service // Start, Stop + + SetSwitch(*Switch) + GetChannels() []*ChannelDescriptor + AddPeer(peer *Peer) + RemovePeer(peer *Peer, reason interface{}) + Receive(chID byte, peer *Peer, msgBytes []byte) +} + +//-------------------------------------- + +type BaseReactor struct { + QuitService // Provides Start, Stop, .Quit + Switch *Switch +} + +func NewBaseReactor(log log15.Logger, name string, impl Reactor) *BaseReactor { + return &BaseReactor{ + QuitService: *NewQuitService(log, name, impl), + Switch: nil, + } +} + +func (br *BaseReactor) SetSwitch(sw *Switch) { + br.Switch = sw +} +func (_ *BaseReactor) GetChannels() []*ChannelDescriptor { return nil } +func (_ *BaseReactor) AddPeer(peer *Peer) {} +func (_ *BaseReactor) RemovePeer(peer *Peer, reason interface{}) {} +func (_ *BaseReactor) Receive(chID byte, peer *Peer, msgBytes []byte) {} + +//----------------------------------------------------------------------------- + +/* +The `Switch` handles peer connections and exposes an API to receive incoming messages +on `Reactors`. Each `Reactor` is responsible for handling incoming messages of one +or more `Channels`. So while sending outgoing messages is typically performed on the peer, +incoming messages are received on the reactor. +*/ +type Switch struct { + BaseService + + listeners []Listener + reactors map[string]Reactor + chDescs []*ChannelDescriptor + reactorsByCh map[byte]Reactor + peers *PeerSet + dialing *CMap + nodeInfo *NodeInfo // our node info + nodePrivKey crypto.PrivKeyEd25519 // our node privkey +} + +var ( + ErrSwitchDuplicatePeer = errors.New("Duplicate peer") + ErrSwitchMaxPeersPerIPRange = errors.New("IP range has too many peers") +) + +const ( + peerDialTimeoutSeconds = 3 // TODO make this configurable + handshakeTimeoutSeconds = 20 // TODO make this configurable + maxNumPeers = 50 // TODO make this configurable +) + +func NewSwitch() *Switch { + sw := &Switch{ + reactors: make(map[string]Reactor), + chDescs: make([]*ChannelDescriptor, 0), + reactorsByCh: make(map[byte]Reactor), + peers: NewPeerSet(), + dialing: NewCMap(), + nodeInfo: nil, + } + sw.BaseService = *NewBaseService(log, "P2P Switch", sw) + return sw +} + +// Not goroutine safe. +func (sw *Switch) AddReactor(name string, reactor Reactor) Reactor { + // Validate the reactor. + // No two reactors can share the same channel. + reactorChannels := reactor.GetChannels() + for _, chDesc := range reactorChannels { + chID := chDesc.ID + if sw.reactorsByCh[chID] != nil { + PanicSanity(fmt.Sprintf("Channel %X has multiple reactors %v & %v", chID, sw.reactorsByCh[chID], reactor)) + } + sw.chDescs = append(sw.chDescs, chDesc) + sw.reactorsByCh[chID] = reactor + } + sw.reactors[name] = reactor + reactor.SetSwitch(sw) + return reactor +} + +// Not goroutine safe. +func (sw *Switch) Reactors() map[string]Reactor { + return sw.reactors +} + +// Not goroutine safe. +func (sw *Switch) Reactor(name string) Reactor { + return sw.reactors[name] +} + +// Not goroutine safe. +func (sw *Switch) AddListener(l Listener) { + sw.listeners = append(sw.listeners, l) +} + +// Not goroutine safe. +func (sw *Switch) Listeners() []Listener { + return sw.listeners +} + +// Not goroutine safe. +func (sw *Switch) IsListening() bool { + return len(sw.listeners) > 0 +} + +// Not goroutine safe. +func (sw *Switch) SetNodeInfo(nodeInfo *NodeInfo) { + sw.nodeInfo = nodeInfo +} + +// Not goroutine safe. +func (sw *Switch) NodeInfo() *NodeInfo { + return sw.nodeInfo +} + +// Not goroutine safe. +// NOTE: Overwrites sw.nodeInfo.PubKey +func (sw *Switch) SetNodePrivKey(nodePrivKey crypto.PrivKeyEd25519) { + sw.nodePrivKey = nodePrivKey + if sw.nodeInfo != nil { + sw.nodeInfo.PubKey = nodePrivKey.PubKey().(crypto.PubKeyEd25519) + } +} + +// Switch.Start() starts all the reactors, peers, and listeners. +func (sw *Switch) OnStart() error { + sw.BaseService.OnStart() + // Start reactors + for _, reactor := range sw.reactors { + _, err := reactor.Start() + if err != nil { + return err + } + } + // Start peers + for _, peer := range sw.peers.List() { + sw.startInitPeer(peer) + } + // Start listeners + for _, listener := range sw.listeners { + go sw.listenerRoutine(listener) + } + return nil +} + +func (sw *Switch) OnStop() { + sw.BaseService.OnStop() + // Stop listeners + for _, listener := range sw.listeners { + listener.Stop() + } + sw.listeners = nil + // Stop peers + for _, peer := range sw.peers.List() { + peer.Stop() + } + sw.peers = NewPeerSet() + // Stop reactors + for _, reactor := range sw.reactors { + reactor.Stop() + } +} + +// NOTE: This performs a blocking handshake before the peer is added. +// CONTRACT: Iff error is returned, peer is nil, and conn is immediately closed. +func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool) (*Peer, error) { + // Set deadline for handshake so we don't block forever on conn.ReadFull + conn.SetDeadline(time.Now().Add(handshakeTimeoutSeconds * time.Second)) + + // First, encrypt the connection. + sconn, err := MakeSecretConnection(conn, sw.nodePrivKey) + if err != nil { + conn.Close() + return nil, err + } + // Then, perform node handshake + peerNodeInfo, err := peerHandshake(sconn, sw.nodeInfo) + if err != nil { + sconn.Close() + return nil, err + } + // Check that the professed PubKey matches the sconn's. + if !peerNodeInfo.PubKey.Equals(sconn.RemotePubKey()) { + sconn.Close() + return nil, fmt.Errorf("Ignoring connection with unmatching pubkey: %v vs %v", + peerNodeInfo.PubKey, sconn.RemotePubKey()) + } + // Avoid self + if peerNodeInfo.PubKey.Equals(sw.nodeInfo.PubKey) { + sconn.Close() + return nil, fmt.Errorf("Ignoring connection from self") + } + // Check version, chain id + if err := sw.nodeInfo.CompatibleWith(peerNodeInfo); err != nil { + sconn.Close() + return nil, err + } + + // The peerNodeInfo is not verified, so overwrite + // the IP, and the port too if we dialed out + // Everything else we just have to trust + peerNodeInfo.Address = sconn.RemoteAddr().String() + peer := newPeer(sconn, peerNodeInfo, outbound, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError) + + // Add the peer to .peers + // ignore if duplicate or if we already have too many for that IP range + if err := sw.peers.Add(peer); err != nil { + log.Notice("Ignoring peer", "error", err, "peer", peer) + peer.Stop() + return nil, err + } + + // remove deadline and start peer + conn.SetDeadline(time.Time{}) + if sw.IsRunning() { + sw.startInitPeer(peer) + } + + log.Notice("Added peer", "peer", peer) + return peer, nil +} + +func (sw *Switch) startInitPeer(peer *Peer) { + peer.Start() // spawn send/recv routines + sw.addPeerToReactors(peer) // run AddPeer on each reactor +} + +func (sw *Switch) DialPeerWithAddress(addr *NetAddress) (*Peer, error) { + log.Info("Dialing address", "address", addr) + sw.dialing.Set(addr.IP.String(), addr) + conn, err := addr.DialTimeout(peerDialTimeoutSeconds * time.Second) + sw.dialing.Delete(addr.IP.String()) + if err != nil { + log.Info("Failed dialing address", "address", addr, "error", err) + return nil, err + } + peer, err := sw.AddPeerWithConnection(conn, true) + if err != nil { + log.Info("Failed adding peer", "address", addr, "conn", conn, "error", err) + return nil, err + } + log.Notice("Dialed and added peer", "address", addr, "peer", peer) + return peer, nil +} + +func (sw *Switch) IsDialing(addr *NetAddress) bool { + return sw.dialing.Has(addr.IP.String()) +} + +// Broadcast runs a go routine for each attempted send, which will block +// trying to send for defaultSendTimeoutSeconds. Returns a channel +// which receives success values for each attempted send (false if times out) +func (sw *Switch) Broadcast(chID byte, msg interface{}) chan bool { + successChan := make(chan bool, len(sw.peers.List())) + log.Info("Broadcast", "channel", chID, "msg", msg) + for _, peer := range sw.peers.List() { + go func(peer *Peer) { + success := peer.Send(chID, msg) + successChan <- success + }(peer) + } + return successChan +} + +// Returns the count of outbound/inbound and outbound-dialing peers. +func (sw *Switch) NumPeers() (outbound, inbound, dialing int) { + peers := sw.peers.List() + for _, peer := range peers { + if peer.outbound { + outbound++ + } else { + inbound++ + } + } + dialing = sw.dialing.Size() + return +} + +func (sw *Switch) Peers() IPeerSet { + return sw.peers +} + +// Disconnect from a peer due to external error. +// TODO: make record depending on reason. +func (sw *Switch) StopPeerForError(peer *Peer, reason interface{}) { + log.Notice("Stopping peer for error", "peer", peer, "error", reason) + sw.peers.Remove(peer) + peer.Stop() + sw.removePeerFromReactors(peer, reason) +} + +// Disconnect from a peer gracefully. +// TODO: handle graceful disconnects. +func (sw *Switch) StopPeerGracefully(peer *Peer) { + log.Notice("Stopping peer gracefully") + sw.peers.Remove(peer) + peer.Stop() + sw.removePeerFromReactors(peer, nil) +} + +func (sw *Switch) addPeerToReactors(peer *Peer) { + for _, reactor := range sw.reactors { + reactor.AddPeer(peer) + } +} + +func (sw *Switch) removePeerFromReactors(peer *Peer, reason interface{}) { + for _, reactor := range sw.reactors { + reactor.RemovePeer(peer, reason) + } +} + +func (sw *Switch) listenerRoutine(l Listener) { + for { + inConn, ok := <-l.Connections() + if !ok { + break + } + + // ignore connection if we already have enough + if maxNumPeers <= sw.peers.Size() { + log.Info("Ignoring inbound connection: already have enough peers", "address", inConn.RemoteAddr().String(), "numPeers", sw.peers.Size(), "max", maxNumPeers) + continue + } + + // Ignore connections from IP ranges for which we have too many + if sw.peers.HasMaxForIPRange(inConn) { + log.Info("Ignoring inbound connection: already have enough peers for that IP range", "address", inConn.RemoteAddr().String()) + continue + } + + // New inbound connection! + _, err := sw.AddPeerWithConnection(inConn, false) + if err != nil { + log.Notice("Ignoring inbound connection: error on AddPeerWithConnection", "address", inConn.RemoteAddr().String(), "error", err) + continue + } + + // NOTE: We don't yet have the listening port of the + // remote (if they have a listener at all). + // The peerHandshake will handle that + } + + // cleanup +} + +//----------------------------------------------------------------------------- + +type SwitchEventNewPeer struct { + Peer *Peer +} + +type SwitchEventDonePeer struct { + Peer *Peer + Error interface{} +} diff --git a/switch_test.go b/switch_test.go new file mode 100644 index 000000000..046649791 --- /dev/null +++ b/switch_test.go @@ -0,0 +1,234 @@ +package p2p + +import ( + "bytes" + "sync" + "testing" + "time" + + . "github.com/tendermint/go-common" + "github.com/tendermint/go-crypto" + "github.com/tendermint/go-wire" +) + +type PeerMessage struct { + PeerKey string + Bytes []byte + Counter int +} + +type TestReactor struct { + BaseReactor + + mtx sync.Mutex + channels []*ChannelDescriptor + peersAdded []*Peer + peersRemoved []*Peer + logMessages bool + msgsCounter int + msgsReceived map[byte][]PeerMessage +} + +func NewTestReactor(channels []*ChannelDescriptor, logMessages bool) *TestReactor { + tr := &TestReactor{ + channels: channels, + logMessages: logMessages, + msgsReceived: make(map[byte][]PeerMessage), + } + tr.BaseReactor = *NewBaseReactor(log, "TestReactor", tr) + return tr +} + +func (tr *TestReactor) GetChannels() []*ChannelDescriptor { + return tr.channels +} + +func (tr *TestReactor) AddPeer(peer *Peer) { + tr.mtx.Lock() + defer tr.mtx.Unlock() + tr.peersAdded = append(tr.peersAdded, peer) +} + +func (tr *TestReactor) RemovePeer(peer *Peer, reason interface{}) { + tr.mtx.Lock() + defer tr.mtx.Unlock() + tr.peersRemoved = append(tr.peersRemoved, peer) +} + +func (tr *TestReactor) Receive(chID byte, peer *Peer, msgBytes []byte) { + if tr.logMessages { + tr.mtx.Lock() + defer tr.mtx.Unlock() + //fmt.Printf("Received: %X, %X\n", chID, msgBytes) + tr.msgsReceived[chID] = append(tr.msgsReceived[chID], PeerMessage{peer.Key, msgBytes, tr.msgsCounter}) + tr.msgsCounter++ + } +} + +//----------------------------------------------------------------------------- + +// convenience method for creating two switches connected to each other. +func makeSwitchPair(t testing.TB, initSwitch func(*Switch) *Switch) (*Switch, *Switch) { + + s1PrivKey := crypto.GenPrivKeyEd25519() + s2PrivKey := crypto.GenPrivKeyEd25519() + + // Create two switches that will be interconnected. + s1 := initSwitch(NewSwitch()) + s1.SetNodeInfo(&NodeInfo{ + PubKey: s1PrivKey.PubKey().(crypto.PubKeyEd25519), + Moniker: "switch1", + Network: "testing", + Version: "123.123.123", + }) + s1.SetNodePrivKey(s1PrivKey) + s2 := initSwitch(NewSwitch()) + s2.SetNodeInfo(&NodeInfo{ + PubKey: s2PrivKey.PubKey().(crypto.PubKeyEd25519), + Moniker: "switch2", + Network: "testing", + Version: "123.123.123", + }) + s2.SetNodePrivKey(s2PrivKey) + + // Start switches and reactors + s1.Start() + s2.Start() + + // Create a listener for s1 + l := NewDefaultListener("tcp", ":8001", true) + + // Dial the listener & add the connection to s2. + lAddr := l.ExternalAddress() + connOut, err := lAddr.Dial() + if err != nil { + t.Fatalf("Could not connect to listener address %v", lAddr) + } else { + t.Logf("Created a connection to listener address %v", lAddr) + } + connIn, ok := <-l.Connections() + if !ok { + t.Fatalf("Could not get inbound connection from listener") + } + + go s1.AddPeerWithConnection(connIn, false) // AddPeer is blocking, requires handshake. + s2.AddPeerWithConnection(connOut, true) + + // Wait for things to happen, peers to get added... + time.Sleep(100 * time.Millisecond) + + // Close the server, no longer needed. + l.Stop() + + return s1, s2 +} + +func TestSwitches(t *testing.T) { + s1, s2 := makeSwitchPair(t, func(sw *Switch) *Switch { + // Make two reactors of two channels each + sw.AddReactor("foo", NewTestReactor([]*ChannelDescriptor{ + &ChannelDescriptor{ID: byte(0x00), Priority: 10}, + &ChannelDescriptor{ID: byte(0x01), Priority: 10}, + }, true)) + sw.AddReactor("bar", NewTestReactor([]*ChannelDescriptor{ + &ChannelDescriptor{ID: byte(0x02), Priority: 10}, + &ChannelDescriptor{ID: byte(0x03), Priority: 10}, + }, true)) + return sw + }) + defer s1.Stop() + defer s2.Stop() + + // Lets send a message from s1 to s2. + if s1.Peers().Size() != 1 { + t.Errorf("Expected exactly 1 peer in s1, got %v", s1.Peers().Size()) + } + if s2.Peers().Size() != 1 { + t.Errorf("Expected exactly 1 peer in s2, got %v", s2.Peers().Size()) + } + + ch0Msg := "channel zero" + ch1Msg := "channel foo" + ch2Msg := "channel bar" + + s1.Broadcast(byte(0x00), ch0Msg) + s1.Broadcast(byte(0x01), ch1Msg) + s1.Broadcast(byte(0x02), ch2Msg) + + // Wait for things to settle... + time.Sleep(5000 * time.Millisecond) + + // Check message on ch0 + ch0Msgs := s2.Reactor("foo").(*TestReactor).msgsReceived[byte(0x00)] + if len(ch0Msgs) != 1 { + t.Errorf("Expected to have received 1 message in ch0") + } + if !bytes.Equal(ch0Msgs[0].Bytes, wire.BinaryBytes(ch0Msg)) { + t.Errorf("Unexpected message bytes. Wanted: %X, Got: %X", wire.BinaryBytes(ch0Msg), ch0Msgs[0].Bytes) + } + + // Check message on ch1 + ch1Msgs := s2.Reactor("foo").(*TestReactor).msgsReceived[byte(0x01)] + if len(ch1Msgs) != 1 { + t.Errorf("Expected to have received 1 message in ch1") + } + if !bytes.Equal(ch1Msgs[0].Bytes, wire.BinaryBytes(ch1Msg)) { + t.Errorf("Unexpected message bytes. Wanted: %X, Got: %X", wire.BinaryBytes(ch1Msg), ch1Msgs[0].Bytes) + } + + // Check message on ch2 + ch2Msgs := s2.Reactor("bar").(*TestReactor).msgsReceived[byte(0x02)] + if len(ch2Msgs) != 1 { + t.Errorf("Expected to have received 1 message in ch2") + } + if !bytes.Equal(ch2Msgs[0].Bytes, wire.BinaryBytes(ch2Msg)) { + t.Errorf("Unexpected message bytes. Wanted: %X, Got: %X", wire.BinaryBytes(ch2Msg), ch2Msgs[0].Bytes) + } + +} + +func BenchmarkSwitches(b *testing.B) { + + b.StopTimer() + + s1, s2 := makeSwitchPair(b, func(sw *Switch) *Switch { + // Make bar reactors of bar channels each + sw.AddReactor("foo", NewTestReactor([]*ChannelDescriptor{ + &ChannelDescriptor{ID: byte(0x00), Priority: 10}, + &ChannelDescriptor{ID: byte(0x01), Priority: 10}, + }, false)) + sw.AddReactor("bar", NewTestReactor([]*ChannelDescriptor{ + &ChannelDescriptor{ID: byte(0x02), Priority: 10}, + &ChannelDescriptor{ID: byte(0x03), Priority: 10}, + }, false)) + return sw + }) + defer s1.Stop() + defer s2.Stop() + + // Allow time for goroutines to boot up + time.Sleep(1000 * time.Millisecond) + b.StartTimer() + + numSuccess, numFailure := 0, 0 + + // Send random message from foo channel to another + for i := 0; i < b.N; i++ { + chID := byte(i % 4) + successChan := s1.Broadcast(chID, "test data") + for s := range successChan { + if s { + numSuccess += 1 + } else { + numFailure += 1 + } + } + } + + log.Warn(Fmt("success: %v, failure: %v", numSuccess, numFailure)) + + // Allow everything to flush before stopping switches & closing connections. + b.StopTimer() + time.Sleep(1000 * time.Millisecond) + +} diff --git a/types.go b/types.go new file mode 100644 index 000000000..0e7fc681d --- /dev/null +++ b/types.go @@ -0,0 +1,74 @@ +package p2p + +import ( + "fmt" + "net" + "strconv" + "strings" + + "github.com/tendermint/go-crypto" +) + +type NodeInfo struct { + PubKey crypto.PubKeyEd25519 `json:"pub_key"` + Moniker string `json:"moniker"` + Network string `json:"network"` + Address string `json:"address"` + Version string `json:"version"` // major.minor.revision + Other []string `json:"other"` // other application specific data +} + +// CONTRACT: two nodes are compactible if the major/minor versions match and network match +func (info *NodeInfo) CompatibleWith(other *NodeInfo) error { + iMajor, iMinor, _, iErr := splitVersion(info.Version) + oMajor, oMinor, _, oErr := splitVersion(other.Version) + + // if our own version number is not formatted right, we messed up + if iErr != nil { + return iErr + } + + // version number must be formatted correctly ("x.x.x") + if oErr != nil { + return oErr + } + + // major version must match + if iMajor != oMajor { + return fmt.Errorf("Peer is on a different major version. Got %v, expected %v", oMajor, iMajor) + } + + // minor version must match + if iMinor != oMinor { + return fmt.Errorf("Peer is on a different minor version. Got %v, expected %v", oMinor, iMinor) + } + + // nodes must be on the same network + if info.Network != other.Network { + return fmt.Errorf("Peer is on a different network. Got %v, expected %v", other.Network, info.Network) + } + + return nil +} + +func (info *NodeInfo) Host() string { + host, _, _ := net.SplitHostPort(info.Address) + return host +} + +func (info *NodeInfo) Port() int { + _, port, _ := net.SplitHostPort(info.Address) + port_i, err := strconv.Atoi(port) + if err != nil { + return -1 + } + return port_i +} + +func splitVersion(version string) (string, string, string, error) { + spl := strings.Split(version, ".") + if len(spl) != 3 { + return "", "", "", fmt.Errorf("Invalid version format %v", version) + } + return spl[0], spl[1], spl[2], nil +} diff --git a/upnp/README.md b/upnp/README.md new file mode 100644 index 000000000..557d05bdc --- /dev/null +++ b/upnp/README.md @@ -0,0 +1,5 @@ +# `tendermint/p2p/upnp` + +## Resources + +* http://www.upnp-hacks.org/upnp.html diff --git a/upnp/log.go b/upnp/log.go new file mode 100644 index 000000000..edc5b4980 --- /dev/null +++ b/upnp/log.go @@ -0,0 +1,7 @@ +package upnp + +import ( + "github.com/tendermint/go-logger" +) + +var log = logger.New("module", "upnp") diff --git a/upnp/probe.go b/upnp/probe.go new file mode 100644 index 000000000..5ba9b2370 --- /dev/null +++ b/upnp/probe.go @@ -0,0 +1,111 @@ +package upnp + +import ( + "errors" + "fmt" + "net" + "time" + + . "github.com/tendermint/go-common" +) + +type UPNPCapabilities struct { + PortMapping bool + Hairpin bool +} + +func makeUPNPListener(intPort int, extPort int) (NAT, net.Listener, net.IP, error) { + nat, err := Discover() + if err != nil { + return nil, nil, nil, errors.New(fmt.Sprintf("NAT upnp could not be discovered: %v", err)) + } + log.Info(Fmt("ourIP: %v", nat.(*upnpNAT).ourIP)) + + ext, err := nat.GetExternalAddress() + if err != nil { + return nat, nil, nil, errors.New(fmt.Sprintf("External address error: %v", err)) + } + log.Info(Fmt("External address: %v", ext)) + + port, err := nat.AddPortMapping("tcp", extPort, intPort, "Tendermint UPnP Probe", 0) + if err != nil { + return nat, nil, ext, errors.New(fmt.Sprintf("Port mapping error: %v", err)) + } + log.Info(Fmt("Port mapping mapped: %v", port)) + + // also run the listener, open for all remote addresses. + listener, err := net.Listen("tcp", fmt.Sprintf(":%v", intPort)) + if err != nil { + return nat, nil, ext, errors.New(fmt.Sprintf("Error establishing listener: %v", err)) + } + return nat, listener, ext, nil +} + +func testHairpin(listener net.Listener, extAddr string) (supportsHairpin bool) { + // Listener + go func() { + inConn, err := listener.Accept() + if err != nil { + log.Notice(Fmt("Listener.Accept() error: %v", err)) + return + } + log.Info(Fmt("Accepted incoming connection: %v -> %v", inConn.LocalAddr(), inConn.RemoteAddr())) + buf := make([]byte, 1024) + n, err := inConn.Read(buf) + if err != nil { + log.Notice(Fmt("Incoming connection read error: %v", err)) + return + } + log.Info(Fmt("Incoming connection read %v bytes: %X", n, buf)) + if string(buf) == "test data" { + supportsHairpin = true + return + } + }() + + // Establish outgoing + outConn, err := net.Dial("tcp", extAddr) + if err != nil { + log.Notice(Fmt("Outgoing connection dial error: %v", err)) + return + } + + n, err := outConn.Write([]byte("test data")) + if err != nil { + log.Notice(Fmt("Outgoing connection write error: %v", err)) + return + } + log.Info(Fmt("Outgoing connection wrote %v bytes", n)) + + // Wait for data receipt + time.Sleep(1 * time.Second) + return +} + +func Probe() (caps UPNPCapabilities, err error) { + log.Info("Probing for UPnP!") + + intPort, extPort := 8001, 8001 + + nat, listener, ext, err := makeUPNPListener(intPort, extPort) + if err != nil { + return + } + caps.PortMapping = true + + // Deferred cleanup + defer func() { + err = nat.DeletePortMapping("tcp", intPort, extPort) + if err != nil { + log.Warn(Fmt("Port mapping delete error: %v", err)) + } + listener.Close() + }() + + supportsHairpin := testHairpin(listener, fmt.Sprintf("%v:%v", ext, extPort)) + if supportsHairpin { + caps.Hairpin = true + } + + return +} diff --git a/upnp/upnp.go b/upnp/upnp.go new file mode 100644 index 000000000..3d6c55035 --- /dev/null +++ b/upnp/upnp.go @@ -0,0 +1,380 @@ +/* +Taken from taipei-torrent + +Just enough UPnP to be able to forward ports +*/ +package upnp + +// BUG(jae): TODO: use syscalls to get actual ourIP. http://pastebin.com/9exZG4rh + +import ( + "bytes" + "encoding/xml" + "errors" + "io/ioutil" + "net" + "net/http" + "strconv" + "strings" + "time" +) + +type upnpNAT struct { + serviceURL string + ourIP string + urnDomain string +} + +// protocol is either "udp" or "tcp" +type NAT interface { + GetExternalAddress() (addr net.IP, err error) + AddPortMapping(protocol string, externalPort, internalPort int, description string, timeout int) (mappedExternalPort int, err error) + DeletePortMapping(protocol string, externalPort, internalPort int) (err error) +} + +func Discover() (nat NAT, err error) { + ssdp, err := net.ResolveUDPAddr("udp4", "239.255.255.250:1900") + if err != nil { + return + } + conn, err := net.ListenPacket("udp4", ":0") + if err != nil { + return + } + socket := conn.(*net.UDPConn) + defer socket.Close() + + err = socket.SetDeadline(time.Now().Add(3 * time.Second)) + if err != nil { + return + } + + st := "InternetGatewayDevice:1" + + buf := bytes.NewBufferString( + "M-SEARCH * HTTP/1.1\r\n" + + "HOST: 239.255.255.250:1900\r\n" + + "ST: ssdp:all\r\n" + + "MAN: \"ssdp:discover\"\r\n" + + "MX: 2\r\n\r\n") + message := buf.Bytes() + answerBytes := make([]byte, 1024) + for i := 0; i < 3; i++ { + _, err = socket.WriteToUDP(message, ssdp) + if err != nil { + return + } + var n int + n, _, err = socket.ReadFromUDP(answerBytes) + for { + n, _, err = socket.ReadFromUDP(answerBytes) + if err != nil { + break + } + answer := string(answerBytes[0:n]) + if strings.Index(answer, st) < 0 { + continue + } + // HTTP header field names are case-insensitive. + // http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 + locString := "\r\nlocation:" + answer = strings.ToLower(answer) + locIndex := strings.Index(answer, locString) + if locIndex < 0 { + continue + } + loc := answer[locIndex+len(locString):] + endIndex := strings.Index(loc, "\r\n") + if endIndex < 0 { + continue + } + locURL := strings.TrimSpace(loc[0:endIndex]) + var serviceURL, urnDomain string + serviceURL, urnDomain, err = getServiceURL(locURL) + if err != nil { + return + } + var ourIP net.IP + ourIP, err = localIPv4() + if err != nil { + return + } + nat = &upnpNAT{serviceURL: serviceURL, ourIP: ourIP.String(), urnDomain: urnDomain} + return + } + } + err = errors.New("UPnP port discovery failed.") + return +} + +type Envelope struct { + XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Envelope"` + Soap *SoapBody +} +type SoapBody struct { + XMLName xml.Name `xml:"http://schemas.xmlsoap.org/soap/envelope/ Body"` + ExternalIP *ExternalIPAddressResponse +} + +type ExternalIPAddressResponse struct { + XMLName xml.Name `xml:"GetExternalIPAddressResponse"` + IPAddress string `xml:"NewExternalIPAddress"` +} + +type ExternalIPAddress struct { + XMLName xml.Name `xml:"NewExternalIPAddress"` + IP string +} + +type UPNPService struct { + ServiceType string `xml:"serviceType"` + ControlURL string `xml:"controlURL"` +} + +type DeviceList struct { + Device []Device `xml:"device"` +} + +type ServiceList struct { + Service []UPNPService `xml:"service"` +} + +type Device struct { + XMLName xml.Name `xml:"device"` + DeviceType string `xml:"deviceType"` + DeviceList DeviceList `xml:"deviceList"` + ServiceList ServiceList `xml:"serviceList"` +} + +type Root struct { + Device Device +} + +func getChildDevice(d *Device, deviceType string) *Device { + dl := d.DeviceList.Device + for i := 0; i < len(dl); i++ { + if strings.Index(dl[i].DeviceType, deviceType) >= 0 { + return &dl[i] + } + } + return nil +} + +func getChildService(d *Device, serviceType string) *UPNPService { + sl := d.ServiceList.Service + for i := 0; i < len(sl); i++ { + if strings.Index(sl[i].ServiceType, serviceType) >= 0 { + return &sl[i] + } + } + return nil +} + +func localIPv4() (net.IP, error) { + tt, err := net.Interfaces() + if err != nil { + return nil, err + } + for _, t := range tt { + aa, err := t.Addrs() + if err != nil { + return nil, err + } + for _, a := range aa { + ipnet, ok := a.(*net.IPNet) + if !ok { + continue + } + v4 := ipnet.IP.To4() + if v4 == nil || v4[0] == 127 { // loopback address + continue + } + return v4, nil + } + } + return nil, errors.New("cannot find local IP address") +} + +func getServiceURL(rootURL string) (url, urnDomain string, err error) { + r, err := http.Get(rootURL) + if err != nil { + return + } + defer r.Body.Close() + if r.StatusCode >= 400 { + err = errors.New(string(r.StatusCode)) + return + } + var root Root + err = xml.NewDecoder(r.Body).Decode(&root) + if err != nil { + return + } + a := &root.Device + if strings.Index(a.DeviceType, "InternetGatewayDevice:1") < 0 { + err = errors.New("No InternetGatewayDevice") + return + } + b := getChildDevice(a, "WANDevice:1") + if b == nil { + err = errors.New("No WANDevice") + return + } + c := getChildDevice(b, "WANConnectionDevice:1") + if c == nil { + err = errors.New("No WANConnectionDevice") + return + } + d := getChildService(c, "WANIPConnection:1") + if d == nil { + // Some routers don't follow the UPnP spec, and put WanIPConnection under WanDevice, + // instead of under WanConnectionDevice + d = getChildService(b, "WANIPConnection:1") + + if d == nil { + err = errors.New("No WANIPConnection") + return + } + } + // Extract the domain name, which isn't always 'schemas-upnp-org' + urnDomain = strings.Split(d.ServiceType, ":")[1] + url = combineURL(rootURL, d.ControlURL) + return +} + +func combineURL(rootURL, subURL string) string { + protocolEnd := "://" + protoEndIndex := strings.Index(rootURL, protocolEnd) + a := rootURL[protoEndIndex+len(protocolEnd):] + rootIndex := strings.Index(a, "/") + return rootURL[0:protoEndIndex+len(protocolEnd)+rootIndex] + subURL +} + +func soapRequest(url, function, message, domain string) (r *http.Response, err error) { + fullMessage := "" + + "\r\n" + + "" + message + "" + + req, err := http.NewRequest("POST", url, strings.NewReader(fullMessage)) + if err != nil { + return nil, err + } + req.Header.Set("Content-Type", "text/xml ; charset=\"utf-8\"") + req.Header.Set("User-Agent", "Darwin/10.0.0, UPnP/1.0, MiniUPnPc/1.3") + //req.Header.Set("Transfer-Encoding", "chunked") + req.Header.Set("SOAPAction", "\"urn:"+domain+":service:WANIPConnection:1#"+function+"\"") + req.Header.Set("Connection", "Close") + req.Header.Set("Cache-Control", "no-cache") + req.Header.Set("Pragma", "no-cache") + + // log.Stderr("soapRequest ", req) + + r, err = http.DefaultClient.Do(req) + if err != nil { + return nil, err + } + /*if r.Body != nil { + defer r.Body.Close() + }*/ + + if r.StatusCode >= 400 { + // log.Stderr(function, r.StatusCode) + err = errors.New("Error " + strconv.Itoa(r.StatusCode) + " for " + function) + r = nil + return + } + return +} + +type statusInfo struct { + externalIpAddress string +} + +func (n *upnpNAT) getExternalIPAddress() (info statusInfo, err error) { + + message := "\r\n" + + "" + + var response *http.Response + response, err = soapRequest(n.serviceURL, "GetExternalIPAddress", message, n.urnDomain) + if response != nil { + defer response.Body.Close() + } + if err != nil { + return + } + var envelope Envelope + data, err := ioutil.ReadAll(response.Body) + reader := bytes.NewReader(data) + xml.NewDecoder(reader).Decode(&envelope) + + info = statusInfo{envelope.Soap.ExternalIP.IPAddress} + + if err != nil { + return + } + + return +} + +func (n *upnpNAT) GetExternalAddress() (addr net.IP, err error) { + info, err := n.getExternalIPAddress() + if err != nil { + return + } + addr = net.ParseIP(info.externalIpAddress) + return +} + +func (n *upnpNAT) AddPortMapping(protocol string, externalPort, internalPort int, description string, timeout int) (mappedExternalPort int, err error) { + // A single concatenation would break ARM compilation. + message := "\r\n" + + "" + strconv.Itoa(externalPort) + message += "" + protocol + "" + message += "" + strconv.Itoa(internalPort) + "" + + "" + n.ourIP + "" + + "1" + message += description + + "" + strconv.Itoa(timeout) + + "" + + var response *http.Response + response, err = soapRequest(n.serviceURL, "AddPortMapping", message, n.urnDomain) + if response != nil { + defer response.Body.Close() + } + if err != nil { + return + } + + // TODO: check response to see if the port was forwarded + // log.Println(message, response) + // JAE: + // body, err := ioutil.ReadAll(response.Body) + // fmt.Println(string(body), err) + mappedExternalPort = externalPort + _ = response + return +} + +func (n *upnpNAT) DeletePortMapping(protocol string, externalPort, internalPort int) (err error) { + + message := "\r\n" + + "" + strconv.Itoa(externalPort) + + "" + protocol + "" + + "" + + var response *http.Response + response, err = soapRequest(n.serviceURL, "DeletePortMapping", message, n.urnDomain) + if response != nil { + defer response.Body.Close() + } + if err != nil { + return + } + + // TODO: check response to see if the port was deleted + // log.Println(message, response) + _ = response + return +} diff --git a/util.go b/util.go new file mode 100644 index 000000000..2be320263 --- /dev/null +++ b/util.go @@ -0,0 +1,15 @@ +package p2p + +import ( + "crypto/sha256" +) + +// doubleSha256 calculates sha256(sha256(b)) and returns the resulting bytes. +func doubleSha256(b []byte) []byte { + hasher := sha256.New() + hasher.Write(b) + sum := hasher.Sum(nil) + hasher.Reset() + hasher.Write(sum) + return hasher.Sum(nil) +} diff --git a/version.go b/version.go new file mode 100644 index 000000000..7e51463dc --- /dev/null +++ b/version.go @@ -0,0 +1,3 @@ +package p2p + +const Version = "0.3.0" From 1c628a97ad5223401276d174388b8d1e3d654d21 Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Tue, 10 Nov 2015 12:29:43 -0800 Subject: [PATCH 002/309] Conform to go-wire 1.0 --- addrbook.go | 3 +- connection.go | 84 ++++++++++++++++++++------------------------ peer.go | 10 +++--- pex_reactor.go | 5 +-- secret_connection.go | 4 +-- types.go | 2 ++ 6 files changed, 54 insertions(+), 54 deletions(-) diff --git a/addrbook.go b/addrbook.go index 367ced8d9..a951dffd3 100644 --- a/addrbook.go +++ b/addrbook.go @@ -65,7 +65,8 @@ const ( minGetSelection = 32 // max addresses returned by GetSelection - maxGetSelection = 2500 + // NOTE: this must match "maxPexMessageSize" + maxGetSelection = 250 // current version of the on-disk format. serializationVersion = 1 diff --git a/connection.go b/connection.go index baa0dc1b4..494fdd753 100644 --- a/connection.go +++ b/connection.go @@ -16,18 +16,19 @@ import ( ) const ( - numBatchMsgPackets = 10 - minReadBufferSize = 1024 - minWriteBufferSize = 1024 - idleTimeoutMinutes = 5 - updateStatsSeconds = 2 - pingTimeoutSeconds = 40 - defaultSendRate = 51200 // 50Kb/s - defaultRecvRate = 51200 // 50Kb/s - flushThrottleMS = 100 - defaultSendQueueCapacity = 1 - defaultRecvBufferCapacity = 4096 - defaultSendTimeoutSeconds = 10 + numBatchMsgPackets = 10 + minReadBufferSize = 1024 + minWriteBufferSize = 1024 + idleTimeoutMinutes = 5 + updateStatsSeconds = 2 + pingTimeoutSeconds = 40 + defaultSendRate = 51200 // 50KB/s + defaultRecvRate = 51200 // 50KB/s + flushThrottleMS = 100 + defaultSendQueueCapacity = 1 + defaultRecvBufferCapacity = 4096 + defaultRecvMessageCapacity = 22020096 // 21MB + defaultSendTimeoutSeconds = 10 ) type receiveCbFunc func(chID byte, msgBytes []byte) @@ -259,7 +260,7 @@ func (c *MConnection) sendRoutine() { FOR_LOOP: for { - var n int64 + var n int var err error select { case <-c.flushTimer.Ch: @@ -313,7 +314,7 @@ func (c *MConnection) sendSomeMsgPackets() bool { // Block until .sendMonitor says we can write. // Once we're ready we send more than we asked for, // but amortized it should even out. - c.sendMonitor.Limit(maxMsgPacketSize, atomic.LoadInt64(&c.sendRate), true) + c.sendMonitor.Limit(maxMsgPacketTotalSize, atomic.LoadInt64(&c.sendRate), true) // Now send some msgPackets. for i := 0; i < numBatchMsgPackets; i++ { @@ -371,7 +372,7 @@ func (c *MConnection) recvRoutine() { FOR_LOOP: for { // Block until .recvMonitor says we can read. - c.recvMonitor.Limit(maxMsgPacketSize, atomic.LoadInt64(&c.recvRate), true) + c.recvMonitor.Limit(maxMsgPacketTotalSize, atomic.LoadInt64(&c.recvRate), true) /* // Peek into bufReader for debugging @@ -389,7 +390,7 @@ FOR_LOOP: */ // Read packet type - var n int64 + var n int var err error pktType := wire.ReadByte(c.bufReader, &n, &err) c.recvMonitor.Update(int(n)) @@ -411,8 +412,8 @@ FOR_LOOP: // do nothing log.Info("Receive Pong") case packetTypeMsg: - pkt, n, err := msgPacket{}, int64(0), error(nil) - wire.ReadBinaryPtr(&pkt, c.bufReader, &n, &err) + pkt, n, err := msgPacket{}, int(0), error(nil) + wire.ReadBinaryPtr(&pkt, c.bufReader, maxMsgPacketTotalSize, &n, &err) c.recvMonitor.Update(int(n)) if err != nil { if c.IsRunning() { @@ -456,10 +457,11 @@ FOR_LOOP: //----------------------------------------------------------------------------- type ChannelDescriptor struct { - ID byte - Priority int - SendQueueCapacity int - RecvBufferCapacity int + ID byte + Priority int + SendQueueCapacity int + RecvBufferCapacity int + RecvMessageCapacity int } func (chDesc *ChannelDescriptor) FillDefaults() { @@ -469,6 +471,9 @@ func (chDesc *ChannelDescriptor) FillDefaults() { if chDesc.RecvBufferCapacity == 0 { chDesc.RecvBufferCapacity = defaultRecvBufferCapacity } + if chDesc.RecvMessageCapacity == 0 { + chDesc.RecvMessageCapacity = defaultRecvMessageCapacity + } } // TODO: lowercase. @@ -557,27 +562,27 @@ func (ch *Channel) isSendPending() bool { func (ch *Channel) nextMsgPacket() msgPacket { packet := msgPacket{} packet.ChannelID = byte(ch.id) - packet.Bytes = ch.sending[:MinInt(maxMsgPacketSize, len(ch.sending))] - if len(ch.sending) <= maxMsgPacketSize { + packet.Bytes = ch.sending[:MinInt(maxMsgPacketPayloadSize, len(ch.sending))] + if len(ch.sending) <= maxMsgPacketPayloadSize { packet.EOF = byte(0x01) ch.sending = nil atomic.AddInt32(&ch.sendQueueSize, -1) // decrement sendQueueSize } else { packet.EOF = byte(0x00) - ch.sending = ch.sending[MinInt(maxMsgPacketSize, len(ch.sending)):] + ch.sending = ch.sending[MinInt(maxMsgPacketPayloadSize, len(ch.sending)):] } return packet } // Writes next msgPacket to w. // Not goroutine-safe -func (ch *Channel) writeMsgPacketTo(w io.Writer) (n int64, err error) { +func (ch *Channel) writeMsgPacketTo(w io.Writer) (n int, err error) { packet := ch.nextMsgPacket() log.Debug("Write Msg Packet", "conn", ch.conn, "packet", packet) wire.WriteByte(packetTypeMsg, w, &n, &err) wire.WriteBinary(packet, w, &n, &err) if err != nil { - ch.recentlySent += n + ch.recentlySent += int64(n) } return } @@ -586,7 +591,7 @@ func (ch *Channel) writeMsgPacketTo(w io.Writer) (n int64, err error) { // Not goroutine-safe func (ch *Channel) recvMsgPacket(packet msgPacket) ([]byte, error) { // log.Debug("Read Msg Packet", "conn", ch.conn, "packet", packet) - if wire.MaxBinaryReadSize < len(ch.recving)+len(packet.Bytes) { + if ch.desc.RecvMessageCapacity < len(ch.recving)+len(packet.Bytes) { return nil, wire.ErrBinaryReadSizeOverflow } ch.recving = append(ch.recving, packet.Bytes...) @@ -609,10 +614,12 @@ func (ch *Channel) updateStats() { //----------------------------------------------------------------------------- const ( - maxMsgPacketSize = 1024 - packetTypePing = byte(0x01) - packetTypePong = byte(0x02) - packetTypeMsg = byte(0x03) + maxMsgPacketPayloadSize = 1024 + maxMsgPacketOverheadSize = 10 // It's actually lower but good enough + maxMsgPacketTotalSize = maxMsgPacketPayloadSize + maxMsgPacketOverheadSize + packetTypePing = byte(0x01) + packetTypePong = byte(0x02) + packetTypeMsg = byte(0x03) ) // Messages in channels are chopped into smaller msgPackets for multiplexing. @@ -625,16 +632,3 @@ type msgPacket struct { func (p msgPacket) String() string { return fmt.Sprintf("MsgPacket{%X:%X T:%X}", p.ChannelID, p.Bytes, p.EOF) } - -//----------------------------------------------------------------------------- - -// Convenience struct for writing typed messages. -// Reading requires a custom decoder that switches on the first type byte of a byteslice. -type TypedMessage struct { - Type byte - Msg interface{} -} - -func (tm TypedMessage) String() string { - return fmt.Sprintf("TMsg{%X:%v}", tm.Type, tm.Msg) -} diff --git a/peer.go b/peer.go index 61e7cd688..47a6955a9 100644 --- a/peer.go +++ b/peer.go @@ -28,12 +28,12 @@ func peerHandshake(conn net.Conn, ourNodeInfo *NodeInfo) (*NodeInfo, error) { var err2 error Parallel( func() { - var n int64 + var n int wire.WriteBinary(ourNodeInfo, conn, &n, &err1) }, func() { - var n int64 - wire.ReadBinary(peerNodeInfo, conn, &n, &err2) + var n int + wire.ReadBinary(peerNodeInfo, conn, maxNodeInfoSize, &n, &err2) log.Notice("Peer handshake", "peerNodeInfo", peerNodeInfo) }) if err1 != nil { @@ -112,7 +112,9 @@ func (p *Peer) CanSend(chID byte) bool { } func (p *Peer) WriteTo(w io.Writer) (n int64, err error) { - wire.WriteString(p.Key, w, &n, &err) + var n_ int + wire.WriteString(p.Key, w, &n_, &err) + n += int64(n_) return } diff --git a/pex_reactor.go b/pex_reactor.go index b6d8bf0e1..1a421b366 100644 --- a/pex_reactor.go +++ b/pex_reactor.go @@ -18,6 +18,7 @@ const ( PexChannel = byte(0x00) ensurePeersPeriodSeconds = 30 minNumOutboundPeers = 10 + maxPexMessageSize = 1048576 // 1MB ) /* @@ -227,9 +228,9 @@ var _ = wire.RegisterInterface( func DecodeMessage(bz []byte) (msgType byte, msg PexMessage, err error) { msgType = bz[0] - n := new(int64) + n := new(int) r := bytes.NewReader(bz) - msg = wire.ReadBinary(struct{ PexMessage }{}, r, n, &err).(struct{ PexMessage }).PexMessage + msg = wire.ReadBinary(struct{ PexMessage }{}, r, maxPexMessageSize, n, &err).(struct{ PexMessage }).PexMessage return } diff --git a/secret_connection.go b/secret_connection.go index bec465e62..1e1cdb4b2 100644 --- a/secret_connection.go +++ b/secret_connection.go @@ -279,8 +279,8 @@ func shareAuthSignature(sc *SecretConnection, pubKey crypto.PubKeyEd25519, signa if err2 != nil { return } - n := int64(0) // not used. - recvMsg = wire.ReadBinary(authSigMessage{}, bytes.NewBuffer(readBuffer), &n, &err2).(authSigMessage) + n := int(0) // not used. + recvMsg = wire.ReadBinary(authSigMessage{}, bytes.NewBuffer(readBuffer), authSigMsgSize, &n, &err2).(authSigMessage) }) if err1 != nil { diff --git a/types.go b/types.go index 0e7fc681d..fa139124e 100644 --- a/types.go +++ b/types.go @@ -9,6 +9,8 @@ import ( "github.com/tendermint/go-crypto" ) +const maxNodeInfoSize = 10240 // 10Kb + type NodeInfo struct { PubKey crypto.PubKeyEd25519 `json:"pub_key"` Moniker string `json:"moniker"` From c37e25e76b569a2dd4857f9192fd7e8d8f908fef Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Fri, 4 Dec 2015 00:02:44 -0800 Subject: [PATCH 003/309] Conform to go-common WriteFile*(path, mode) --- addrbook.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/addrbook.go b/addrbook.go index a951dffd3..14b39b575 100644 --- a/addrbook.go +++ b/addrbook.go @@ -318,7 +318,7 @@ func (a *AddrBook) saveToFile(filePath string) { log.Error("Failed to save AddrBook to file", "err", err) return } - err = WriteFileAtomic(filePath, jsonBytes) + err = WriteFileAtomic(filePath, jsonBytes, 0644) if err != nil { log.Error("Failed to save AddrBook to file", "file", filePath, "error", err) } From 432a37857df2b85c7c768ffd6d7f3632837ba4a6 Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Sat, 5 Dec 2015 09:44:03 -0800 Subject: [PATCH 004/309] Add RemoteAddr and ListenAddr to NodeInfo; Refactor IPRange logic --- ip_range_counter.go | 29 +++++++++++ peer.go | 1 + peer_set.go | 122 ++------------------------------------------ peer_set_test.go | 105 +------------------------------------- pex_reactor.go | 3 +- switch.go | 10 ---- types.go | 21 ++++---- 7 files changed, 50 insertions(+), 241 deletions(-) create mode 100644 ip_range_counter.go diff --git a/ip_range_counter.go b/ip_range_counter.go new file mode 100644 index 000000000..85d9d407a --- /dev/null +++ b/ip_range_counter.go @@ -0,0 +1,29 @@ +package p2p + +import ( + "strings" +) + +// TODO Test +func AddToIPRangeCounts(counts map[string]int, ip string) map[string]int { + changes := make(map[string]int) + ipParts := strings.Split(ip, ":") + for i := 1; i < len(ipParts); i++ { + prefix := strings.Join(ipParts[:i], ":") + counts[prefix] += 1 + changes[prefix] = counts[prefix] + } + return changes +} + +// TODO Test +func CheckIPRangeCounts(counts map[string]int, limits []int) bool { + for prefix, count := range counts { + ipParts := strings.Split(prefix, ":") + numParts := len(ipParts) + if limits[numParts] < count { + return false + } + } + return true +} diff --git a/peer.go b/peer.go index 47a6955a9..a0f153fe3 100644 --- a/peer.go +++ b/peer.go @@ -42,6 +42,7 @@ func peerHandshake(conn net.Conn, ourNodeInfo *NodeInfo) (*NodeInfo, error) { if err2 != nil { return nil, err2 } + peerNodeInfo.RemoteAddr = conn.RemoteAddr().String() return peerNodeInfo, nil } diff --git a/peer_set.go b/peer_set.go index ccf26dc3b..f3bc1edaf 100644 --- a/peer_set.go +++ b/peer_set.go @@ -1,8 +1,6 @@ package p2p import ( - "net" - "strings" "sync" ) @@ -16,18 +14,13 @@ type IPeerSet interface { //----------------------------------------------------------------------------- -var ( - maxPeersPerIPRange = [4]int{11, 7, 5, 3} // ... -) - // PeerSet is a special structure for keeping a table of peers. // Iteration over the peers is super fast and thread-safe. // We also track how many peers per IP range and avoid too many type PeerSet struct { - mtx sync.Mutex - lookup map[string]*peerSetItem - list []*Peer - connectedIPs *nestedCounter + mtx sync.Mutex + lookup map[string]*peerSetItem + list []*Peer } type peerSetItem struct { @@ -37,9 +30,8 @@ type peerSetItem struct { func NewPeerSet() *PeerSet { return &PeerSet{ - lookup: make(map[string]*peerSetItem), - list: make([]*Peer, 0, 256), - connectedIPs: NewNestedCounter(), + lookup: make(map[string]*peerSetItem), + list: make([]*Peer, 0, 256), } } @@ -52,12 +44,6 @@ func (ps *PeerSet) Add(peer *Peer) error { return ErrSwitchDuplicatePeer } - // ensure we havent maxed out connections for the peer's IP range yet - // and update the IP range counters - if !ps.incrIPRangeCounts(peer.Host()) { - return ErrSwitchMaxPeersPerIPRange - } - index := len(ps.list) // Appending is safe even with other goroutines // iterating over the ps.list slice. @@ -92,9 +78,6 @@ func (ps *PeerSet) Remove(peer *Peer) { return } - // update the IP range counters - ps.decrIPRangeCounts(peer.Host()) - index := item.index // Copy the list but without the last element. // (we must copy because we're mutating the list) @@ -130,98 +113,3 @@ func (ps *PeerSet) List() []*Peer { defer ps.mtx.Unlock() return ps.list } - -//----------------------------------------------------------------------------- -// track the number of IPs we're connected to for each IP address range - -// forms an IP address hierarchy tree with counts -// the struct itself is not thread safe and should always only be accessed with the ps.mtx locked -type nestedCounter struct { - count int - children map[string]*nestedCounter -} - -func NewNestedCounter() *nestedCounter { - nc := new(nestedCounter) - nc.children = make(map[string]*nestedCounter) - return nc -} - -// Check if we have too many IPs in the IP range of the incoming connection -// Thread safe -func (ps *PeerSet) HasMaxForIPRange(conn net.Conn) (ok bool) { - ps.mtx.Lock() - defer ps.mtx.Unlock() - ip, _, _ := net.SplitHostPort(conn.RemoteAddr().String()) - ipBytes := strings.Split(ip, ".") - - c := ps.connectedIPs - for i, ipByte := range ipBytes { - if c, ok = c.children[ipByte]; !ok { - return false - } - if maxPeersPerIPRange[i] <= c.count { - return true - } - } - return false -} - -// Increments counts for this address' IP range -// Returns false if we already have enough connections -// Not thread safe (only called by ps.Add()) -func (ps *PeerSet) incrIPRangeCounts(address string) bool { - addrParts := strings.Split(address, ".") - - c := ps.connectedIPs - return incrNestedCounters(c, addrParts, 0) -} - -// Recursively descend the IP hierarchy, checking if we have -// max peers for each range and incrementing if not. -// Returns false if incr failed because max peers reached for some range counter. -func incrNestedCounters(c *nestedCounter, ipBytes []string, index int) bool { - ipByte := ipBytes[index] - child := c.children[ipByte] - if child == nil { - child = NewNestedCounter() - c.children[ipByte] = child - } - if index+1 < len(ipBytes) { - if !incrNestedCounters(child, ipBytes, index+1) { - return false - } - } - if maxPeersPerIPRange[index] <= child.count { - return false - } else { - child.count += 1 - return true - } -} - -// Decrement counts for this address' IP range -func (ps *PeerSet) decrIPRangeCounts(address string) { - addrParts := strings.Split(address, ".") - - c := ps.connectedIPs - decrNestedCounters(c, addrParts, 0) -} - -// Recursively descend the IP hierarchy, decrementing by one. -// If the counter is zero, deletes the child. -func decrNestedCounters(c *nestedCounter, ipBytes []string, index int) { - ipByte := ipBytes[index] - child := c.children[ipByte] - if child == nil { - log.Error("p2p/peer_set decrNestedCounters encountered a missing child counter") - return - } - if index+1 < len(ipBytes) { - decrNestedCounters(child, ipBytes, index+1) - } - child.count -= 1 - if child.count <= 0 { - delete(c.children, ipByte) - } -} diff --git a/peer_set_test.go b/peer_set_test.go index 1e16847c1..ceb10eeee 100644 --- a/peer_set_test.go +++ b/peer_set_test.go @@ -2,7 +2,6 @@ package p2p import ( "math/rand" - "strings" "testing" . "github.com/tendermint/go-common" @@ -13,7 +12,8 @@ func randPeer() *Peer { return &Peer{ Key: RandStr(12), NodeInfo: &NodeInfo{ - Address: Fmt("%v.%v.%v.%v:46656", rand.Int()%256, rand.Int()%256, rand.Int()%256, rand.Int()%256), + RemoteAddr: Fmt("%v.%v.%v.%v:46656", rand.Int()%256, rand.Int()%256, rand.Int()%256, rand.Int()%256), + ListenAddr: Fmt("%v.%v.%v.%v:46656", rand.Int()%256, rand.Int()%256, rand.Int()%256, rand.Int()%256), }, } } @@ -44,7 +44,6 @@ func TestAddRemoveMany(t *testing.T) { peers := []*Peer{} N := 100 - maxPeersPerIPRange = [4]int{N, N, N, N} for i := 0; i < N; i++ { peer := randPeer() if err := peerSet.Add(peer); err != nil { @@ -66,103 +65,3 @@ func TestAddRemoveMany(t *testing.T) { } } } - -func newPeerInIPRange(ipBytes ...string) *Peer { - ips := make([]string, 4) - for i, ipByte := range ipBytes { - ips[i] = ipByte - } - for i := len(ipBytes); i < 4; i++ { - ips[i] = Fmt("%v", rand.Int()%256) - } - ipS := strings.Join(ips, ".") - return &Peer{ - Key: RandStr(12), - NodeInfo: &NodeInfo{ - Address: ipS + ":46656", - }, - } -} - -func TestIPRanges(t *testing.T) { - peerSet := NewPeerSet() - - // test /8 - maxPeersPerIPRange = [4]int{2, 2, 2, 2} - peer := newPeerInIPRange("54", "1") - if err := peerSet.Add(peer); err != nil { - t.Errorf("Failed to add new peer") - } - peer = newPeerInIPRange("54", "2") - if err := peerSet.Add(peer); err != nil { - t.Errorf("Failed to add new peer") - } - peer = newPeerInIPRange("54", "3") - if err := peerSet.Add(peer); err == nil { - t.Errorf("Added peer when we shouldn't have") - } - peer = newPeerInIPRange("55", "1") - if err := peerSet.Add(peer); err != nil { - t.Errorf("Failed to add new peer") - } - - // test /16 - peerSet = NewPeerSet() - maxPeersPerIPRange = [4]int{3, 2, 1, 1} - peer = newPeerInIPRange("54", "112", "1") - if err := peerSet.Add(peer); err != nil { - t.Errorf("Failed to add new peer") - } - peer = newPeerInIPRange("54", "112", "2") - if err := peerSet.Add(peer); err != nil { - t.Errorf("Failed to add new peer") - } - peer = newPeerInIPRange("54", "112", "3") - if err := peerSet.Add(peer); err == nil { - t.Errorf("Added peer when we shouldn't have") - } - peer = newPeerInIPRange("54", "113", "1") - if err := peerSet.Add(peer); err != nil { - t.Errorf("Failed to add new peer") - } - - // test /24 - peerSet = NewPeerSet() - maxPeersPerIPRange = [4]int{5, 3, 2, 1} - peer = newPeerInIPRange("54", "112", "11", "1") - if err := peerSet.Add(peer); err != nil { - t.Errorf("Failed to add new peer") - } - peer = newPeerInIPRange("54", "112", "11", "2") - if err := peerSet.Add(peer); err != nil { - t.Errorf("Failed to add new peer") - } - peer = newPeerInIPRange("54", "112", "11", "3") - if err := peerSet.Add(peer); err == nil { - t.Errorf("Added peer when we shouldn't have") - } - peer = newPeerInIPRange("54", "112", "12", "1") - if err := peerSet.Add(peer); err != nil { - t.Errorf("Failed to add new peer") - } - - // test /32 - peerSet = NewPeerSet() - maxPeersPerIPRange = [4]int{11, 7, 5, 2} - peer = newPeerInIPRange("54", "112", "11", "10") - if err := peerSet.Add(peer); err != nil { - t.Errorf("Failed to add new peer") - } - peer = newPeerInIPRange("54", "112", "11", "10") - if err := peerSet.Add(peer); err != nil { - t.Errorf("Failed to add new peer") - } - peer = newPeerInIPRange("54", "112", "11", "10") - if err := peerSet.Add(peer); err == nil { - t.Errorf("Added peer when we shouldn't have") - } - peer = newPeerInIPRange("54", "112", "11", "11") - if err := peerSet.Add(peer); err != nil { - t.Errorf("Failed to add new peer") - } -} diff --git a/pex_reactor.go b/pex_reactor.go index 1a421b366..321ec7d7b 100644 --- a/pex_reactor.go +++ b/pex_reactor.go @@ -63,8 +63,9 @@ func (pexR *PEXReactor) GetChannels() []*ChannelDescriptor { // Implements Reactor func (pexR *PEXReactor) AddPeer(peer *Peer) { + // XXX Move this into Switch // Add the peer to the address book - netAddr := NewNetAddressString(peer.Address) + netAddr := NewNetAddressString(peer.ListenAddr) if peer.IsOutbound() { if pexR.book.NeedMoreAddrs() { pexR.RequestPEX(peer) diff --git a/switch.go b/switch.go index 409a0fa75..d118d95e5 100644 --- a/switch.go +++ b/switch.go @@ -224,10 +224,6 @@ func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool) (*Peer, er return nil, err } - // The peerNodeInfo is not verified, so overwrite - // the IP, and the port too if we dialed out - // Everything else we just have to trust - peerNodeInfo.Address = sconn.RemoteAddr().String() peer := newPeer(sconn, peerNodeInfo, outbound, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError) // Add the peer to .peers @@ -351,12 +347,6 @@ func (sw *Switch) listenerRoutine(l Listener) { continue } - // Ignore connections from IP ranges for which we have too many - if sw.peers.HasMaxForIPRange(inConn) { - log.Info("Ignoring inbound connection: already have enough peers for that IP range", "address", inConn.RemoteAddr().String()) - continue - } - // New inbound connection! _, err := sw.AddPeerWithConnection(inConn, false) if err != nil { diff --git a/types.go b/types.go index fa139124e..0db2c957b 100644 --- a/types.go +++ b/types.go @@ -12,12 +12,13 @@ import ( const maxNodeInfoSize = 10240 // 10Kb type NodeInfo struct { - PubKey crypto.PubKeyEd25519 `json:"pub_key"` - Moniker string `json:"moniker"` - Network string `json:"network"` - Address string `json:"address"` - Version string `json:"version"` // major.minor.revision - Other []string `json:"other"` // other application specific data + PubKey crypto.PubKeyEd25519 `json:"pub_key"` + Moniker string `json:"moniker"` + Network string `json:"network"` + RemoteAddr string `json:"remote_addr"` + ListenAddr string `json:"listen_addr"` + Version string `json:"version"` // major.minor.revision + Other []string `json:"other"` // other application specific data } // CONTRACT: two nodes are compactible if the major/minor versions match and network match @@ -53,13 +54,13 @@ func (info *NodeInfo) CompatibleWith(other *NodeInfo) error { return nil } -func (info *NodeInfo) Host() string { - host, _, _ := net.SplitHostPort(info.Address) +func (info *NodeInfo) ListenHost() string { + host, _, _ := net.SplitHostPort(info.ListenAddr) return host } -func (info *NodeInfo) Port() int { - _, port, _ := net.SplitHostPort(info.Address) +func (info *NodeInfo) ListenPort() int { + _, port, _ := net.SplitHostPort(info.ListenAddr) port_i, err := strconv.Atoi(port) if err != nil { return -1 From 4347b91b89fb93bf37e1d233468f0d879df941ba Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Sat, 5 Dec 2015 09:48:08 -0800 Subject: [PATCH 005/309] Remove wrong comment --- pex_reactor.go | 1 - 1 file changed, 1 deletion(-) diff --git a/pex_reactor.go b/pex_reactor.go index 321ec7d7b..f6dacdb13 100644 --- a/pex_reactor.go +++ b/pex_reactor.go @@ -63,7 +63,6 @@ func (pexR *PEXReactor) GetChannels() []*ChannelDescriptor { // Implements Reactor func (pexR *PEXReactor) AddPeer(peer *Peer) { - // XXX Move this into Switch // Add the peer to the address book netAddr := NewNetAddressString(peer.ListenAddr) if peer.IsOutbound() { From 8b308c1c0829406c0e7c12354112ed321a15bdba Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Wed, 9 Dec 2015 13:53:50 -0800 Subject: [PATCH 006/309] Tweak send/recv rates for performance test --- connection.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/connection.go b/connection.go index 494fdd753..944a59352 100644 --- a/connection.go +++ b/connection.go @@ -22,8 +22,8 @@ const ( idleTimeoutMinutes = 5 updateStatsSeconds = 2 pingTimeoutSeconds = 40 - defaultSendRate = 51200 // 50KB/s - defaultRecvRate = 51200 // 50KB/s + defaultSendRate = 512000 // 500KB/s + defaultRecvRate = 512000 // 500KB/s flushThrottleMS = 100 defaultSendQueueCapacity = 1 defaultRecvBufferCapacity = 4096 @@ -608,7 +608,7 @@ func (ch *Channel) recvMsgPacket(packet msgPacket) ([]byte, error) { func (ch *Channel) updateStats() { // Exponential decay of stats. // TODO: optimize. - ch.recentlySent = int64(float64(ch.recentlySent) * 0.5) + ch.recentlySent = int64(float64(ch.recentlySent) * 0.8) } //----------------------------------------------------------------------------- From 44d8e62689e6579ad81b200b45acdc56e6b91d55 Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Mon, 21 Dec 2015 12:55:52 -0800 Subject: [PATCH 007/309] Confirm to go-wire new TypeByte behavior --- pex_reactor.go | 4 ++-- secret_connection.go | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/pex_reactor.go b/pex_reactor.go index f6dacdb13..d7ccc7613 100644 --- a/pex_reactor.go +++ b/pex_reactor.go @@ -114,11 +114,11 @@ func (pexR *PEXReactor) Receive(chID byte, src *Peer, msgBytes []byte) { // Asks peer for more addresses. func (pexR *PEXReactor) RequestPEX(peer *Peer) { - peer.Send(PexChannel, &pexRequestMessage{}) + peer.Send(PexChannel, struct{ PexMessage }{&pexRequestMessage{}}) } func (pexR *PEXReactor) SendAddrs(peer *Peer, addrs []*NetAddress) { - peer.Send(PexChannel, &pexAddrsMessage{Addrs: addrs}) + peer.Send(PexChannel, struct{ PexMessage }{&pexAddrsMessage{Addrs: addrs}}) } // Ensures that sufficient peers are connected. (continuous) diff --git a/secret_connection.go b/secret_connection.go index 1e1cdb4b2..be3e62a9d 100644 --- a/secret_connection.go +++ b/secret_connection.go @@ -96,7 +96,7 @@ func MakeSecretConnection(conn io.ReadWriteCloser, locPrivKey crypto.PrivKeyEd25 } // We've authorized. - sc.remPubKey = remPubKey + sc.remPubKey = remPubKey.(crypto.PubKeyEd25519) return sc, nil } @@ -260,8 +260,8 @@ func signChallenge(challenge *[32]byte, locPrivKey crypto.PrivKeyEd25519) (signa } type authSigMessage struct { - Key crypto.PubKeyEd25519 - Sig crypto.SignatureEd25519 + Key crypto.PubKey + Sig crypto.Signature } func shareAuthSignature(sc *SecretConnection, pubKey crypto.PubKeyEd25519, signature crypto.SignatureEd25519) (*authSigMessage, error) { From 0c9b9fe8bbf1976aa9494083f36bea896834b6ec Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Wed, 23 Dec 2015 14:08:39 -0800 Subject: [PATCH 008/309] Change license to Apache2.0 --- LICENSE | 193 +++++++++++++++++++++++++++++++++++++++++++++++++ LICENSE.md | 206 ----------------------------------------------------- 2 files changed, 193 insertions(+), 206 deletions(-) create mode 100644 LICENSE delete mode 100644 LICENSE.md diff --git a/LICENSE b/LICENSE new file mode 100644 index 000000000..e908e0f95 --- /dev/null +++ b/LICENSE @@ -0,0 +1,193 @@ +Tendermint Go-P2P +Copyright (C) 2015 Tendermint + + + + Apache License + Version 2.0, January 2004 + https://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + https://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSE.md b/LICENSE.md deleted file mode 100644 index ec02173eb..000000000 --- a/LICENSE.md +++ /dev/null @@ -1,206 +0,0 @@ -Tendermint P2P -Copyright (C) 2015 Tendermint - -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU General Public License as published by -the Free Software Foundation, either version 3 of the License, or -(at your option) any later version. - -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU General Public License for more details. - -You should have received a copy of the GNU General Public License -along with this program. If not, see . - -//-------------------------------------------------------------------------------- - -GNU GENERAL PUBLIC LICENSE - -Version 3, 29 June 2007 - -Copyright © 2007 Free Software Foundation, Inc. - -Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. - -Preamble - -The GNU General Public License is a free, copyleft license for software and other kinds of works. - -The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. - -When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. - -To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. - -For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. - -Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. - -For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. - -Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. - -Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. - -The precise terms and conditions for copying, distribution and modification follow. - -TERMS AND CONDITIONS - -0. Definitions. -“This License” refers to version 3 of the GNU General Public License. - -“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. - -“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. - -To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. - -A “covered work” means either the unmodified Program or a work based on the Program. - -To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. - -To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. - -An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. - -1. Source Code. -The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. - -A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. - -The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. - -The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. - -The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. - -The Corresponding Source for a work in source code form is that same work. - -2. Basic Permissions. -All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. - -You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. - -Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. - -3. Protecting Users' Legal Rights From Anti-Circumvention Law. -No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. - -When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. - -4. Conveying Verbatim Copies. -You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. - -You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. - -5. Conveying Modified Source Versions. -You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: - -a) The work must carry prominent notices stating that you modified it, and giving a relevant date. -b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. -c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. -d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. -A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. - -6. Conveying Non-Source Forms. -You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: - -a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. -b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. -c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. -d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. -e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. -A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. - -A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. - -“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. - -If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). - -The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. - -Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. - -7. Additional Terms. -“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. - -When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. - -Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: - -a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or -b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or -c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or -d) Limiting the use for publicity purposes of names of licensors or authors of the material; or -e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or -f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. -All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. - -If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. - -Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. - -8. Termination. -You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). - -However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. - -Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. - -Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. - -9. Acceptance Not Required for Having Copies. -You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. - -10. Automatic Licensing of Downstream Recipients. -Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. - -An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. - -You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. - -11. Patents. -A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. - -A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. - -Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. - -In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. - -If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. - -If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. - -A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. - -Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. - -12. No Surrender of Others' Freedom. -If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. - -13. Use with the GNU Affero General Public License. -Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. - -14. Revised Versions of this License. -The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. - -Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. - -If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. - -Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. - -15. Disclaimer of Warranty. -THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. - -16. Limitation of Liability. -IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - -17. Interpretation of Sections 15 and 16. -If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. - -END OF TERMS AND CONDITIONS From 3abc18d7babe12709f8adc6721540a865e714888 Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Sat, 2 Jan 2016 20:53:10 -0800 Subject: [PATCH 009/309] Add MConnection.Status() --- connection.go | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/connection.go b/connection.go index 944a59352..f0f992146 100644 --- a/connection.go +++ b/connection.go @@ -454,6 +454,30 @@ FOR_LOOP: } } +func (c *MConnection) Status() interface{} { + status := make(map[string]interface{}) + status["sendMonitor"] = c.sendMonitor.Status() + status["recvMonitor"] = c.recvMonitor.Status() + + type channelStatus struct { + SendQueueCapacity int + SendQueueSize int + Priority int + RecentlySent int64 + } + + for _, channel := range c.channels { + status[Fmt("ch[%X]", channel.id)] = channelStatus{ + SendQueueCapacity: cap(channel.sendQueue), + SendQueueSize: int(channel.sendQueueSize), // TODO use atomic + Priority: channel.priority, + RecentlySent: channel.recentlySent, + } + } + + return status +} + //----------------------------------------------------------------------------- type ChannelDescriptor struct { From 1f2c1d07600b9612a1f92f42a3c8c893eafd922c Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Sun, 3 Jan 2016 06:20:18 -0800 Subject: [PATCH 010/309] Fix prioritization logic; Add Status() --- connection.go | 35 +++++++++++++++++++++-------------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/connection.go b/connection.go index f0f992146..9fae4e510 100644 --- a/connection.go +++ b/connection.go @@ -454,27 +454,34 @@ FOR_LOOP: } } -func (c *MConnection) Status() interface{} { - status := make(map[string]interface{}) - status["sendMonitor"] = c.sendMonitor.Status() - status["recvMonitor"] = c.recvMonitor.Status() +type ConnectionStatus struct { + SendMonitor flow.Status + RecvMonitor flow.Status + Channels []ChannelStatus +} - type channelStatus struct { - SendQueueCapacity int - SendQueueSize int - Priority int - RecentlySent int64 - } +type ChannelStatus struct { + ID byte + SendQueueCapacity int + SendQueueSize int + Priority int + RecentlySent int64 +} - for _, channel := range c.channels { - status[Fmt("ch[%X]", channel.id)] = channelStatus{ +func (c *MConnection) Status() ConnectionStatus { + var status ConnectionStatus + status.SendMonitor = c.sendMonitor.Status() + status.RecvMonitor = c.recvMonitor.Status() + status.Channels = make([]ChannelStatus, len(c.channels)) + for i, channel := range c.channels { + status.Channels[i] = ChannelStatus{ + ID: channel.id, SendQueueCapacity: cap(channel.sendQueue), SendQueueSize: int(channel.sendQueueSize), // TODO use atomic Priority: channel.priority, RecentlySent: channel.recentlySent, } } - return status } @@ -605,7 +612,7 @@ func (ch *Channel) writeMsgPacketTo(w io.Writer) (n int, err error) { log.Debug("Write Msg Packet", "conn", ch.conn, "packet", packet) wire.WriteByte(packetTypeMsg, w, &n, &err) wire.WriteBinary(packet, w, &n, &err) - if err != nil { + if err == nil { ch.recentlySent += int64(n) } return From c52524a215d2cc90f718172f06139b53db0ec87c Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Tue, 12 Jan 2016 15:26:00 -0500 Subject: [PATCH 011/309] Initial commit --- LICENSE | 201 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ README.md | 1 + 2 files changed, 202 insertions(+) create mode 100644 LICENSE create mode 100644 README.md diff --git a/LICENSE b/LICENSE new file mode 100644 index 000000000..8dada3eda --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md new file mode 100644 index 000000000..fd01b380c --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# go-rpc \ No newline at end of file From 3d59e13dd8562331fd04cdc99ff755898ec44d5c Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Tue, 12 Jan 2016 16:50:06 -0500 Subject: [PATCH 012/309] move from tendermint/tendermint --- README.md | 5 +- client/http_client.go | 133 ++++++++++ client/log.go | 7 + client/ws_client.go | 119 +++++++++ server/handlers.go | 553 ++++++++++++++++++++++++++++++++++++++++++ server/http_params.go | 89 +++++++ server/http_server.go | 115 +++++++++ server/log.go | 7 + types/types.go | 71 ++++++ version.go | 3 + 10 files changed, 1101 insertions(+), 1 deletion(-) create mode 100644 client/http_client.go create mode 100644 client/log.go create mode 100644 client/ws_client.go create mode 100644 server/handlers.go create mode 100644 server/http_params.go create mode 100644 server/http_server.go create mode 100644 server/log.go create mode 100644 types/types.go create mode 100644 version.go diff --git a/README.md b/README.md index fd01b380c..e74cf8021 100644 --- a/README.md +++ b/README.md @@ -1 +1,4 @@ -# go-rpc \ No newline at end of file +# go-rpc + +HTTP RPC server supporting calls via uri params, jsonrpc, and jsonrpc over websockets + diff --git a/client/http_client.go b/client/http_client.go new file mode 100644 index 000000000..133f2b725 --- /dev/null +++ b/client/http_client.go @@ -0,0 +1,133 @@ +package rpcclient + +import ( + "bytes" + "errors" + "io/ioutil" + "net/http" + "net/url" + "strings" + + . "github.com/tendermint/go-common" + "github.com/tendermint/go-rpc/types" + "github.com/tendermint/go-wire" +) + +// JSON rpc takes params as a slice +type ClientJSONRPC struct { + remote string +} + +func NewClientJSONRPC(remote string) *ClientJSONRPC { + return &ClientJSONRPC{remote} +} + +func (c *ClientJSONRPC) Call(method string, params []interface{}) (interface{}, error) { + return CallHTTP_JSONRPC(c.remote, method, params) +} + +// URI takes params as a map +type ClientURI struct { + remote string +} + +func NewClientURI(remote string) *ClientURI { + if !strings.HasSuffix(remote, "/") { + remote = remote + "/" + } + return &ClientURI{remote} +} + +func (c *ClientURI) Call(method string, params map[string]interface{}) (interface{}, error) { + return CallHTTP_URI(c.remote, method, params) +} + +func CallHTTP_JSONRPC(remote string, method string, params []interface{}) (interface{}, error) { + // Make request and get responseBytes + request := rpctypes.RPCRequest{ + JSONRPC: "2.0", + Method: method, + Params: params, + ID: "", + } + requestBytes := wire.JSONBytes(request) + requestBuf := bytes.NewBuffer(requestBytes) + log.Info(Fmt("RPC request to %v: %v", remote, string(requestBytes))) + httpResponse, err := http.Post(remote, "text/json", requestBuf) + if err != nil { + return nil, err + } + defer httpResponse.Body.Close() + responseBytes, err := ioutil.ReadAll(httpResponse.Body) + if err != nil { + return nil, err + } + log.Info(Fmt("RPC response: %v", string(responseBytes))) + return unmarshalResponseBytes(responseBytes) +} + +func CallHTTP_URI(remote string, method string, params map[string]interface{}) (interface{}, error) { + values, err := argsToURLValues(params) + if err != nil { + return nil, err + } + log.Info(Fmt("URI request to %v: %v", remote, values)) + resp, err := http.PostForm(remote+method, values) + if err != nil { + return nil, err + } + defer resp.Body.Close() + responseBytes, err := ioutil.ReadAll(resp.Body) + if err != nil { + return nil, err + } + return unmarshalResponseBytes(responseBytes) +} + +//------------------------------------------------ + +func unmarshalResponseBytes(responseBytes []byte) (interface{}, error) { + // read response + // if rpc/core/types is imported, the result will unmarshal + // into the correct type + var err error + response := &rpctypes.RPCResponse{} + wire.ReadJSON(response, responseBytes, &err) + if err != nil { + return nil, err + } + errorStr := response.Error + if errorStr != "" { + return nil, errors.New(errorStr) + } + return response.Result, err +} + +func argsToURLValues(args map[string]interface{}) (url.Values, error) { + values := make(url.Values) + if len(args) == 0 { + return values, nil + } + err := argsToJson(args) + if err != nil { + return nil, err + } + for key, val := range args { + values.Set(key, val.(string)) + } + return values, nil +} + +func argsToJson(args map[string]interface{}) error { + var n int + var err error + for k, v := range args { + buf := new(bytes.Buffer) + wire.WriteJSON(v, buf, &n, &err) + if err != nil { + return err + } + args[k] = buf.String() + } + return nil +} diff --git a/client/log.go b/client/log.go new file mode 100644 index 000000000..8b33e2f10 --- /dev/null +++ b/client/log.go @@ -0,0 +1,7 @@ +package rpcclient + +import ( + "github.com/tendermint/log15" +) + +var log = log15.New("module", "rpcclient") diff --git a/client/ws_client.go b/client/ws_client.go new file mode 100644 index 000000000..ae2b324a4 --- /dev/null +++ b/client/ws_client.go @@ -0,0 +1,119 @@ +package rpcclient + +import ( + "net/http" + "time" + + "github.com/gorilla/websocket" + . "github.com/tendermint/go-common" + "github.com/tendermint/go-rpc/types" + "github.com/tendermint/go-wire" +) + +const ( + wsResultsChannelCapacity = 10 + wsWriteTimeoutSeconds = 10 +) + +type WSClient struct { + QuitService + Address string + *websocket.Conn + ResultsCh chan rpctypes.Result // closes upon WSClient.Stop() +} + +// create a new connection +func NewWSClient(addr string) *WSClient { + wsClient := &WSClient{ + Address: addr, + Conn: nil, + ResultsCh: make(chan rpctypes.Result, wsResultsChannelCapacity), + } + wsClient.QuitService = *NewQuitService(log, "WSClient", wsClient) + return wsClient +} + +func (wsc *WSClient) OnStart() error { + wsc.QuitService.OnStart() + err := wsc.dial() + if err != nil { + return err + } + go wsc.receiveEventsRoutine() + return nil +} + +func (wsc *WSClient) dial() error { + // Dial + dialer := websocket.DefaultDialer + rHeader := http.Header{} + con, _, err := dialer.Dial(wsc.Address, rHeader) + if err != nil { + return err + } + // Set the ping/pong handlers + con.SetPingHandler(func(m string) error { + // NOTE: https://github.com/gorilla/websocket/issues/97 + log.Debug("Client received ping, writing pong") + go con.WriteControl(websocket.PongMessage, []byte(m), time.Now().Add(time.Second*wsWriteTimeoutSeconds)) + return nil + }) + con.SetPongHandler(func(m string) error { + log.Debug("Client received pong") + // NOTE: https://github.com/gorilla/websocket/issues/97 + return nil + }) + wsc.Conn = con + return nil +} + +func (wsc *WSClient) OnStop() { + wsc.QuitService.OnStop() + // ResultsCh is closed in receiveEventsRoutine. +} + +func (wsc *WSClient) receiveEventsRoutine() { + for { + log.Notice("Waiting for wsc message ...") + _, data, err := wsc.ReadMessage() + if err != nil { + log.Info("WSClient failed to read message", "error", err, "data", string(data)) + wsc.Stop() + break + } else { + var response rpctypes.RPCResponse + wire.ReadJSON(&response, data, &err) + if err != nil { + log.Info("WSClient failed to parse message", "error", err, "data", string(data)) + wsc.Stop() + break + } + wsc.ResultsCh <- response.Result + } + } + + // Cleanup + close(wsc.ResultsCh) +} + +// subscribe to an event +func (wsc *WSClient) Subscribe(eventid string) error { + err := wsc.WriteJSON(rpctypes.RPCRequest{ + JSONRPC: "2.0", + ID: "", + Method: "subscribe", + Params: []interface{}{eventid}, + }) + return err +} + +// unsubscribe from an event +func (wsc *WSClient) Unsubscribe(eventid string) error { + err := wsc.WriteJSON(rpctypes.RPCRequest{ + JSONRPC: "2.0", + ID: "", + Method: "unsubscribe", + Params: []interface{}{eventid}, + }) + return err +} diff --git a/server/handlers.go b/server/handlers.go new file mode 100644 index 000000000..64c151808 --- /dev/null +++ b/server/handlers.go @@ -0,0 +1,553 @@ +package rpcserver + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io/ioutil" + "net/http" + "reflect" + "sort" + "time" + + "github.com/gorilla/websocket" + . "github.com/tendermint/go-common" + "github.com/tendermint/go-events" + . "github.com/tendermint/go-rpc/types" + "github.com/tendermint/go-wire" +) + +func RegisterRPCFuncs(mux *http.ServeMux, funcMap map[string]*RPCFunc) { + // HTTP endpoints + for funcName, rpcFunc := range funcMap { + mux.HandleFunc("/"+funcName, makeHTTPHandler(rpcFunc)) + } + + // JSONRPC endpoints + mux.HandleFunc("/", makeJSONRPCHandler(funcMap)) +} + +//------------------------------------- +// function introspection + +// holds all type information for each function +type RPCFunc struct { + f reflect.Value // underlying rpc function + args []reflect.Type // type of each function arg + returns []reflect.Type // type of each return arg + argNames []string // name of each argument + ws bool // websocket only +} + +// wraps a function for quicker introspection +func NewRPCFunc(f interface{}, args []string) *RPCFunc { + return &RPCFunc{ + f: reflect.ValueOf(f), + args: funcArgTypes(f), + returns: funcReturnTypes(f), + argNames: args, + ws: false, + } +} + +func NewWSRPCFunc(f interface{}, args []string) *RPCFunc { + return &RPCFunc{ + f: reflect.ValueOf(f), + args: funcArgTypes(f), + returns: funcReturnTypes(f), + argNames: args, + ws: true, + } +} + +// return a function's argument types +func funcArgTypes(f interface{}) []reflect.Type { + t := reflect.TypeOf(f) + n := t.NumIn() + typez := make([]reflect.Type, n) + for i := 0; i < n; i++ { + typez[i] = t.In(i) + } + return typez +} + +// return a function's return types +func funcReturnTypes(f interface{}) []reflect.Type { + t := reflect.TypeOf(f) + n := t.NumOut() + typez := make([]reflect.Type, n) + for i := 0; i < n; i++ { + typez[i] = t.Out(i) + } + return typez +} + +// function introspection +//----------------------------------------------------------------------------- +// rpc.json + +// jsonrpc calls grab the given method's function info and runs reflect.Call +func makeJSONRPCHandler(funcMap map[string]*RPCFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + b, _ := ioutil.ReadAll(r.Body) + // if its an empty request (like from a browser), + // just display a list of functions + if len(b) == 0 { + writeListOfEndpoints(w, r, funcMap) + return + } + + var request RPCRequest + err := json.Unmarshal(b, &request) + if err != nil { + WriteRPCResponseHTTP(w, NewRPCResponse("", nil, err.Error())) + return + } + if len(r.URL.Path) > 1 { + WriteRPCResponseHTTP(w, NewRPCResponse(request.ID, nil, fmt.Sprintf("Invalid JSONRPC endpoint %s", r.URL.Path))) + return + } + rpcFunc := funcMap[request.Method] + if rpcFunc == nil { + WriteRPCResponseHTTP(w, NewRPCResponse(request.ID, nil, "RPC method unknown: "+request.Method)) + return + } + if rpcFunc.ws { + WriteRPCResponseHTTP(w, NewRPCResponse(request.ID, nil, "RPC method is only for websockets: "+request.Method)) + return + } + args, err := jsonParamsToArgs(rpcFunc, request.Params) + if err != nil { + WriteRPCResponseHTTP(w, NewRPCResponse(request.ID, nil, err.Error())) + return + } + returns := rpcFunc.f.Call(args) + log.Info("HTTPJSONRPC", "method", request.Method, "args", args, "returns", returns) + result, err := unreflectResult(returns) + if err != nil { + WriteRPCResponseHTTP(w, NewRPCResponse(request.ID, nil, err.Error())) + return + } + WriteRPCResponseHTTP(w, NewRPCResponse(request.ID, result, "")) + } +} + +// Convert a list of interfaces to properly typed values +func jsonParamsToArgs(rpcFunc *RPCFunc, params []interface{}) ([]reflect.Value, error) { + if len(rpcFunc.argNames) != len(params) { + return nil, errors.New(fmt.Sprintf("Expected %v parameters (%v), got %v (%v)", + len(rpcFunc.argNames), rpcFunc.argNames, len(params), params)) + } + values := make([]reflect.Value, len(params)) + for i, p := range params { + ty := rpcFunc.args[i] + v, err := _jsonObjectToArg(ty, p) + if err != nil { + return nil, err + } + values[i] = v + } + return values, nil +} + +// Same as above, but with the first param the websocket connection +func jsonParamsToArgsWS(rpcFunc *RPCFunc, params []interface{}, wsCtx WSRPCContext) ([]reflect.Value, error) { + if len(rpcFunc.argNames) != len(params) { + return nil, errors.New(fmt.Sprintf("Expected %v parameters (%v), got %v (%v)", + len(rpcFunc.argNames)-1, rpcFunc.argNames[1:], len(params), params)) + } + values := make([]reflect.Value, len(params)+1) + values[0] = reflect.ValueOf(wsCtx) + for i, p := range params { + ty := rpcFunc.args[i+1] + v, err := _jsonObjectToArg(ty, p) + if err != nil { + return nil, err + } + values[i+1] = v + } + return values, nil +} + +func _jsonObjectToArg(ty reflect.Type, object interface{}) (reflect.Value, error) { + var err error + v := reflect.New(ty) + wire.ReadJSONObjectPtr(v.Interface(), object, &err) + if err != nil { + return v, err + } + v = v.Elem() + return v, nil +} + +// rpc.json +//----------------------------------------------------------------------------- +// rpc.http + +// convert from a function name to the http handler +func makeHTTPHandler(rpcFunc *RPCFunc) func(http.ResponseWriter, *http.Request) { + // Exception for websocket endpoints + if rpcFunc.ws { + return func(w http.ResponseWriter, r *http.Request) { + WriteRPCResponseHTTP(w, NewRPCResponse("", nil, "This RPC method is only for websockets")) + } + } + // All other endpoints + return func(w http.ResponseWriter, r *http.Request) { + args, err := httpParamsToArgs(rpcFunc, r) + if err != nil { + WriteRPCResponseHTTP(w, NewRPCResponse("", nil, err.Error())) + return + } + returns := rpcFunc.f.Call(args) + log.Info("HTTPRestRPC", "method", r.URL.Path, "args", args, "returns", returns) + result, err := unreflectResult(returns) + if err != nil { + WriteRPCResponseHTTP(w, NewRPCResponse("", nil, err.Error())) + return + } + WriteRPCResponseHTTP(w, NewRPCResponse("", result, "")) + } +} + +// Covert an http query to a list of properly typed values. +// To be properly decoded the arg must be a concrete type from tendermint (if its an interface). +func httpParamsToArgs(rpcFunc *RPCFunc, r *http.Request) ([]reflect.Value, error) { + argTypes := rpcFunc.args + argNames := rpcFunc.argNames + + var err error + values := make([]reflect.Value, len(argNames)) + for i, name := range argNames { + ty := argTypes[i] + arg := GetParam(r, name) + values[i], err = _jsonStringToArg(ty, arg) + if err != nil { + return nil, err + } + } + return values, nil +} + +func _jsonStringToArg(ty reflect.Type, arg string) (reflect.Value, error) { + var err error + v := reflect.New(ty) + wire.ReadJSONPtr(v.Interface(), []byte(arg), &err) + if err != nil { + return v, err + } + v = v.Elem() + return v, nil +} + +// rpc.http +//----------------------------------------------------------------------------- +// rpc.websocket + +const ( + writeChanCapacity = 1000 + wsWriteTimeoutSeconds = 30 // each write times out after this + wsReadTimeoutSeconds = 30 // connection times out if we haven't received *anything* in this long, not even pings. + wsPingTickerSeconds = 10 // send a ping every PingTickerSeconds. +) + +// a single websocket connection +// contains listener id, underlying ws connection, +// and the event switch for subscribing to events +type wsConnection struct { + QuitService + + remoteAddr string + baseConn *websocket.Conn + writeChan chan RPCResponse + readTimeout *time.Timer + pingTicker *time.Ticker + + funcMap map[string]*RPCFunc + evsw *events.EventSwitch +} + +// new websocket connection wrapper +func NewWSConnection(baseConn *websocket.Conn, funcMap map[string]*RPCFunc, evsw *events.EventSwitch) *wsConnection { + wsc := &wsConnection{ + remoteAddr: baseConn.RemoteAddr().String(), + baseConn: baseConn, + writeChan: make(chan RPCResponse, writeChanCapacity), // error when full. + funcMap: funcMap, + evsw: evsw, + } + wsc.QuitService = *NewQuitService(log, "wsConnection", wsc) + return wsc +} + +// wsc.Start() blocks until the connection closes. +func (wsc *wsConnection) OnStart() error { + wsc.QuitService.OnStart() + + // Read subscriptions/unsubscriptions to events + go wsc.readRoutine() + + // Custom Ping handler to touch readTimeout + wsc.readTimeout = time.NewTimer(time.Second * wsReadTimeoutSeconds) + wsc.pingTicker = time.NewTicker(time.Second * wsPingTickerSeconds) + wsc.baseConn.SetPingHandler(func(m string) error { + // NOTE: https://github.com/gorilla/websocket/issues/97 + go wsc.baseConn.WriteControl(websocket.PongMessage, []byte(m), time.Now().Add(time.Second*wsWriteTimeoutSeconds)) + wsc.readTimeout.Reset(time.Second * wsReadTimeoutSeconds) + return nil + }) + wsc.baseConn.SetPongHandler(func(m string) error { + // NOTE: https://github.com/gorilla/websocket/issues/97 + wsc.readTimeout.Reset(time.Second * wsReadTimeoutSeconds) + return nil + }) + go wsc.readTimeoutRoutine() + + // Write responses, BLOCKING. + wsc.writeRoutine() + return nil +} + +func (wsc *wsConnection) OnStop() { + wsc.QuitService.OnStop() + wsc.evsw.RemoveListener(wsc.remoteAddr) + wsc.readTimeout.Stop() + wsc.pingTicker.Stop() + // The write loop closes the websocket connection + // when it exits its loop, and the read loop + // closes the writeChan +} + +func (wsc *wsConnection) readTimeoutRoutine() { + select { + case <-wsc.readTimeout.C: + log.Notice("Stopping connection due to read timeout") + wsc.Stop() + case <-wsc.Quit: + return + } +} + +// Implements WSRPCConnection +func (wsc *wsConnection) GetRemoteAddr() string { + return wsc.remoteAddr +} + +// Implements WSRPCConnection +func (wsc *wsConnection) GetEventSwitch() *events.EventSwitch { + return wsc.evsw +} + +// Implements WSRPCConnection +// Blocking write to writeChan until service stops. +func (wsc *wsConnection) WriteRPCResponse(resp RPCResponse) { + select { + case <-wsc.Quit: + return + case wsc.writeChan <- resp: + } +} + +// Implements WSRPCConnection +// Nonblocking write. +func (wsc *wsConnection) TryWriteRPCResponse(resp RPCResponse) bool { + select { + case <-wsc.Quit: + return false + case wsc.writeChan <- resp: + return true + default: + return false + } +} + +// Read from the socket and subscribe to or unsubscribe from events +func (wsc *wsConnection) readRoutine() { + // Do not close writeChan, to allow WriteRPCResponse() to fail. + // defer close(wsc.writeChan) + + for { + select { + case <-wsc.Quit: + return + default: + var in []byte + // Do not set a deadline here like below: + // wsc.baseConn.SetReadDeadline(time.Now().Add(time.Second * wsReadTimeoutSeconds)) + // The client may not send anything for a while. + // We use `readTimeout` to handle read timeouts. + _, in, err := wsc.baseConn.ReadMessage() + if err != nil { + log.Notice("Failed to read from connection", "remote", wsc.remoteAddr) + // an error reading the connection, + // kill the connection + wsc.Stop() + return + } + var request RPCRequest + err = json.Unmarshal(in, &request) + if err != nil { + errStr := fmt.Sprintf("Error unmarshaling data: %s", err.Error()) + wsc.WriteRPCResponse(NewRPCResponse(request.ID, nil, errStr)) + continue + } + + // Now, fetch the RPCFunc and execute it. + + rpcFunc := wsc.funcMap[request.Method] + if rpcFunc == nil { + wsc.WriteRPCResponse(NewRPCResponse(request.ID, nil, "RPC method unknown: "+request.Method)) + continue + } + var args []reflect.Value + if rpcFunc.ws { + wsCtx := WSRPCContext{Request: request, WSRPCConnection: wsc} + args, err = jsonParamsToArgsWS(rpcFunc, request.Params, wsCtx) + } else { + args, err = jsonParamsToArgs(rpcFunc, request.Params) + } + if err != nil { + wsc.WriteRPCResponse(NewRPCResponse(request.ID, nil, err.Error())) + continue + } + returns := rpcFunc.f.Call(args) + log.Info("WSJSONRPC", "method", request.Method, "args", args, "returns", returns) + result, err := unreflectResult(returns) + if err != nil { + wsc.WriteRPCResponse(NewRPCResponse(request.ID, nil, err.Error())) + continue + } else { + wsc.WriteRPCResponse(NewRPCResponse(request.ID, result, "")) + continue + } + + } + } +} + +// receives on a write channel and writes out on the socket +func (wsc *wsConnection) writeRoutine() { + defer wsc.baseConn.Close() + var n, err = int(0), error(nil) + for { + select { + case <-wsc.Quit: + return + case <-wsc.pingTicker.C: + err := wsc.baseConn.WriteMessage(websocket.PingMessage, []byte{}) + if err != nil { + log.Error("Failed to write ping message on websocket", "error", err) + wsc.Stop() + return + } + case msg := <-wsc.writeChan: + buf := new(bytes.Buffer) + wire.WriteJSON(msg, buf, &n, &err) + if err != nil { + log.Error("Failed to marshal RPCResponse to JSON", "error", err) + } else { + wsc.baseConn.SetWriteDeadline(time.Now().Add(time.Second * wsWriteTimeoutSeconds)) + bufBytes := buf.Bytes() + if err = wsc.baseConn.WriteMessage(websocket.TextMessage, bufBytes); err != nil { + log.Warn("Failed to write response on websocket", "error", err) + wsc.Stop() + return + } + } + } + } +} + +//---------------------------------------- + +// Main manager for all websocket connections +// Holds the event switch +// NOTE: The websocket path is defined externally, e.g. in node/node.go +type WebsocketManager struct { + websocket.Upgrader + funcMap map[string]*RPCFunc + evsw *events.EventSwitch +} + +func NewWebsocketManager(funcMap map[string]*RPCFunc, evsw *events.EventSwitch) *WebsocketManager { + return &WebsocketManager{ + funcMap: funcMap, + evsw: evsw, + Upgrader: websocket.Upgrader{ + ReadBufferSize: 1024, + WriteBufferSize: 1024, + CheckOrigin: func(r *http.Request) bool { + // TODO + return true + }, + }, + } +} + +// Upgrade the request/response (via http.Hijack) and starts the wsConnection. +func (wm *WebsocketManager) WebsocketHandler(w http.ResponseWriter, r *http.Request) { + wsConn, err := wm.Upgrade(w, r, nil) + if err != nil { + // TODO - return http error + log.Error("Failed to upgrade to websocket connection", "error", err) + return + } + + // register connection + con := NewWSConnection(wsConn, wm.funcMap, wm.evsw) + log.Notice("New websocket connection", "remote", con.remoteAddr) + con.Start() // Blocking +} + +// rpc.websocket +//----------------------------------------------------------------------------- + +// returns is result struct and error. If error is not nil, return it +func unreflectResult(returns []reflect.Value) (interface{}, error) { + errV := returns[1] + if errV.Interface() != nil { + return nil, fmt.Errorf("%v", errV.Interface()) + } + return returns[0].Interface(), nil +} + +// writes a list of available rpc endpoints as an html page +func writeListOfEndpoints(w http.ResponseWriter, r *http.Request, funcMap map[string]*RPCFunc) { + noArgNames := []string{} + argNames := []string{} + for name, funcData := range funcMap { + if len(funcData.args) == 0 { + noArgNames = append(noArgNames, name) + } else { + argNames = append(argNames, name) + } + } + sort.Strings(noArgNames) + sort.Strings(argNames) + buf := new(bytes.Buffer) + buf.WriteString("") + buf.WriteString("
Available endpoints:
") + + for _, name := range noArgNames { + link := fmt.Sprintf("http://%s/%s", r.Host, name) + buf.WriteString(fmt.Sprintf("%s
", link, link)) + } + + buf.WriteString("
Endpoints that require arguments:
") + for _, name := range argNames { + link := fmt.Sprintf("http://%s/%s?", r.Host, name) + funcData := funcMap[name] + for i, argName := range funcData.argNames { + link += argName + "=_" + if i < len(funcData.argNames)-1 { + link += "&" + } + } + buf.WriteString(fmt.Sprintf("%s
", link, link)) + } + buf.WriteString("") + w.Header().Set("Content-Type", "text/html") + w.WriteHeader(200) + w.Write(buf.Bytes()) +} diff --git a/server/http_params.go b/server/http_params.go new file mode 100644 index 000000000..acf5b4c8c --- /dev/null +++ b/server/http_params.go @@ -0,0 +1,89 @@ +package rpcserver + +import ( + "encoding/hex" + "fmt" + "net/http" + "regexp" + "strconv" +) + +var ( + // Parts of regular expressions + atom = "[A-Z0-9!#$%&'*+\\-/=?^_`{|}~]+" + dotAtom = atom + `(?:\.` + atom + `)*` + domain = `[A-Z0-9.-]+\.[A-Z]{2,4}` + + RE_HEX = regexp.MustCompile(`^(?i)[a-f0-9]+$`) + RE_EMAIL = regexp.MustCompile(`^(?i)(` + dotAtom + `)@(` + dotAtom + `)$`) + RE_ADDRESS = regexp.MustCompile(`^(?i)[a-z0-9]{25,34}$`) + RE_HOST = regexp.MustCompile(`^(?i)(` + domain + `)$`) + + //RE_ID12 = regexp.MustCompile(`^[a-zA-Z0-9]{12}$`) +) + +func GetParam(r *http.Request, param string) string { + s := r.URL.Query().Get(param) + if s == "" { + s = r.FormValue(param) + } + return s +} + +func GetParamByteSlice(r *http.Request, param string) ([]byte, error) { + s := GetParam(r, param) + return hex.DecodeString(s) +} + +func GetParamInt64(r *http.Request, param string) (int64, error) { + s := GetParam(r, param) + i, err := strconv.ParseInt(s, 10, 64) + if err != nil { + return 0, fmt.Errorf(param, err.Error()) + } + return i, nil +} + +func GetParamInt32(r *http.Request, param string) (int32, error) { + s := GetParam(r, param) + i, err := strconv.ParseInt(s, 10, 32) + if err != nil { + return 0, fmt.Errorf(param, err.Error()) + } + return int32(i), nil +} + +func GetParamUint64(r *http.Request, param string) (uint64, error) { + s := GetParam(r, param) + i, err := strconv.ParseUint(s, 10, 64) + if err != nil { + return 0, fmt.Errorf(param, err.Error()) + } + return i, nil +} + +func GetParamUint(r *http.Request, param string) (uint, error) { + s := GetParam(r, param) + i, err := strconv.ParseUint(s, 10, 64) + if err != nil { + return 0, fmt.Errorf(param, err.Error()) + } + return uint(i), nil +} + +func GetParamRegexp(r *http.Request, param string, re *regexp.Regexp) (string, error) { + s := GetParam(r, param) + if !re.MatchString(s) { + return "", fmt.Errorf(param, "Did not match regular expression %v", re.String()) + } + return s, nil +} + +func GetParamFloat64(r *http.Request, param string) (float64, error) { + s := GetParam(r, param) + f, err := strconv.ParseFloat(s, 64) + if err != nil { + return 0, fmt.Errorf(param, err.Error()) + } + return f, nil +} diff --git a/server/http_server.go b/server/http_server.go new file mode 100644 index 000000000..37b01ceee --- /dev/null +++ b/server/http_server.go @@ -0,0 +1,115 @@ +// Commons for HTTP handling +package rpcserver + +import ( + "bufio" + "fmt" + "net" + "net/http" + "runtime/debug" + "time" + + "github.com/tendermint/go-alert" + . "github.com/tendermint/go-common" + . "github.com/tendermint/go-rpc/types" + "github.com/tendermint/go-wire" +) + +func StartHTTPServer(listenAddr string, handler http.Handler) (net.Listener, error) { + log.Notice(Fmt("Starting RPC HTTP server on %v", listenAddr)) + listener, err := net.Listen("tcp", listenAddr) + if err != nil { + return nil, fmt.Errorf("Failed to listen to %v", listenAddr) + } + go func() { + res := http.Serve( + listener, + RecoverAndLogHandler(handler), + ) + log.Crit("RPC HTTP server stopped", "result", res) + }() + return listener, nil +} + +func WriteRPCResponseHTTP(w http.ResponseWriter, res RPCResponse) { + jsonBytes := wire.JSONBytesPretty(res) + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(200) + w.Write(jsonBytes) +} + +//----------------------------------------------------------------------------- + +// Wraps an HTTP handler, adding error logging. +// If the inner function panics, the outer function recovers, logs, sends an +// HTTP 500 error response. +func RecoverAndLogHandler(handler http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Wrap the ResponseWriter to remember the status + rww := &ResponseWriterWrapper{-1, w} + begin := time.Now() + + // Common headers + origin := r.Header.Get("Origin") + rww.Header().Set("Access-Control-Allow-Origin", origin) + rww.Header().Set("Access-Control-Allow-Credentials", "true") + rww.Header().Set("Access-Control-Expose-Headers", "X-Server-Time") + rww.Header().Set("X-Server-Time", fmt.Sprintf("%v", begin.Unix())) + + defer func() { + // Send a 500 error if a panic happens during a handler. + // Without this, Chrome & Firefox were retrying aborted ajax requests, + // at least to my localhost. + if e := recover(); e != nil { + + // If RPCResponse + if res, ok := e.(RPCResponse); ok { + WriteRPCResponseHTTP(rww, res) + } else { + // For the rest, + log.Error("Panic in RPC HTTP handler", "error", e, "stack", string(debug.Stack())) + rww.WriteHeader(http.StatusInternalServerError) + WriteRPCResponseHTTP(rww, NewRPCResponse("", nil, Fmt("Internal Server Error: %v", e))) + } + } + + // Finally, log. + durationMS := time.Since(begin).Nanoseconds() / 1000000 + if rww.Status == -1 { + rww.Status = 200 + } + log.Info("Served RPC HTTP response", + "method", r.Method, "url", r.URL, + "status", rww.Status, "duration", durationMS, + "remoteAddr", r.RemoteAddr, + ) + }() + + handler.ServeHTTP(rww, r) + }) +} + +// Remember the status for logging +type ResponseWriterWrapper struct { + Status int + http.ResponseWriter +} + +func (w *ResponseWriterWrapper) WriteHeader(status int) { + w.Status = status + w.ResponseWriter.WriteHeader(status) +} + +// implements http.Hijacker +func (w *ResponseWriterWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) { + return w.ResponseWriter.(http.Hijacker).Hijack() +} + +// Stick it as a deferred statement in gouroutines to prevent the program from crashing. +func Recover(daemonName string) { + if e := recover(); e != nil { + stack := string(debug.Stack()) + errorString := fmt.Sprintf("[%s] %s\n%s", daemonName, e, stack) + alert.Alert(errorString) + } +} diff --git a/server/log.go b/server/log.go new file mode 100644 index 000000000..704e22e30 --- /dev/null +++ b/server/log.go @@ -0,0 +1,7 @@ +package rpcserver + +import ( + "github.com/tendermint/log15" +) + +var log = log15.New("module", "rpcserver") diff --git a/types/types.go b/types/types.go new file mode 100644 index 000000000..4905d000b --- /dev/null +++ b/types/types.go @@ -0,0 +1,71 @@ +package rpctypes + +import ( + "github.com/tendermint/go-events" +) + +type RPCRequest struct { + JSONRPC string `json:"jsonrpc"` + ID string `json:"id"` + Method string `json:"method"` + Params []interface{} `json:"params"` +} + +func NewRPCRequest(id string, method string, params []interface{}) RPCRequest { + return RPCRequest{ + JSONRPC: "2.0", + ID: id, + Method: method, + Params: params, + } +} + +//---------------------------------------- + +/* +Result is a generic interface. +Applications should register type-bytes like so: + +var _ = wire.RegisterInterface( + struct{ Result }{}, + wire.ConcreteType{&ResultGenesis{}, ResultTypeGenesis}, + wire.ConcreteType{&ResultBlockchainInfo{}, ResultTypeBlockchainInfo}, + ... +) +*/ +type Result interface { +} + +//---------------------------------------- + +type RPCResponse struct { + JSONRPC string `json:"jsonrpc"` + ID string `json:"id"` + Result Result `json:"result"` + Error string `json:"error"` +} + +func NewRPCResponse(id string, res Result, err string) RPCResponse { + return RPCResponse{ + JSONRPC: "2.0", + ID: id, + Result: res, + Error: err, + } +} + +//---------------------------------------- + +// *wsConnection implements this interface. +type WSRPCConnection interface { + GetRemoteAddr() string + GetEventSwitch() *events.EventSwitch + WriteRPCResponse(resp RPCResponse) + TryWriteRPCResponse(resp RPCResponse) bool +} + +// websocket-only RPCFuncs take this as the first parameter. +type WSRPCContext struct { + Request RPCRequest + WSRPCConnection +} diff --git a/version.go b/version.go new file mode 100644 index 000000000..2982824dd --- /dev/null +++ b/version.go @@ -0,0 +1,3 @@ +package rpc + +const Version = "0.4.0" From 0bcae125c20df24f5d592453d119ec0f4e0dc89c Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Tue, 12 Jan 2016 18:29:31 -0500 Subject: [PATCH 013/309] use comma separated string for arg names --- client/ws_client.go | 3 --- server/handlers.go | 26 +++++++++++++++----------- 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/client/ws_client.go b/client/ws_client.go index ae2b324a4..4ce1ca07e 100644 --- a/client/ws_client.go +++ b/client/ws_client.go @@ -54,12 +54,10 @@ func (wsc *WSClient) dial() error { // Set the ping/pong handlers con.SetPingHandler(func(m string) error { // NOTE: https://github.com/gorilla/websocket/issues/97 - log.Debug("Client received ping, writing pong") go con.WriteControl(websocket.PongMessage, []byte(m), time.Now().Add(time.Second*wsWriteTimeoutSeconds)) return nil }) con.SetPongHandler(func(m string) error { - log.Debug("Client received pong") // NOTE: https://github.com/gorilla/websocket/issues/97 return nil }) @@ -74,7 +72,6 @@ func (wsc *WSClient) OnStop() { func (wsc *WSClient) receiveEventsRoutine() { for { - log.Notice("Waiting for wsc message ...") _, data, err := wsc.ReadMessage() if err != nil { log.Info("WSClient failed to read message", "error", err, "data", string(data)) diff --git a/server/handlers.go b/server/handlers.go index 64c151808..843a7ada8 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -9,6 +9,7 @@ import ( "net/http" "reflect" "sort" + "strings" "time" "github.com/gorilla/websocket" @@ -41,23 +42,26 @@ type RPCFunc struct { } // wraps a function for quicker introspection -func NewRPCFunc(f interface{}, args []string) *RPCFunc { - return &RPCFunc{ - f: reflect.ValueOf(f), - args: funcArgTypes(f), - returns: funcReturnTypes(f), - argNames: args, - ws: false, - } +// f is the function, args are comma separated argument names +func NewRPCFunc(f interface{}, args string) *RPCFunc { + return newRPCFunc(f, args, false) } -func NewWSRPCFunc(f interface{}, args []string) *RPCFunc { +func NewWSRPCFunc(f interface{}, args string) *RPCFunc { + return newRPCFunc(f, args, true) +} + +func newRPCFunc(f interface{}, args string, ws bool) *RPCFunc { + var argNames []string + if args != "" { + argNames = strings.Split(args, ",") + } return &RPCFunc{ f: reflect.ValueOf(f), args: funcArgTypes(f), returns: funcReturnTypes(f), - argNames: args, - ws: true, + argNames: argNames, + ws: ws, } } From aff561d8c3a904d87ff9eb859b467772d8506e08 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Wed, 13 Jan 2016 18:37:35 -0500 Subject: [PATCH 014/309] RPCResponse.Result is json.RawMessage --- client/http_client.go | 25 ++++++++++++++----------- client/ws_client.go | 4 ++-- server/handlers.go | 18 +++++++++++------- server/http_server.go | 9 +++++++-- types/types.go | 16 ++++++++++------ 5 files changed, 44 insertions(+), 28 deletions(-) diff --git a/client/http_client.go b/client/http_client.go index 133f2b725..f614a776e 100644 --- a/client/http_client.go +++ b/client/http_client.go @@ -2,6 +2,7 @@ package rpcclient import ( "bytes" + "encoding/json" "errors" "io/ioutil" "net/http" @@ -22,8 +23,8 @@ func NewClientJSONRPC(remote string) *ClientJSONRPC { return &ClientJSONRPC{remote} } -func (c *ClientJSONRPC) Call(method string, params []interface{}) (interface{}, error) { - return CallHTTP_JSONRPC(c.remote, method, params) +func (c *ClientJSONRPC) Call(method string, params []interface{}, result interface{}) (interface{}, error) { + return CallHTTP_JSONRPC(c.remote, method, params, result) } // URI takes params as a map @@ -38,11 +39,11 @@ func NewClientURI(remote string) *ClientURI { return &ClientURI{remote} } -func (c *ClientURI) Call(method string, params map[string]interface{}) (interface{}, error) { - return CallHTTP_URI(c.remote, method, params) +func (c *ClientURI) Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) { + return CallHTTP_URI(c.remote, method, params, result) } -func CallHTTP_JSONRPC(remote string, method string, params []interface{}) (interface{}, error) { +func CallHTTP_JSONRPC(remote string, method string, params []interface{}, result interface{}) (interface{}, error) { // Make request and get responseBytes request := rpctypes.RPCRequest{ JSONRPC: "2.0", @@ -63,10 +64,10 @@ func CallHTTP_JSONRPC(remote string, method string, params []interface{}) (inter return nil, err } log.Info(Fmt("RPC response: %v", string(responseBytes))) - return unmarshalResponseBytes(responseBytes) + return unmarshalResponseBytes(responseBytes, result) } -func CallHTTP_URI(remote string, method string, params map[string]interface{}) (interface{}, error) { +func CallHTTP_URI(remote string, method string, params map[string]interface{}, result interface{}) (interface{}, error) { values, err := argsToURLValues(params) if err != nil { return nil, err @@ -81,18 +82,18 @@ func CallHTTP_URI(remote string, method string, params map[string]interface{}) ( if err != nil { return nil, err } - return unmarshalResponseBytes(responseBytes) + return unmarshalResponseBytes(responseBytes, result) } //------------------------------------------------ -func unmarshalResponseBytes(responseBytes []byte) (interface{}, error) { +func unmarshalResponseBytes(responseBytes []byte, result interface{}) (interface{}, error) { // read response // if rpc/core/types is imported, the result will unmarshal // into the correct type var err error response := &rpctypes.RPCResponse{} - wire.ReadJSON(response, responseBytes, &err) + err = json.Unmarshal(responseBytes, response) if err != nil { return nil, err } @@ -100,7 +101,9 @@ func unmarshalResponseBytes(responseBytes []byte) (interface{}, error) { if errorStr != "" { return nil, errors.New(errorStr) } - return response.Result, err + // unmarshal the RawMessage into the result + result = wire.ReadJSONPtr(result, *response.Result, &err) + return result, err } func argsToURLValues(args map[string]interface{}) (url.Values, error) { diff --git a/client/ws_client.go b/client/ws_client.go index 4ce1ca07e..e0dc349ce 100644 --- a/client/ws_client.go +++ b/client/ws_client.go @@ -1,13 +1,13 @@ package rpcclient import ( + "encoding/json" "net/http" "time" "github.com/gorilla/websocket" . "github.com/tendermint/go-common" "github.com/tendermint/go-rpc/types" - "github.com/tendermint/go-wire" ) const ( @@ -79,7 +79,7 @@ func (wsc *WSClient) receiveEventsRoutine() { break } else { var response rpctypes.RPCResponse - wire.ReadJSON(&response, data, &err) + err := json.Unmarshal(data, &response) if err != nil { log.Info("WSClient failed to parse message", "error", err, "data", string(data)) wsc.Stop() diff --git a/server/handlers.go b/server/handlers.go index 843a7ada8..a463b21e1 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -19,6 +19,8 @@ import ( "github.com/tendermint/go-wire" ) +// Adds a route for each function in the funcMap, as well as general jsonrpc and websocket handlers for all functions. +// "result" is the interface on which the result objects are registered, and is popualted with every RPCResponse func RegisterRPCFuncs(mux *http.ServeMux, funcMap map[string]*RPCFunc) { // HTTP endpoints for funcName, rpcFunc := range funcMap { @@ -433,7 +435,6 @@ func (wsc *wsConnection) readRoutine() { // receives on a write channel and writes out on the socket func (wsc *wsConnection) writeRoutine() { defer wsc.baseConn.Close() - var n, err = int(0), error(nil) for { select { case <-wsc.Quit: @@ -446,14 +447,12 @@ func (wsc *wsConnection) writeRoutine() { return } case msg := <-wsc.writeChan: - buf := new(bytes.Buffer) - wire.WriteJSON(msg, buf, &n, &err) + jsonBytes, err := json.Marshal(msg) if err != nil { log.Error("Failed to marshal RPCResponse to JSON", "error", err) } else { wsc.baseConn.SetWriteDeadline(time.Now().Add(time.Second * wsWriteTimeoutSeconds)) - bufBytes := buf.Bytes() - if err = wsc.baseConn.WriteMessage(websocket.TextMessage, bufBytes); err != nil { + if err = wsc.baseConn.WriteMessage(websocket.TextMessage, jsonBytes); err != nil { log.Warn("Failed to write response on websocket", "error", err) wsc.Stop() return @@ -507,13 +506,18 @@ func (wm *WebsocketManager) WebsocketHandler(w http.ResponseWriter, r *http.Requ // rpc.websocket //----------------------------------------------------------------------------- -// returns is result struct and error. If error is not nil, return it +// NOTE: assume returns is result struct and error. If error is not nil, return it func unreflectResult(returns []reflect.Value) (interface{}, error) { errV := returns[1] if errV.Interface() != nil { return nil, fmt.Errorf("%v", errV.Interface()) } - return returns[0].Interface(), nil + rv := returns[0] + // the result is a registered interface, + // we need a pointer to it so we can marshal with type byte + rvp := reflect.New(rv.Type()) + rvp.Elem().Set(rv) + return rvp.Interface(), nil } // writes a list of available rpc endpoints as an html page diff --git a/server/http_server.go b/server/http_server.go index 37b01ceee..1271d073b 100644 --- a/server/http_server.go +++ b/server/http_server.go @@ -3,6 +3,7 @@ package rpcserver import ( "bufio" + "encoding/json" "fmt" "net" "net/http" @@ -12,7 +13,7 @@ import ( "github.com/tendermint/go-alert" . "github.com/tendermint/go-common" . "github.com/tendermint/go-rpc/types" - "github.com/tendermint/go-wire" + //"github.com/tendermint/go-wire" ) func StartHTTPServer(listenAddr string, handler http.Handler) (net.Listener, error) { @@ -32,7 +33,11 @@ func StartHTTPServer(listenAddr string, handler http.Handler) (net.Listener, err } func WriteRPCResponseHTTP(w http.ResponseWriter, res RPCResponse) { - jsonBytes := wire.JSONBytesPretty(res) + // jsonBytes := wire.JSONBytesPretty(res) + jsonBytes, err := json.Marshal(res) + if err != nil { + panic(err) + } w.Header().Set("Content-Type", "application/json") w.WriteHeader(200) w.Write(jsonBytes) diff --git a/types/types.go b/types/types.go index 4905d000b..f9d1961c1 100644 --- a/types/types.go +++ b/types/types.go @@ -1,7 +1,10 @@ package rpctypes import ( + "encoding/json" + "github.com/tendermint/go-events" + "github.com/tendermint/go-wire" ) type RPCRequest struct { @@ -39,17 +42,18 @@ type Result interface { //---------------------------------------- type RPCResponse struct { - JSONRPC string `json:"jsonrpc"` - ID string `json:"id"` - Result Result `json:"result"` - Error string `json:"error"` + JSONRPC string `json:"jsonrpc"` + ID string `json:"id"` + Result *json.RawMessage `json:"result"` + Error string `json:"error"` } -func NewRPCResponse(id string, res Result, err string) RPCResponse { +func NewRPCResponse(id string, res interface{}, err string) RPCResponse { + raw := json.RawMessage(wire.JSONBytes(res)) return RPCResponse{ JSONRPC: "2.0", ID: id, - Result: res, + Result: &raw, Error: err, } } From 91c734d02edf03b689f84c22bc8e7530b8abbede Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Wed, 13 Jan 2016 21:21:16 -0500 Subject: [PATCH 015/309] client: ResultsCh chan json.RawMessage, ErrorsCh --- client/ws_client.go | 21 +++++++++++++++------ 1 file changed, 15 insertions(+), 6 deletions(-) diff --git a/client/ws_client.go b/client/ws_client.go index e0dc349ce..a2506585b 100644 --- a/client/ws_client.go +++ b/client/ws_client.go @@ -2,6 +2,7 @@ package rpcclient import ( "encoding/json" + "fmt" "net/http" "time" @@ -12,6 +13,7 @@ import ( const ( wsResultsChannelCapacity = 10 + wsErrorsChannelCapacity = 1 wsWriteTimeoutSeconds = 10 ) @@ -19,7 +21,8 @@ type WSClient struct { QuitService Address string *websocket.Conn - ResultsCh chan rpctypes.Result // closes upon WSClient.Stop() + ResultsCh chan json.RawMessage // closes upon WSClient.Stop() + ErrorsCh chan error // closes upon WSClient.Stop() } // create a new connection @@ -27,7 +30,8 @@ func NewWSClient(addr string) *WSClient { wsClient := &WSClient{ Address: addr, Conn: nil, - ResultsCh: make(chan rpctypes.Result, wsResultsChannelCapacity), + ResultsCh: make(chan json.RawMessage, wsResultsChannelCapacity), + ErrorsCh: make(chan error, wsErrorsChannelCapacity), } wsClient.QuitService = *NewQuitService(log, "WSClient", wsClient) return wsClient @@ -67,7 +71,7 @@ func (wsc *WSClient) dial() error { func (wsc *WSClient) OnStop() { wsc.QuitService.OnStop() - // ResultsCh is closed in receiveEventsRoutine. + // ResultsCh/ErrorsCh is closed in receiveEventsRoutine. } func (wsc *WSClient) receiveEventsRoutine() { @@ -82,15 +86,20 @@ func (wsc *WSClient) receiveEventsRoutine() { err := json.Unmarshal(data, &response) if err != nil { log.Info("WSClient failed to parse message", "error", err, "data", string(data)) - wsc.Stop() - break + wsc.ErrorsCh <- err + continue } - wsc.ResultsCh <- response.Result + if response.Error != "" { + wsc.ErrorsCh <- fmt.Errorf(err.Error()) + continue + } + wsc.ResultsCh <- *response.Result } } // Cleanup close(wsc.ResultsCh) + close(wsc.ErrorsCh) } // subscribe to an event From 14735d5eb5401ac80b73a183d217d3638acf2d34 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Wed, 13 Jan 2016 22:16:56 -0500 Subject: [PATCH 016/309] RawMessage fix --- types/types.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/types/types.go b/types/types.go index f9d1961c1..a35e3dae8 100644 --- a/types/types.go +++ b/types/types.go @@ -49,11 +49,15 @@ type RPCResponse struct { } func NewRPCResponse(id string, res interface{}, err string) RPCResponse { - raw := json.RawMessage(wire.JSONBytes(res)) + var raw *json.RawMessage + if res != nil { + rawMsg := json.RawMessage(wire.JSONBytes(res)) + raw = &rawMsg + } return RPCResponse{ JSONRPC: "2.0", ID: id, - Result: &raw, + Result: raw, Error: err, } } From 0380e404bdbafe5a22951c58e806702db7d75254 Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Sun, 17 Jan 2016 21:30:06 -0800 Subject: [PATCH 017/309] Conform to go-wire version 0.6.0 --- connection.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/connection.go b/connection.go index 9fae4e510..f57f29db4 100644 --- a/connection.go +++ b/connection.go @@ -623,7 +623,7 @@ func (ch *Channel) writeMsgPacketTo(w io.Writer) (n int, err error) { func (ch *Channel) recvMsgPacket(packet msgPacket) ([]byte, error) { // log.Debug("Read Msg Packet", "conn", ch.conn, "packet", packet) if ch.desc.RecvMessageCapacity < len(ch.recving)+len(packet.Bytes) { - return nil, wire.ErrBinaryReadSizeOverflow + return nil, wire.ErrBinaryReadOverflow } ch.recving = append(ch.recving, packet.Bytes...) if packet.EOF == byte(0x01) { From 9bc75eaf24c4f77031c067f9e09258f74f744aa7 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Wed, 20 Jan 2016 11:29:09 -0500 Subject: [PATCH 018/309] move DialSeeds in from tendermint/tendermint/node --- switch.go | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/switch.go b/switch.go index d118d95e5..72a599ab3 100644 --- a/switch.go +++ b/switch.go @@ -3,6 +3,7 @@ package p2p import ( "errors" "fmt" + "math/rand" "net" "time" @@ -249,6 +250,32 @@ func (sw *Switch) startInitPeer(peer *Peer) { sw.addPeerToReactors(peer) // run AddPeer on each reactor } +// Dial a list of seeds in random order +// Spawns a go routine for each dial +func (sw *Switch) DialSeeds(seeds []string) { + // permute the list, dial them in random order. + perm := rand.Perm(len(seeds)) + for i := 0; i < len(perm); i++ { + go func(i int) { + time.Sleep(time.Duration(rand.Int63n(3000)) * time.Millisecond) + j := perm[i] + addr := NewNetAddressString(seeds[j]) + + sw.dialSeed(addr) + }(i) + } +} + +func (sw *Switch) dialSeed(addr *NetAddress) { + peer, err := sw.DialPeerWithAddress(addr) + if err != nil { + log.Error("Error dialing seed", "error", err) + return + } else { + log.Notice("Connected to seed", "peer", peer) + } +} + func (sw *Switch) DialPeerWithAddress(addr *NetAddress) (*Peer, error) { log.Info("Dialing address", "address", addr) sw.dialing.Set(addr.IP.String(), addr) From b9eec7e4380115aea4fd1c8962c4b399ac9afd4c Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Wed, 20 Jan 2016 11:36:31 -0500 Subject: [PATCH 019/309] version bump --- version.go | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/version.go b/version.go index 2982824dd..d0a0ee9cd 100644 --- a/version.go +++ b/version.go @@ -1,3 +1,7 @@ package rpc -const Version = "0.4.0" +const Maj = "0" +const Min = "5" // refactored out of tendermint/tendermint; RPCResponse.Result is RawJSON +const Fix = "0" + +const Version = Maj + "." + Min + "." + Fix From fbc5ac80524e467d542ea9b4a55034255ee0691a Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Thu, 21 Jan 2016 23:03:39 -0500 Subject: [PATCH 020/309] print method in client log --- client/http_client.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/client/http_client.go b/client/http_client.go index f614a776e..6bb746d2e 100644 --- a/client/http_client.go +++ b/client/http_client.go @@ -53,7 +53,7 @@ func CallHTTP_JSONRPC(remote string, method string, params []interface{}, result } requestBytes := wire.JSONBytes(request) requestBuf := bytes.NewBuffer(requestBytes) - log.Info(Fmt("RPC request to %v: %v", remote, string(requestBytes))) + log.Info(Fmt("RPC request to %v (%v): %v", remote, method, string(requestBytes))) httpResponse, err := http.Post(remote, "text/json", requestBuf) if err != nil { return nil, err @@ -72,7 +72,7 @@ func CallHTTP_URI(remote string, method string, params map[string]interface{}, r if err != nil { return nil, err } - log.Info(Fmt("URI request to %v: %v", remote, values)) + log.Info(Fmt("URI request to %v (%v): %v", remote, method, values)) resp, err := http.PostForm(remote+method, values) if err != nil { return nil, err From 45f57198cc54e5db21f66dc30726d0ef8fab1311 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Wed, 3 Feb 2016 02:01:28 -0500 Subject: [PATCH 021/309] client: wsc.String() --- client/ws_client.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/client/ws_client.go b/client/ws_client.go index a2506585b..f7a23fca8 100644 --- a/client/ws_client.go +++ b/client/ws_client.go @@ -37,6 +37,10 @@ func NewWSClient(addr string) *WSClient { return wsClient } +func (wsc *WSClient) String() string { + return wsc.Address +} + func (wsc *WSClient) OnStart() error { wsc.QuitService.OnStart() err := wsc.dial() From 8b7969d6eade8d2ed358f97dc940574b2cd6c2b9 Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Mon, 8 Feb 2016 00:57:37 -0800 Subject: [PATCH 022/309] Add comments about goroutine-safety --- server/handlers.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/server/handlers.go b/server/handlers.go index a463b21e1..b150c6076 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -347,6 +347,7 @@ func (wsc *wsConnection) GetEventSwitch() *events.EventSwitch { // Implements WSRPCConnection // Blocking write to writeChan until service stops. +// Goroutine-safe func (wsc *wsConnection) WriteRPCResponse(resp RPCResponse) { select { case <-wsc.Quit: @@ -357,6 +358,7 @@ func (wsc *wsConnection) WriteRPCResponse(resp RPCResponse) { // Implements WSRPCConnection // Nonblocking write. +// Goroutine-safe func (wsc *wsConnection) TryWriteRPCResponse(resp RPCResponse) bool { select { case <-wsc.Quit: From 1370f89864b10518e9753078dc2d7f769685e9a0 Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Mon, 8 Feb 2016 02:20:34 -0800 Subject: [PATCH 023/309] Fix bug in receiveEventsRoutine error handling --- client/ws_client.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/ws_client.go b/client/ws_client.go index f7a23fca8..4c994bfcc 100644 --- a/client/ws_client.go +++ b/client/ws_client.go @@ -94,7 +94,7 @@ func (wsc *WSClient) receiveEventsRoutine() { continue } if response.Error != "" { - wsc.ErrorsCh <- fmt.Errorf(err.Error()) + wsc.ErrorsCh <- fmt.Errorf(response.Error) continue } wsc.ResultsCh <- *response.Result From 6607232a5daf1b474c4578836750e71943793c48 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Thu, 18 Feb 2016 21:07:49 +0000 Subject: [PATCH 024/309] add support for unix sockets --- client/http_client.go | 89 +++++++++++++++++++++++---------- rpc_test.go | 114 ++++++++++++++++++++++++++++++++++++++++++ server/http_server.go | 9 ++-- types/types.go | 14 ++++++ 4 files changed, 197 insertions(+), 29 deletions(-) create mode 100644 rpc_test.go diff --git a/client/http_client.go b/client/http_client.go index 6bb746d2e..100507196 100644 --- a/client/http_client.go +++ b/client/http_client.go @@ -5,45 +5,63 @@ import ( "encoding/json" "errors" "io/ioutil" + "net" "net/http" "net/url" - "strings" . "github.com/tendermint/go-common" "github.com/tendermint/go-rpc/types" "github.com/tendermint/go-wire" ) +// Set the net.Dial manually so we can do http over tcp or unix. +// Get/Post require a dummyDomain but it's over written by the Transport +var dummyDomain = "http://dummyDomain/" + +func unixDial(remote string) func(string, string) (net.Conn, error) { + return func(proto, addr string) (conn net.Conn, err error) { + return net.Dial("unix", remote) + } +} + +func tcpDial(remote string) func(string, string) (net.Conn, error) { + return func(proto, addr string) (conn net.Conn, err error) { + return net.Dial("tcp", remote) + } +} + +func socketTransport(remote string) *http.Transport { + if rpctypes.SocketType(remote) == "unix" { + return &http.Transport{ + Dial: unixDial(remote), + } + } else { + return &http.Transport{ + Dial: tcpDial(remote), + } + } +} + +//------------------------------------------------------------------------------------ + // JSON rpc takes params as a slice type ClientJSONRPC struct { remote string + client *http.Client } func NewClientJSONRPC(remote string) *ClientJSONRPC { - return &ClientJSONRPC{remote} + return &ClientJSONRPC{ + remote: remote, + client: &http.Client{Transport: socketTransport(remote)}, + } } func (c *ClientJSONRPC) Call(method string, params []interface{}, result interface{}) (interface{}, error) { - return CallHTTP_JSONRPC(c.remote, method, params, result) + return c.call(method, params, result) } -// URI takes params as a map -type ClientURI struct { - remote string -} - -func NewClientURI(remote string) *ClientURI { - if !strings.HasSuffix(remote, "/") { - remote = remote + "/" - } - return &ClientURI{remote} -} - -func (c *ClientURI) Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) { - return CallHTTP_URI(c.remote, method, params, result) -} - -func CallHTTP_JSONRPC(remote string, method string, params []interface{}, result interface{}) (interface{}, error) { +func (c *ClientJSONRPC) call(method string, params []interface{}, result interface{}) (interface{}, error) { // Make request and get responseBytes request := rpctypes.RPCRequest{ JSONRPC: "2.0", @@ -53,8 +71,8 @@ func CallHTTP_JSONRPC(remote string, method string, params []interface{}, result } requestBytes := wire.JSONBytes(request) requestBuf := bytes.NewBuffer(requestBytes) - log.Info(Fmt("RPC request to %v (%v): %v", remote, method, string(requestBytes))) - httpResponse, err := http.Post(remote, "text/json", requestBuf) + log.Info(Fmt("RPC request to %v (%v): %v", c.remote, method, string(requestBytes))) + httpResponse, err := c.client.Post(dummyDomain, "text/json", requestBuf) if err != nil { return nil, err } @@ -63,17 +81,36 @@ func CallHTTP_JSONRPC(remote string, method string, params []interface{}, result if err != nil { return nil, err } - log.Info(Fmt("RPC response: %v", string(responseBytes))) + // log.Info(Fmt("RPC response: %v", string(responseBytes))) return unmarshalResponseBytes(responseBytes, result) } -func CallHTTP_URI(remote string, method string, params map[string]interface{}, result interface{}) (interface{}, error) { +//------------------------------------------------------------- + +// URI takes params as a map +type ClientURI struct { + remote string + client *http.Client +} + +func NewClientURI(remote string) *ClientURI { + return &ClientURI{ + remote: remote, + client: &http.Client{Transport: socketTransport(remote)}, + } +} + +func (c *ClientURI) Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) { + return c.call(method, params, result) +} + +func (c *ClientURI) call(method string, params map[string]interface{}, result interface{}) (interface{}, error) { values, err := argsToURLValues(params) if err != nil { return nil, err } - log.Info(Fmt("URI request to %v (%v): %v", remote, method, values)) - resp, err := http.PostForm(remote+method, values) + log.Info(Fmt("URI request to %v (%v): %v", c.remote, method, values)) + resp, err := c.client.PostForm(dummyDomain+method, values) if err != nil { return nil, err } diff --git a/rpc_test.go b/rpc_test.go new file mode 100644 index 000000000..f81bf1a16 --- /dev/null +++ b/rpc_test.go @@ -0,0 +1,114 @@ +package rpc + +import ( + "net/http" + "testing" + "time" + + "github.com/tendermint/go-rpc/client" + "github.com/tendermint/go-rpc/server" + "github.com/tendermint/go-wire" +) + +// Client and Server should work over tcp or unix sockets +var ( + tcpAddr = "0.0.0.0:46657" + unixAddr = "/tmp/go-rpc.sock" // NOTE: must remove file for test to run again +) + +// Define a type for results and register concrete versions +type Result interface{} + +type ResultStatus struct { + Value string +} + +var _ = wire.RegisterInterface( + struct{ Result }{}, + wire.ConcreteType{&ResultStatus{}, 0x1}, +) + +// Define some routes +var Routes = map[string]*rpcserver.RPCFunc{ + "status": rpcserver.NewRPCFunc(StatusResult, "arg"), +} + +// an rpc function +func StatusResult(v string) (Result, error) { + return &ResultStatus{v}, nil +} + +// launch unix and tcp servers +func init() { + mux := http.NewServeMux() + rpcserver.RegisterRPCFuncs(mux, Routes) + go func() { + _, err := rpcserver.StartHTTPServer(tcpAddr, mux) + if err != nil { + panic(err) + } + }() + + mux = http.NewServeMux() + rpcserver.RegisterRPCFuncs(mux, Routes) + go func() { + _, err := rpcserver.StartHTTPServer(unixAddr, mux) + if err != nil { + panic(err) + } + }() + + // wait for servers to start + time.Sleep(time.Second * 2) + +} + +func testURI(t *testing.T, cl *rpcclient.ClientURI) { + val := "acbd" + params := map[string]interface{}{ + "arg": val, + } + var result Result + _, err := cl.Call("status", params, &result) + if err != nil { + t.Fatal(err) + } + got := result.(*ResultStatus).Value + if got != val { + t.Fatalf("Got: %v .... Expected: %v \n", got, val) + } +} + +func testJSONRPC(t *testing.T, cl *rpcclient.ClientJSONRPC) { + val := "acbd" + params := []interface{}{val} + var result Result + _, err := cl.Call("status", params, &result) + if err != nil { + t.Fatal(err) + } + got := result.(*ResultStatus).Value + if got != val { + t.Fatalf("Got: %v .... Expected: %v \n", got, val) + } +} + +func TestURI_TCP(t *testing.T) { + cl := rpcclient.NewClientURI(tcpAddr) + testURI(t, cl) +} + +func TestURI_UNIX(t *testing.T) { + cl := rpcclient.NewClientURI(unixAddr) + testURI(t, cl) +} + +func TestJSONRPC_TCP(t *testing.T) { + cl := rpcclient.NewClientJSONRPC(tcpAddr) + testJSONRPC(t, cl) +} + +func TestJSONRPC_UNIX(t *testing.T) { + cl := rpcclient.NewClientJSONRPC(unixAddr) + testJSONRPC(t, cl) +} diff --git a/server/http_server.go b/server/http_server.go index 1271d073b..beec9bcc2 100644 --- a/server/http_server.go +++ b/server/http_server.go @@ -17,11 +17,14 @@ import ( ) func StartHTTPServer(listenAddr string, handler http.Handler) (net.Listener, error) { - log.Notice(Fmt("Starting RPC HTTP server on %v", listenAddr)) - listener, err := net.Listen("tcp", listenAddr) + // listenAddr is `IP:PORT` or /path/to/socket + socketType := SocketType(listenAddr) + log.Notice(Fmt("Starting RPC HTTP server on %s socket %v", socketType, listenAddr)) + listener, err := net.Listen(socketType, listenAddr) if err != nil { - return nil, fmt.Errorf("Failed to listen to %v", listenAddr) + return nil, fmt.Errorf("Failed to listen to %v: %v", listenAddr, err) } + go func() { res := http.Serve( listener, diff --git a/types/types.go b/types/types.go index a35e3dae8..d7461f4e1 100644 --- a/types/types.go +++ b/types/types.go @@ -2,6 +2,7 @@ package rpctypes import ( "encoding/json" + "strings" "github.com/tendermint/go-events" "github.com/tendermint/go-wire" @@ -77,3 +78,16 @@ type WSRPCContext struct { Request RPCRequest WSRPCConnection } + +//---------------------------------------- +// sockets +// +// Determine if its a unix or tcp socket. +// If tcp, must specify the port; `0.0.0.0` will return incorrectly as "unix" since there's no port +func SocketType(listenAddr string) string { + socketType := "unix" + if len(strings.Split(listenAddr, ":")) == 2 { + socketType = "tcp" + } + return socketType +} From 74130008f7d44bdf1294b833a94d5ca9bda20cd6 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 19 Feb 2016 00:20:20 +0000 Subject: [PATCH 025/309] deduplicate dialFunc --- client/http_client.go | 15 +++++---------- 1 file changed, 5 insertions(+), 10 deletions(-) diff --git a/client/http_client.go b/client/http_client.go index 100507196..d49001ed0 100644 --- a/client/http_client.go +++ b/client/http_client.go @@ -18,26 +18,21 @@ import ( // Get/Post require a dummyDomain but it's over written by the Transport var dummyDomain = "http://dummyDomain/" -func unixDial(remote string) func(string, string) (net.Conn, error) { +func dialFunc(sockType, remote string) func(string, string) (net.Conn, error) { return func(proto, addr string) (conn net.Conn, err error) { - return net.Dial("unix", remote) - } -} - -func tcpDial(remote string) func(string, string) (net.Conn, error) { - return func(proto, addr string) (conn net.Conn, err error) { - return net.Dial("tcp", remote) + return net.Dial(sockType, remote) } } +// remote is IP:PORT or /path/to/socket func socketTransport(remote string) *http.Transport { if rpctypes.SocketType(remote) == "unix" { return &http.Transport{ - Dial: unixDial(remote), + Dial: dialFunc("unix", remote), } } else { return &http.Transport{ - Dial: tcpDial(remote), + Dial: dialFunc("tcp", remote), } } } From 1410693eae5400a50efbbac3f23b9e3e94b7d6c8 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 19 Feb 2016 02:05:24 +0000 Subject: [PATCH 026/309] support unix domain websockets --- client/http_client.go | 18 +++++---------- client/ws_client.go | 16 ++++++++----- rpc_test.go | 52 +++++++++++++++++++++++++++++++++++++++++++ types/types.go | 2 +- 4 files changed, 70 insertions(+), 18 deletions(-) diff --git a/client/http_client.go b/client/http_client.go index d49001ed0..e9e18bfa8 100644 --- a/client/http_client.go +++ b/client/http_client.go @@ -16,24 +16,18 @@ import ( // Set the net.Dial manually so we can do http over tcp or unix. // Get/Post require a dummyDomain but it's over written by the Transport -var dummyDomain = "http://dummyDomain/" +var dummyDomain = "http://dummyDomain" -func dialFunc(sockType, remote string) func(string, string) (net.Conn, error) { +func dialer(remote string) func(string, string) (net.Conn, error) { return func(proto, addr string) (conn net.Conn, err error) { - return net.Dial(sockType, remote) + return net.Dial(rpctypes.SocketType(remote), remote) } } // remote is IP:PORT or /path/to/socket func socketTransport(remote string) *http.Transport { - if rpctypes.SocketType(remote) == "unix" { - return &http.Transport{ - Dial: dialFunc("unix", remote), - } - } else { - return &http.Transport{ - Dial: dialFunc("tcp", remote), - } + return &http.Transport{ + Dial: dialer(remote), } } @@ -105,7 +99,7 @@ func (c *ClientURI) call(method string, params map[string]interface{}, result in return nil, err } log.Info(Fmt("URI request to %v (%v): %v", c.remote, method, values)) - resp, err := c.client.PostForm(dummyDomain+method, values) + resp, err := c.client.PostForm(dummyDomain+"/"+method, values) if err != nil { return nil, err } diff --git a/client/ws_client.go b/client/ws_client.go index 4c994bfcc..a8b8ce80c 100644 --- a/client/ws_client.go +++ b/client/ws_client.go @@ -19,16 +19,18 @@ const ( type WSClient struct { QuitService - Address string + Address string // IP:PORT or /path/to/socket + Endpoint string // /websocket/url/endpoint *websocket.Conn ResultsCh chan json.RawMessage // closes upon WSClient.Stop() ErrorsCh chan error // closes upon WSClient.Stop() } // create a new connection -func NewWSClient(addr string) *WSClient { +func NewWSClient(addr, endpoint string) *WSClient { wsClient := &WSClient{ Address: addr, + Endpoint: endpoint, Conn: nil, ResultsCh: make(chan json.RawMessage, wsResultsChannelCapacity), ErrorsCh: make(chan error, wsErrorsChannelCapacity), @@ -38,7 +40,7 @@ func NewWSClient(addr string) *WSClient { } func (wsc *WSClient) String() string { - return wsc.Address + return wsc.Address + ", " + wsc.Endpoint } func (wsc *WSClient) OnStart() error { @@ -52,10 +54,14 @@ func (wsc *WSClient) OnStart() error { } func (wsc *WSClient) dial() error { + // Dial - dialer := websocket.DefaultDialer + dialer := &websocket.Dialer{ + NetDial: dialer(wsc.Address), + Proxy: http.ProxyFromEnvironment, + } rHeader := http.Header{} - con, _, err := dialer.Dial(wsc.Address, rHeader) + con, _, err := dialer.Dial("ws://"+dummyDomain+wsc.Endpoint, rHeader) if err != nil { return err } diff --git a/rpc_test.go b/rpc_test.go index f81bf1a16..f23f6cdfb 100644 --- a/rpc_test.go +++ b/rpc_test.go @@ -7,6 +7,7 @@ import ( "github.com/tendermint/go-rpc/client" "github.com/tendermint/go-rpc/server" + "github.com/tendermint/go-rpc/types" "github.com/tendermint/go-wire" ) @@ -14,6 +15,8 @@ import ( var ( tcpAddr = "0.0.0.0:46657" unixAddr = "/tmp/go-rpc.sock" // NOTE: must remove file for test to run again + + websocketEndpoint = "/websocket/endpoint" ) // Define a type for results and register concrete versions @@ -42,6 +45,8 @@ func StatusResult(v string) (Result, error) { func init() { mux := http.NewServeMux() rpcserver.RegisterRPCFuncs(mux, Routes) + wm := rpcserver.NewWebsocketManager(Routes, nil) + mux.HandleFunc(websocketEndpoint, wm.WebsocketHandler) go func() { _, err := rpcserver.StartHTTPServer(tcpAddr, mux) if err != nil { @@ -51,6 +56,8 @@ func init() { mux = http.NewServeMux() rpcserver.RegisterRPCFuncs(mux, Routes) + wm = rpcserver.NewWebsocketManager(Routes, nil) + mux.HandleFunc(websocketEndpoint, wm.WebsocketHandler) go func() { _, err := rpcserver.StartHTTPServer(unixAddr, mux) if err != nil { @@ -93,6 +100,33 @@ func testJSONRPC(t *testing.T, cl *rpcclient.ClientJSONRPC) { } } +func testWS(t *testing.T, cl *rpcclient.WSClient) { + val := "acbd" + params := []interface{}{val} + err := cl.WriteJSON(rpctypes.RPCRequest{ + JSONRPC: "2.0", + ID: "", + Method: "status", + Params: params, + }) + if err != nil { + t.Fatal(err) + } + + msg := <-cl.ResultsCh + result := new(Result) + wire.ReadJSONPtr(result, msg, &err) + if err != nil { + t.Fatal(err) + } + got := (*result).(*ResultStatus).Value + if got != val { + t.Fatalf("Got: %v .... Expected: %v \n", got, val) + } +} + +//------------- + func TestURI_TCP(t *testing.T) { cl := rpcclient.NewClientURI(tcpAddr) testURI(t, cl) @@ -112,3 +146,21 @@ func TestJSONRPC_UNIX(t *testing.T) { cl := rpcclient.NewClientJSONRPC(unixAddr) testJSONRPC(t, cl) } + +func TestWS_TCP(t *testing.T) { + cl := rpcclient.NewWSClient(tcpAddr, websocketEndpoint) + _, err := cl.Start() + if err != nil { + t.Fatal(err) + } + testWS(t, cl) +} + +func TestWS_UNIX(t *testing.T) { + cl := rpcclient.NewWSClient(unixAddr, websocketEndpoint) + _, err := cl.Start() + if err != nil { + t.Fatal(err) + } + testWS(t, cl) +} diff --git a/types/types.go b/types/types.go index d7461f4e1..5d79c4a66 100644 --- a/types/types.go +++ b/types/types.go @@ -86,7 +86,7 @@ type WSRPCContext struct { // If tcp, must specify the port; `0.0.0.0` will return incorrectly as "unix" since there's no port func SocketType(listenAddr string) string { socketType := "unix" - if len(strings.Split(listenAddr, ":")) == 2 { + if len(strings.Split(listenAddr, ":")) >= 2 { socketType = "tcp" } return socketType From 7f6aad20fbad6ef1a132d5a8bebd18f3521fff1a Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Fri, 4 Mar 2016 22:04:05 -0800 Subject: [PATCH 027/309] Add note on nondeterminism of Broadcast --- switch.go | 1 + 1 file changed, 1 insertion(+) diff --git a/switch.go b/switch.go index 72a599ab3..518c6dfa2 100644 --- a/switch.go +++ b/switch.go @@ -301,6 +301,7 @@ func (sw *Switch) IsDialing(addr *NetAddress) bool { // Broadcast runs a go routine for each attempted send, which will block // trying to send for defaultSendTimeoutSeconds. Returns a channel // which receives success values for each attempted send (false if times out) +// NOTE: Broadcast uses goroutines, so order of broadcast may not be preserved. func (sw *Switch) Broadcast(chID byte, msg interface{}) chan bool { successChan := make(chan bool, len(sw.peers.List())) log.Info("Broadcast", "channel", chID, "msg", msg) From f28f791fff661e83530a47bef2e18f7f4ee2abef Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Wed, 2 Mar 2016 22:32:39 +0000 Subject: [PATCH 028/309] make some params configurable --- config.go | 40 ++++++++++++++++++++++++++++++++++++++++ connection.go | 32 ++++++++++++++++++++------------ switch.go | 16 +++++++++------- version.go | 2 +- 4 files changed, 70 insertions(+), 20 deletions(-) create mode 100644 config.go diff --git a/config.go b/config.go new file mode 100644 index 000000000..c5ab0e27b --- /dev/null +++ b/config.go @@ -0,0 +1,40 @@ +package p2p + +import ( + cfg "github.com/tendermint/go-config" +) + +// XXX: go-p2p requires ApplyConfig be called +var config cfg.Config = nil + +func init() { + initConfigureable(dialTimeoutKey, 3) + initConfigureable(handshakeTimeoutKey, 20) + initConfigureable(maxNumPeersKey, 50) + + initConfigureable(sendRateKey, 512000) // 500KB/s + initConfigureable(recvRateKey, 512000) // 500KB/s + + initConfigureable(maxPayloadSizeKey, 1024) + + cfg.OnConfig(func(newConfig cfg.Config) { + config = newConfig + + // fill in any config values that might be missing + for key, value := range defaultConfigValues { + if !config.IsSet(key) { + config.Set(key, value) + } + } + }) + c := cfg.NewMapConfig(nil) + c.Set("log_level", "debug") + cfg.ApplyConfig(c) +} + +// default config map +var defaultConfigValues = make(map[string]int) + +func initConfigureable(key string, value int) { + defaultConfigValues[key] = value +} diff --git a/connection.go b/connection.go index f57f29db4..923a63283 100644 --- a/connection.go +++ b/connection.go @@ -22,8 +22,6 @@ const ( idleTimeoutMinutes = 5 updateStatsSeconds = 2 pingTimeoutSeconds = 40 - defaultSendRate = 512000 // 500KB/s - defaultRecvRate = 512000 // 500KB/s flushThrottleMS = 100 defaultSendQueueCapacity = 1 defaultRecvBufferCapacity = 4096 @@ -31,6 +29,13 @@ const ( defaultSendTimeoutSeconds = 10 ) +// config keys +const ( + sendRateKey = "p2p_send_rate" + recvRateKey = "p2p_recv_rate" + maxPayloadSizeKey = "p2p_max_msg_packet_payload_size" +) + type receiveCbFunc func(chID byte, msgBytes []byte) type errorCbFunc func(interface{}) @@ -94,8 +99,8 @@ func NewMConnection(conn net.Conn, chDescs []*ChannelDescriptor, onReceive recei bufWriter: bufio.NewWriterSize(conn, minWriteBufferSize), sendMonitor: flow.New(0, 0), recvMonitor: flow.New(0, 0), - sendRate: defaultSendRate, - recvRate: defaultRecvRate, + sendRate: int64(config.GetInt(sendRateKey)), + recvRate: int64(config.GetInt(recvRateKey)), send: make(chan struct{}, 1), pong: make(chan struct{}), onReceive: onReceive, @@ -314,7 +319,7 @@ func (c *MConnection) sendSomeMsgPackets() bool { // Block until .sendMonitor says we can write. // Once we're ready we send more than we asked for, // but amortized it should even out. - c.sendMonitor.Limit(maxMsgPacketTotalSize, atomic.LoadInt64(&c.sendRate), true) + c.sendMonitor.Limit(maxMsgPacketTotalSize(), atomic.LoadInt64(&c.sendRate), true) // Now send some msgPackets. for i := 0; i < numBatchMsgPackets; i++ { @@ -372,7 +377,7 @@ func (c *MConnection) recvRoutine() { FOR_LOOP: for { // Block until .recvMonitor says we can read. - c.recvMonitor.Limit(maxMsgPacketTotalSize, atomic.LoadInt64(&c.recvRate), true) + c.recvMonitor.Limit(maxMsgPacketTotalSize(), atomic.LoadInt64(&c.recvRate), true) /* // Peek into bufReader for debugging @@ -413,7 +418,7 @@ FOR_LOOP: log.Info("Receive Pong") case packetTypeMsg: pkt, n, err := msgPacket{}, int(0), error(nil) - wire.ReadBinaryPtr(&pkt, c.bufReader, maxMsgPacketTotalSize, &n, &err) + wire.ReadBinaryPtr(&pkt, c.bufReader, maxMsgPacketTotalSize(), &n, &err) c.recvMonitor.Update(int(n)) if err != nil { if c.IsRunning() { @@ -593,14 +598,15 @@ func (ch *Channel) isSendPending() bool { func (ch *Channel) nextMsgPacket() msgPacket { packet := msgPacket{} packet.ChannelID = byte(ch.id) - packet.Bytes = ch.sending[:MinInt(maxMsgPacketPayloadSize, len(ch.sending))] - if len(ch.sending) <= maxMsgPacketPayloadSize { + maxPayloadSize := config.GetInt(maxPayloadSizeKey) + packet.Bytes = ch.sending[:MinInt(maxPayloadSize, len(ch.sending))] + if len(ch.sending) <= maxPayloadSize { packet.EOF = byte(0x01) ch.sending = nil atomic.AddInt32(&ch.sendQueueSize, -1) // decrement sendQueueSize } else { packet.EOF = byte(0x00) - ch.sending = ch.sending[MinInt(maxMsgPacketPayloadSize, len(ch.sending)):] + ch.sending = ch.sending[MinInt(maxPayloadSize, len(ch.sending)):] } return packet } @@ -644,10 +650,12 @@ func (ch *Channel) updateStats() { //----------------------------------------------------------------------------- +func maxMsgPacketTotalSize() int { + return config.GetInt(maxPayloadSizeKey) + maxMsgPacketOverheadSize +} + const ( - maxMsgPacketPayloadSize = 1024 maxMsgPacketOverheadSize = 10 // It's actually lower but good enough - maxMsgPacketTotalSize = maxMsgPacketPayloadSize + maxMsgPacketOverheadSize packetTypePing = byte(0x01) packetTypePong = byte(0x02) packetTypeMsg = byte(0x03) diff --git a/switch.go b/switch.go index 518c6dfa2..59ce3860e 100644 --- a/switch.go +++ b/switch.go @@ -70,10 +70,11 @@ var ( ErrSwitchMaxPeersPerIPRange = errors.New("IP range has too many peers") ) +// config keys const ( - peerDialTimeoutSeconds = 3 // TODO make this configurable - handshakeTimeoutSeconds = 20 // TODO make this configurable - maxNumPeers = 50 // TODO make this configurable + dialTimeoutKey = "p2p_dial_timeout_seconds" + handshakeTimeoutKey = "p2p_handshake_timeout_seconds" + maxNumPeersKey = "p2p_max_num_peers" ) func NewSwitch() *Switch { @@ -194,7 +195,7 @@ func (sw *Switch) OnStop() { // CONTRACT: Iff error is returned, peer is nil, and conn is immediately closed. func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool) (*Peer, error) { // Set deadline for handshake so we don't block forever on conn.ReadFull - conn.SetDeadline(time.Now().Add(handshakeTimeoutSeconds * time.Second)) + conn.SetDeadline(time.Now().Add(time.Duration(config.GetInt(handshakeTimeoutKey)) * time.Second)) // First, encrypt the connection. sconn, err := MakeSecretConnection(conn, sw.nodePrivKey) @@ -279,7 +280,7 @@ func (sw *Switch) dialSeed(addr *NetAddress) { func (sw *Switch) DialPeerWithAddress(addr *NetAddress) (*Peer, error) { log.Info("Dialing address", "address", addr) sw.dialing.Set(addr.IP.String(), addr) - conn, err := addr.DialTimeout(peerDialTimeoutSeconds * time.Second) + conn, err := addr.DialTimeout(time.Duration(config.GetInt(dialTimeoutKey)) * time.Second) sw.dialing.Delete(addr.IP.String()) if err != nil { log.Info("Failed dialing address", "address", addr, "error", err) @@ -370,8 +371,9 @@ func (sw *Switch) listenerRoutine(l Listener) { } // ignore connection if we already have enough - if maxNumPeers <= sw.peers.Size() { - log.Info("Ignoring inbound connection: already have enough peers", "address", inConn.RemoteAddr().String(), "numPeers", sw.peers.Size(), "max", maxNumPeers) + maxPeers := config.GetInt(maxNumPeersKey) + if maxPeers <= sw.peers.Size() { + log.Info("Ignoring inbound connection: already have enough peers", "address", inConn.RemoteAddr().String(), "numPeers", sw.peers.Size(), "max", maxPeers) continue } diff --git a/version.go b/version.go index 7e51463dc..335843c95 100644 --- a/version.go +++ b/version.go @@ -1,3 +1,3 @@ package p2p -const Version = "0.3.0" +const Version = "0.3.1" // configurable params From 1bc871162db7206c7ee0a775166dfe4c0705168b Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Sun, 6 Mar 2016 12:33:07 -0800 Subject: [PATCH 029/309] Conform to new go-config behavior; ApplyConfig not needed --- config.go | 14 +++----------- 1 file changed, 3 insertions(+), 11 deletions(-) diff --git a/config.go b/config.go index c5ab0e27b..2c8c1d242 100644 --- a/config.go +++ b/config.go @@ -4,17 +4,14 @@ import ( cfg "github.com/tendermint/go-config" ) -// XXX: go-p2p requires ApplyConfig be called var config cfg.Config = nil func init() { initConfigureable(dialTimeoutKey, 3) initConfigureable(handshakeTimeoutKey, 20) initConfigureable(maxNumPeersKey, 50) - initConfigureable(sendRateKey, 512000) // 500KB/s initConfigureable(recvRateKey, 512000) // 500KB/s - initConfigureable(maxPayloadSizeKey, 1024) cfg.OnConfig(func(newConfig cfg.Config) { @@ -22,19 +19,14 @@ func init() { // fill in any config values that might be missing for key, value := range defaultConfigValues { - if !config.IsSet(key) { - config.Set(key, value) - } + config.SetDefault(key, value) } }) - c := cfg.NewMapConfig(nil) - c.Set("log_level", "debug") - cfg.ApplyConfig(c) } // default config map -var defaultConfigValues = make(map[string]int) +var defaultConfigValues = make(map[string]interface{}) -func initConfigureable(key string, value int) { +func initConfigureable(key string, value interface{}) { defaultConfigValues[key] = value } From 389e4b8b6954cd550296e04c90f49dfbf8a06856 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Thu, 10 Mar 2016 19:07:01 -0500 Subject: [PATCH 030/309] config: toggle authenticated encryption --- config.go | 2 ++ switch.go | 25 ++++++++++++++++--------- 2 files changed, 18 insertions(+), 9 deletions(-) diff --git a/config.go b/config.go index 2c8c1d242..025b55323 100644 --- a/config.go +++ b/config.go @@ -14,6 +14,8 @@ func init() { initConfigureable(recvRateKey, 512000) // 500KB/s initConfigureable(maxPayloadSizeKey, 1024) + initConfigureable(authEncKey, true) + cfg.OnConfig(func(newConfig cfg.Config) { config = newConfig diff --git a/switch.go b/switch.go index 59ce3860e..fddb99e68 100644 --- a/switch.go +++ b/switch.go @@ -75,6 +75,7 @@ const ( dialTimeoutKey = "p2p_dial_timeout_seconds" handshakeTimeoutKey = "p2p_handshake_timeout_seconds" maxNumPeersKey = "p2p_max_num_peers" + authEncKey = "p2p_authenticated_encryption" ) func NewSwitch() *Switch { @@ -198,10 +199,14 @@ func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool) (*Peer, er conn.SetDeadline(time.Now().Add(time.Duration(config.GetInt(handshakeTimeoutKey)) * time.Second)) // First, encrypt the connection. - sconn, err := MakeSecretConnection(conn, sw.nodePrivKey) - if err != nil { - conn.Close() - return nil, err + var sconn net.Conn = conn + if config.GetBool(authEncKey) { + var err error + sconn, err = MakeSecretConnection(conn, sw.nodePrivKey) + if err != nil { + conn.Close() + return nil, err + } } // Then, perform node handshake peerNodeInfo, err := peerHandshake(sconn, sw.nodeInfo) @@ -209,11 +214,13 @@ func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool) (*Peer, er sconn.Close() return nil, err } - // Check that the professed PubKey matches the sconn's. - if !peerNodeInfo.PubKey.Equals(sconn.RemotePubKey()) { - sconn.Close() - return nil, fmt.Errorf("Ignoring connection with unmatching pubkey: %v vs %v", - peerNodeInfo.PubKey, sconn.RemotePubKey()) + if config.GetBool("p2p_authenticated_encryption") { + // Check that the professed PubKey matches the sconn's. + if !peerNodeInfo.PubKey.Equals(sconn.(*SecretConnection).RemotePubKey()) { + sconn.Close() + return nil, fmt.Errorf("Ignoring connection with unmatching pubkey: %v vs %v", + peerNodeInfo.PubKey, sconn.(*SecretConnection).RemotePubKey()) + } } // Avoid self if peerNodeInfo.PubKey.Equals(sw.nodeInfo.PubKey) { From 10619248c665dee6b8f81455f7f27ab93d5ec366 Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Sun, 13 Mar 2016 09:42:11 -0700 Subject: [PATCH 031/309] Use go-crypto CRand* --- addrbook.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/addrbook.go b/addrbook.go index 14b39b575..0b1525646 100644 --- a/addrbook.go +++ b/addrbook.go @@ -15,6 +15,7 @@ import ( "time" . "github.com/tendermint/go-common" + "github.com/tendermint/go-crypto" ) const ( @@ -109,7 +110,7 @@ func NewAddrBook(filePath string) *AddrBook { // When modifying this, don't forget to update loadFromFile() func (a *AddrBook) init() { - a.key = CRandHex(24) // 24/2 * 8 = 96 bits + a.key = crypto.CRandHex(24) // 24/2 * 8 = 96 bits // New addr buckets a.addrNew = make([]map[string]*knownAddress, newBucketCount) for i := range a.addrNew { From 114d90bec898c61d3c64eba6c55b85fdb046d276 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Sat, 12 Mar 2016 01:04:27 -0500 Subject: [PATCH 032/309] don't reallocate on recvMsgPacket --- connection.go | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/connection.go b/connection.go index 923a63283..5ef77f7d0 100644 --- a/connection.go +++ b/connection.go @@ -18,7 +18,7 @@ import ( const ( numBatchMsgPackets = 10 minReadBufferSize = 1024 - minWriteBufferSize = 1024 + minWriteBufferSize = 65536 idleTimeoutMinutes = 5 updateStatsSeconds = 2 pingTimeoutSeconds = 40 @@ -634,7 +634,11 @@ func (ch *Channel) recvMsgPacket(packet msgPacket) ([]byte, error) { ch.recving = append(ch.recving, packet.Bytes...) if packet.EOF == byte(0x01) { msgBytes := ch.recving - ch.recving = make([]byte, 0, defaultRecvBufferCapacity) + // clear the slice without re-allocating. + // http://stackoverflow.com/questions/16971741/how-do-you-clear-a-slice-in-go + // suggests this could be a memory leak, but we might as well keep the memory for the channel until it closes, + // at which point the recving slice stops being used and should be garbage collected + ch.recving = ch.recving[:0] // make([]byte, 0, ch.desc.RecvBufferCapacity) return msgBytes, nil } return nil, nil From 69c7ae5e3fd5fb9a3bf26d4b93f9ea8d6b921b44 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Sat, 12 Mar 2016 13:05:28 -0500 Subject: [PATCH 033/309] version bump --- version.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/version.go b/version.go index 335843c95..d4a712f0b 100644 --- a/version.go +++ b/version.go @@ -1,3 +1,3 @@ package p2p -const Version = "0.3.1" // configurable params +const Version = "0.3.2" // memory optimizations From 78c9d526c31d5ae06d5793b865d25a9407b635dc Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Tue, 29 Mar 2016 11:37:29 -0700 Subject: [PATCH 034/309] change some log.Info to log.Debug --- connection.go | 12 ++++++------ switch.go | 2 +- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/connection.go b/connection.go index 5ef77f7d0..7c77edf58 100644 --- a/connection.go +++ b/connection.go @@ -196,7 +196,7 @@ func (c *MConnection) Send(chID byte, msg interface{}) bool { return false } - log.Info("Send", "channel", chID, "conn", c, "msg", msg) //, "bytes", wire.BinaryBytes(msg)) + log.Debug("Send", "channel", chID, "conn", c, "msg", msg) //, "bytes", wire.BinaryBytes(msg)) // Send message to channel. channel, ok := c.channelsIdx[chID] @@ -225,7 +225,7 @@ func (c *MConnection) TrySend(chID byte, msg interface{}) bool { return false } - log.Info("TrySend", "channel", chID, "conn", c, "msg", msg) + log.Debug("TrySend", "channel", chID, "conn", c, "msg", msg) // Send message to channel. channel, ok := c.channelsIdx[chID] @@ -277,12 +277,12 @@ FOR_LOOP: channel.updateStats() } case <-c.pingTimer.Ch: - log.Info("Send Ping") + log.Debug("Send Ping") wire.WriteByte(packetTypePing, c.bufWriter, &n, &err) c.sendMonitor.Update(int(n)) c.flush() case <-c.pong: - log.Info("Send Pong") + log.Debug("Send Pong") wire.WriteByte(packetTypePong, c.bufWriter, &n, &err) c.sendMonitor.Update(int(n)) c.flush() @@ -411,11 +411,11 @@ FOR_LOOP: switch pktType { case packetTypePing: // TODO: prevent abuse, as they cause flush()'s. - log.Info("Receive Ping") + log.Debug("Receive Ping") c.pong <- struct{}{} case packetTypePong: // do nothing - log.Info("Receive Pong") + log.Debug("Receive Pong") case packetTypeMsg: pkt, n, err := msgPacket{}, int(0), error(nil) wire.ReadBinaryPtr(&pkt, c.bufReader, maxMsgPacketTotalSize(), &n, &err) diff --git a/switch.go b/switch.go index fddb99e68..b59c6b126 100644 --- a/switch.go +++ b/switch.go @@ -312,7 +312,7 @@ func (sw *Switch) IsDialing(addr *NetAddress) bool { // NOTE: Broadcast uses goroutines, so order of broadcast may not be preserved. func (sw *Switch) Broadcast(chID byte, msg interface{}) chan bool { successChan := make(chan bool, len(sw.peers.List())) - log.Info("Broadcast", "channel", chID, "msg", msg) + log.Debug("Broadcast", "channel", chID, "msg", msg) for _, peer := range sw.peers.List() { go func(peer *Peer) { success := peer.Send(chID, msg) From e8538d606aa9700da03f748f61d734e8cbc1438b Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Wed, 4 May 2016 10:39:43 -0400 Subject: [PATCH 035/309] add blank client interface --- client/http_client.go | 7 ++++++- server/handlers.go | 2 +- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/client/http_client.go b/client/http_client.go index e9e18bfa8..7c0480600 100644 --- a/client/http_client.go +++ b/client/http_client.go @@ -33,6 +33,11 @@ func socketTransport(remote string) *http.Transport { //------------------------------------------------------------------------------------ +type Client interface { +} + +//------------------------------------------------------------------------------------ + // JSON rpc takes params as a slice type ClientJSONRPC struct { remote string @@ -60,7 +65,7 @@ func (c *ClientJSONRPC) call(method string, params []interface{}, result interfa } requestBytes := wire.JSONBytes(request) requestBuf := bytes.NewBuffer(requestBytes) - log.Info(Fmt("RPC request to %v (%v): %v", c.remote, method, string(requestBytes))) + // log.Info(Fmt("RPC request to %v (%v): %v", c.remote, method, string(requestBytes))) httpResponse, err := c.client.Post(dummyDomain, "text/json", requestBuf) if err != nil { return nil, err diff --git a/server/handlers.go b/server/handlers.go index b150c6076..1c447c6c9 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -387,7 +387,7 @@ func (wsc *wsConnection) readRoutine() { // We use `readTimeout` to handle read timeouts. _, in, err := wsc.baseConn.ReadMessage() if err != nil { - log.Notice("Failed to read from connection", "remote", wsc.remoteAddr) + log.Notice("Failed to read from connection", "remote", wsc.remoteAddr, "err", err.Error()) // an error reading the connection, // kill the connection wsc.Stop() From 1d9e89812adc202811b7fb8e9e0837e73adadb43 Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Sun, 8 May 2016 14:58:15 -0700 Subject: [PATCH 036/309] Remove go-alert dependency --- server/http_server.go | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/server/http_server.go b/server/http_server.go index beec9bcc2..cc3da39be 100644 --- a/server/http_server.go +++ b/server/http_server.go @@ -10,7 +10,6 @@ import ( "runtime/debug" "time" - "github.com/tendermint/go-alert" . "github.com/tendermint/go-common" . "github.com/tendermint/go-rpc/types" //"github.com/tendermint/go-wire" @@ -112,12 +111,3 @@ func (w *ResponseWriterWrapper) WriteHeader(status int) { func (w *ResponseWriterWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) { return w.ResponseWriter.(http.Hijacker).Hijack() } - -// Stick it as a deferred statement in gouroutines to prevent the program from crashing. -func Recover(daemonName string) { - if e := recover(); e != nil { - stack := string(debug.Stack()) - errorString := fmt.Sprintf("[%s] %s\n%s", daemonName, e, stack) - alert.Alert(errorString) - } -} From 7d997ca8e658731a22de53f11efaedee0c764b8d Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Sun, 8 May 2016 14:59:27 -0700 Subject: [PATCH 037/309] No global config --- config.go | 43 +++++++++++++++++++------------------------ connection.go | 49 +++++++++++++++++++++---------------------------- peer.go | 5 +++-- switch.go | 27 +++++++++++++-------------- 4 files changed, 56 insertions(+), 68 deletions(-) diff --git a/config.go b/config.go index 025b55323..0779bb4c8 100644 --- a/config.go +++ b/config.go @@ -4,31 +4,26 @@ import ( cfg "github.com/tendermint/go-config" ) -var config cfg.Config = nil +const ( + // Switch config keys + configKeyDialTimeoutSeconds = "p2p_dial_timeout_seconds" + configKeyHandshakeTimeoutSeconds = "p2p_handshake_timeout_seconds" + configKeyMaxNumPeers = "p2p_max_num_peers" + configKeyAuthEnc = "p2p_authenticated_encryption" -func init() { - initConfigureable(dialTimeoutKey, 3) - initConfigureable(handshakeTimeoutKey, 20) - initConfigureable(maxNumPeersKey, 50) - initConfigureable(sendRateKey, 512000) // 500KB/s - initConfigureable(recvRateKey, 512000) // 500KB/s - initConfigureable(maxPayloadSizeKey, 1024) + // MConnection config keys + configKeySendRate = "p2p_send_rate" + configKeyRecvRate = "p2p_recv_rate" +) - initConfigureable(authEncKey, true) +func setConfigDefaults(config cfg.Config) { + // Switch default config + config.SetDefault(configKeyDialTimeoutSeconds, 3) + config.SetDefault(configKeyHandshakeTimeoutSeconds, 20) + config.SetDefault(configKeyMaxNumPeers, 50) + config.SetDefault(configKeyAuthEnc, true) - cfg.OnConfig(func(newConfig cfg.Config) { - config = newConfig - - // fill in any config values that might be missing - for key, value := range defaultConfigValues { - config.SetDefault(key, value) - } - }) -} - -// default config map -var defaultConfigValues = make(map[string]interface{}) - -func initConfigureable(key string, value interface{}) { - defaultConfigValues[key] = value + // MConnection default config + config.SetDefault(configKeySendRate, 512000) // 500KB/s + config.SetDefault(configKeyRecvRate, 512000) // 500KB/s } diff --git a/connection.go b/connection.go index 7c77edf58..aa707b97c 100644 --- a/connection.go +++ b/connection.go @@ -12,30 +12,25 @@ import ( flow "github.com/tendermint/flowcontrol" . "github.com/tendermint/go-common" + cfg "github.com/tendermint/go-config" "github.com/tendermint/go-wire" //"github.com/tendermint/log15" ) const ( - numBatchMsgPackets = 10 - minReadBufferSize = 1024 - minWriteBufferSize = 65536 - idleTimeoutMinutes = 5 - updateStatsSeconds = 2 - pingTimeoutSeconds = 40 - flushThrottleMS = 100 + numBatchMsgPackets = 10 + minReadBufferSize = 1024 + minWriteBufferSize = 65536 + idleTimeoutMinutes = 5 + updateStatsSeconds = 2 + pingTimeoutSeconds = 40 + flushThrottleMS = 100 + defaultSendQueueCapacity = 1 defaultRecvBufferCapacity = 4096 defaultRecvMessageCapacity = 22020096 // 21MB defaultSendTimeoutSeconds = 10 ) -// config keys -const ( - sendRateKey = "p2p_send_rate" - recvRateKey = "p2p_recv_rate" - maxPayloadSizeKey = "p2p_max_msg_packet_payload_size" -) - type receiveCbFunc func(chID byte, msgBytes []byte) type errorCbFunc func(interface{}) @@ -91,7 +86,8 @@ type MConnection struct { RemoteAddress *NetAddress } -func NewMConnection(conn net.Conn, chDescs []*ChannelDescriptor, onReceive receiveCbFunc, onError errorCbFunc) *MConnection { +func NewMConnection(config cfg.Config, conn net.Conn, chDescs []*ChannelDescriptor, onReceive receiveCbFunc, onError errorCbFunc) *MConnection { + setConfigDefaults(config) mconn := &MConnection{ conn: conn, @@ -99,8 +95,8 @@ func NewMConnection(conn net.Conn, chDescs []*ChannelDescriptor, onReceive recei bufWriter: bufio.NewWriterSize(conn, minWriteBufferSize), sendMonitor: flow.New(0, 0), recvMonitor: flow.New(0, 0), - sendRate: int64(config.GetInt(sendRateKey)), - recvRate: int64(config.GetInt(recvRateKey)), + sendRate: int64(config.GetInt(configKeySendRate)), + recvRate: int64(config.GetInt(configKeyRecvRate)), send: make(chan struct{}, 1), pong: make(chan struct{}), onReceive: onReceive, @@ -319,7 +315,7 @@ func (c *MConnection) sendSomeMsgPackets() bool { // Block until .sendMonitor says we can write. // Once we're ready we send more than we asked for, // but amortized it should even out. - c.sendMonitor.Limit(maxMsgPacketTotalSize(), atomic.LoadInt64(&c.sendRate), true) + c.sendMonitor.Limit(maxMsgPacketTotalSize, atomic.LoadInt64(&c.sendRate), true) // Now send some msgPackets. for i := 0; i < numBatchMsgPackets; i++ { @@ -377,7 +373,7 @@ func (c *MConnection) recvRoutine() { FOR_LOOP: for { // Block until .recvMonitor says we can read. - c.recvMonitor.Limit(maxMsgPacketTotalSize(), atomic.LoadInt64(&c.recvRate), true) + c.recvMonitor.Limit(maxMsgPacketTotalSize, atomic.LoadInt64(&c.recvRate), true) /* // Peek into bufReader for debugging @@ -418,7 +414,7 @@ FOR_LOOP: log.Debug("Receive Pong") case packetTypeMsg: pkt, n, err := msgPacket{}, int(0), error(nil) - wire.ReadBinaryPtr(&pkt, c.bufReader, maxMsgPacketTotalSize(), &n, &err) + wire.ReadBinaryPtr(&pkt, c.bufReader, maxMsgPacketTotalSize, &n, &err) c.recvMonitor.Update(int(n)) if err != nil { if c.IsRunning() { @@ -598,15 +594,14 @@ func (ch *Channel) isSendPending() bool { func (ch *Channel) nextMsgPacket() msgPacket { packet := msgPacket{} packet.ChannelID = byte(ch.id) - maxPayloadSize := config.GetInt(maxPayloadSizeKey) - packet.Bytes = ch.sending[:MinInt(maxPayloadSize, len(ch.sending))] - if len(ch.sending) <= maxPayloadSize { + packet.Bytes = ch.sending[:MinInt(maxMsgPacketPayloadSize, len(ch.sending))] + if len(ch.sending) <= maxMsgPacketPayloadSize { packet.EOF = byte(0x01) ch.sending = nil atomic.AddInt32(&ch.sendQueueSize, -1) // decrement sendQueueSize } else { packet.EOF = byte(0x00) - ch.sending = ch.sending[MinInt(maxPayloadSize, len(ch.sending)):] + ch.sending = ch.sending[MinInt(maxMsgPacketPayloadSize, len(ch.sending)):] } return packet } @@ -654,12 +649,10 @@ func (ch *Channel) updateStats() { //----------------------------------------------------------------------------- -func maxMsgPacketTotalSize() int { - return config.GetInt(maxPayloadSizeKey) + maxMsgPacketOverheadSize -} - const ( + maxMsgPacketPayloadSize = 1024 maxMsgPacketOverheadSize = 10 // It's actually lower but good enough + maxMsgPacketTotalSize = maxMsgPacketPayloadSize + maxMsgPacketOverheadSize packetTypePing = byte(0x01) packetTypePong = byte(0x02) packetTypeMsg = byte(0x03) diff --git a/peer.go b/peer.go index a0f153fe3..7a2d647f8 100644 --- a/peer.go +++ b/peer.go @@ -6,6 +6,7 @@ import ( "net" . "github.com/tendermint/go-common" + cfg "github.com/tendermint/go-config" "github.com/tendermint/go-wire" ) @@ -47,7 +48,7 @@ func peerHandshake(conn net.Conn, ourNodeInfo *NodeInfo) (*NodeInfo, error) { } // NOTE: call peerHandshake on conn before calling newPeer(). -func newPeer(conn net.Conn, peerNodeInfo *NodeInfo, outbound bool, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{})) *Peer { +func newPeer(config cfg.Config, conn net.Conn, peerNodeInfo *NodeInfo, outbound bool, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{})) *Peer { var p *Peer onReceive := func(chID byte, msgBytes []byte) { reactor := reactorsByCh[chID] @@ -60,7 +61,7 @@ func newPeer(conn net.Conn, peerNodeInfo *NodeInfo, outbound bool, reactorsByCh p.Stop() onPeerError(p, r) } - mconn := NewMConnection(conn, chDescs, onReceive, onError) + mconn := NewMConnection(config, conn, chDescs, onReceive, onError) p = &Peer{ outbound: outbound, mconn: mconn, diff --git a/switch.go b/switch.go index b59c6b126..5aa8b64ed 100644 --- a/switch.go +++ b/switch.go @@ -8,6 +8,7 @@ import ( "time" . "github.com/tendermint/go-common" + cfg "github.com/tendermint/go-config" "github.com/tendermint/go-crypto" "github.com/tendermint/log15" ) @@ -55,6 +56,7 @@ incoming messages are received on the reactor. type Switch struct { BaseService + config cfg.Config listeners []Listener reactors map[string]Reactor chDescs []*ChannelDescriptor @@ -70,16 +72,11 @@ var ( ErrSwitchMaxPeersPerIPRange = errors.New("IP range has too many peers") ) -// config keys -const ( - dialTimeoutKey = "p2p_dial_timeout_seconds" - handshakeTimeoutKey = "p2p_handshake_timeout_seconds" - maxNumPeersKey = "p2p_max_num_peers" - authEncKey = "p2p_authenticated_encryption" -) +func NewSwitch(config cfg.Config) *Switch { + setConfigDefaults(config) -func NewSwitch() *Switch { sw := &Switch{ + config: config, reactors: make(map[string]Reactor), chDescs: make([]*ChannelDescriptor, 0), reactorsByCh: make(map[byte]Reactor), @@ -196,11 +193,12 @@ func (sw *Switch) OnStop() { // CONTRACT: Iff error is returned, peer is nil, and conn is immediately closed. func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool) (*Peer, error) { // Set deadline for handshake so we don't block forever on conn.ReadFull - conn.SetDeadline(time.Now().Add(time.Duration(config.GetInt(handshakeTimeoutKey)) * time.Second)) + conn.SetDeadline(time.Now().Add( + time.Duration(sw.config.GetInt(configKeyHandshakeTimeoutSeconds)) * time.Second)) // First, encrypt the connection. var sconn net.Conn = conn - if config.GetBool(authEncKey) { + if sw.config.GetBool(configKeyAuthEnc) { var err error sconn, err = MakeSecretConnection(conn, sw.nodePrivKey) if err != nil { @@ -214,7 +212,7 @@ func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool) (*Peer, er sconn.Close() return nil, err } - if config.GetBool("p2p_authenticated_encryption") { + if sw.config.GetBool(configKeyAuthEnc) { // Check that the professed PubKey matches the sconn's. if !peerNodeInfo.PubKey.Equals(sconn.(*SecretConnection).RemotePubKey()) { sconn.Close() @@ -233,7 +231,7 @@ func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool) (*Peer, er return nil, err } - peer := newPeer(sconn, peerNodeInfo, outbound, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError) + peer := newPeer(sw.config, sconn, peerNodeInfo, outbound, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError) // Add the peer to .peers // ignore if duplicate or if we already have too many for that IP range @@ -287,7 +285,8 @@ func (sw *Switch) dialSeed(addr *NetAddress) { func (sw *Switch) DialPeerWithAddress(addr *NetAddress) (*Peer, error) { log.Info("Dialing address", "address", addr) sw.dialing.Set(addr.IP.String(), addr) - conn, err := addr.DialTimeout(time.Duration(config.GetInt(dialTimeoutKey)) * time.Second) + conn, err := addr.DialTimeout(time.Duration( + sw.config.GetInt(configKeyDialTimeoutSeconds)) * time.Second) sw.dialing.Delete(addr.IP.String()) if err != nil { log.Info("Failed dialing address", "address", addr, "error", err) @@ -378,7 +377,7 @@ func (sw *Switch) listenerRoutine(l Listener) { } // ignore connection if we already have enough - maxPeers := config.GetInt(maxNumPeersKey) + maxPeers := sw.config.GetInt(configKeyMaxNumPeers) if maxPeers <= sw.peers.Size() { log.Info("Ignoring inbound connection: already have enough peers", "address", inConn.RemoteAddr().String(), "numPeers", sw.peers.Size(), "max", maxPeers) continue From ffbd6d878212795d234ab31bcbb83f79f4acaf91 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Wed, 11 May 2016 23:47:51 -0400 Subject: [PATCH 038/309] drop the p2p_ --- config.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/config.go b/config.go index 0779bb4c8..474d8a8f1 100644 --- a/config.go +++ b/config.go @@ -6,14 +6,14 @@ import ( const ( // Switch config keys - configKeyDialTimeoutSeconds = "p2p_dial_timeout_seconds" - configKeyHandshakeTimeoutSeconds = "p2p_handshake_timeout_seconds" - configKeyMaxNumPeers = "p2p_max_num_peers" - configKeyAuthEnc = "p2p_authenticated_encryption" + configKeyDialTimeoutSeconds = "dial_timeout_seconds" + configKeyHandshakeTimeoutSeconds = "handshake_timeout_seconds" + configKeyMaxNumPeers = "max_num_peers" + configKeyAuthEnc = "authenticated_encryption" // MConnection config keys - configKeySendRate = "p2p_send_rate" - configKeyRecvRate = "p2p_recv_rate" + configKeySendRate = "send_rate" + configKeyRecvRate = "recv_rate" ) func setConfigDefaults(config cfg.Config) { From 0dc6ebc32541350bf35368d69e7e0566e58e716b Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Tue, 22 Dec 2015 21:58:11 -0500 Subject: [PATCH 039/309] configurable fuzz conn --- config.go | 18 +++++++ fuzz.go | 141 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ switch.go | 7 +++ 3 files changed, 166 insertions(+) create mode 100644 fuzz.go diff --git a/config.go b/config.go index 474d8a8f1..60b69e367 100644 --- a/config.go +++ b/config.go @@ -14,6 +14,15 @@ const ( // MConnection config keys configKeySendRate = "send_rate" configKeyRecvRate = "recv_rate" + + // Fuzz params + configFuzzEnable = "fuzz_enable" // use the fuzz wrapped conn + configFuzzActive = "fuzz_active" // toggle fuzzing + configFuzzMode = "fuzz_mode" // eg. drop, delay + configFuzzMaxDelayMilliseconds = "fuzz_max_delay_milliseconds" + configFuzzProbDropRW = "fuzz_prob_drop_rw" + configFuzzProbDropConn = "fuzz_prob_drop_conn" + configFuzzProbSleep = "fuzz_prob_sleep" ) func setConfigDefaults(config cfg.Config) { @@ -26,4 +35,13 @@ func setConfigDefaults(config cfg.Config) { // MConnection default config config.SetDefault(configKeySendRate, 512000) // 500KB/s config.SetDefault(configKeyRecvRate, 512000) // 500KB/s + + // Fuzz defaults + config.SetDefault(configFuzzEnable, false) + config.SetDefault(configFuzzActive, false) + config.SetDefault(configFuzzMode, FuzzModeDrop) + config.SetDefault(configFuzzMaxDelayMilliseconds, 3000) + config.SetDefault(configFuzzProbDropRW, 0.2) + config.SetDefault(configFuzzProbDropConn, 0.00) + config.SetDefault(configFuzzProbSleep, 0.00) } diff --git a/fuzz.go b/fuzz.go new file mode 100644 index 000000000..ee8f43ccf --- /dev/null +++ b/fuzz.go @@ -0,0 +1,141 @@ +package p2p + +import ( + "math/rand" + "net" + "sync" + "time" + + cfg "github.com/tendermint/go-config" +) + +//-------------------------------------------------------- +// delay reads/writes +// randomly drop reads/writes +// randomly drop connections + +const ( + FuzzModeDrop = "drop" + FuzzModeDelay = "delay" +) + +func FuzzConn(config cfg.Config, conn net.Conn) net.Conn { + return &FuzzedConnection{ + conn: conn, + start: time.After(time.Second * 10), // so we have time to do peer handshakes and get set up + params: config, + } +} + +type FuzzedConnection struct { + conn net.Conn + + mtx sync.Mutex + fuzz bool // we don't start fuzzing right away + start <-chan time.Time + + // fuzz params + params cfg.Config +} + +func (fc *FuzzedConnection) randomDuration() time.Duration { + return time.Millisecond * time.Duration(rand.Int()%fc.MaxDelayMilliseconds()) +} + +func (fc *FuzzedConnection) Active() bool { + return fc.params.GetBool(configFuzzActive) +} + +func (fc *FuzzedConnection) Mode() string { + return fc.params.GetString(configFuzzMode) +} + +func (fc *FuzzedConnection) ProbDropRW() float64 { + return fc.params.GetFloat64(configFuzzProbDropRW) +} + +func (fc *FuzzedConnection) ProbDropConn() float64 { + return fc.params.GetFloat64(configFuzzProbDropConn) +} + +func (fc *FuzzedConnection) ProbSleep() float64 { + return fc.params.GetFloat64(configFuzzProbSleep) +} + +func (fc *FuzzedConnection) MaxDelayMilliseconds() int { + return fc.params.GetInt(configFuzzMaxDelayMilliseconds) +} + +// implements the fuzz (delay, kill conn) +// and returns whether or not the read/write should be ignored +func (fc *FuzzedConnection) Fuzz() bool { + if !fc.shouldFuzz() { + return false + } + + switch fc.Mode() { + case FuzzModeDrop: + // randomly drop the r/w, drop the conn, or sleep + r := rand.Float64() + if r <= fc.ProbDropRW() { + return true + } else if r < fc.ProbDropRW()+fc.ProbDropConn() { + // XXX: can't this fail because machine precision? + // XXX: do we need an error? + fc.Close() + return true + } else if r < fc.ProbDropRW()+fc.ProbDropConn()+fc.ProbSleep() { + time.Sleep(fc.randomDuration()) + } + case FuzzModeDelay: + // sleep a bit + time.Sleep(fc.randomDuration()) + } + return false +} + +// we don't fuzz until start chan fires +func (fc *FuzzedConnection) shouldFuzz() bool { + if !fc.Active() { + return false + } + + fc.mtx.Lock() + defer fc.mtx.Unlock() + if fc.fuzz { + return true + } + + select { + case <-fc.start: + fc.fuzz = true + default: + } + return false +} + +func (fc *FuzzedConnection) Read(data []byte) (n int, err error) { + if fc.Fuzz() { + return 0, nil + } + return fc.conn.Read(data) +} + +func (fc *FuzzedConnection) Write(data []byte) (n int, err error) { + if fc.Fuzz() { + return 0, nil + } + return fc.conn.Write(data) +} + +// Implements net.Conn +func (fc *FuzzedConnection) Close() error { return fc.conn.Close() } +func (fc *FuzzedConnection) LocalAddr() net.Addr { return fc.conn.LocalAddr() } +func (fc *FuzzedConnection) RemoteAddr() net.Addr { return fc.conn.RemoteAddr() } +func (fc *FuzzedConnection) SetDeadline(t time.Time) error { return fc.conn.SetDeadline(t) } +func (fc *FuzzedConnection) SetReadDeadline(t time.Time) error { + return fc.conn.SetReadDeadline(t) +} +func (fc *FuzzedConnection) SetWriteDeadline(t time.Time) error { + return fc.conn.SetWriteDeadline(t) +} diff --git a/switch.go b/switch.go index 5aa8b64ed..3cb5f5c9d 100644 --- a/switch.go +++ b/switch.go @@ -292,6 +292,9 @@ func (sw *Switch) DialPeerWithAddress(addr *NetAddress) (*Peer, error) { log.Info("Failed dialing address", "address", addr, "error", err) return nil, err } + if sw.config.GetBool(configFuzzEnable) { + conn = FuzzConn(sw.config, conn) + } peer, err := sw.AddPeerWithConnection(conn, true) if err != nil { log.Info("Failed adding peer", "address", addr, "conn", conn, "error", err) @@ -383,6 +386,10 @@ func (sw *Switch) listenerRoutine(l Listener) { continue } + if sw.config.GetBool(configFuzzEnable) { + inConn = FuzzConn(sw.config, inConn) + } + // New inbound connection! _, err := sw.AddPeerWithConnection(inConn, false) if err != nil { From 6684a1873003bb9d2f24b4c09c5c1c47518df564 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Thu, 12 May 2016 00:08:41 -0400 Subject: [PATCH 040/309] fix test --- switch_test.go | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/switch_test.go b/switch_test.go index 046649791..783d2fd93 100644 --- a/switch_test.go +++ b/switch_test.go @@ -7,10 +7,21 @@ import ( "time" . "github.com/tendermint/go-common" + cfg "github.com/tendermint/go-config" "github.com/tendermint/go-crypto" "github.com/tendermint/go-wire" ) +var ( + config cfg.Config +) + +func init() { + config = cfg.NewMapConfig(nil) + setConfigDefaults(config) + +} + type PeerMessage struct { PeerKey string Bytes []byte @@ -74,7 +85,7 @@ func makeSwitchPair(t testing.TB, initSwitch func(*Switch) *Switch) (*Switch, *S s2PrivKey := crypto.GenPrivKeyEd25519() // Create two switches that will be interconnected. - s1 := initSwitch(NewSwitch()) + s1 := initSwitch(NewSwitch(config)) s1.SetNodeInfo(&NodeInfo{ PubKey: s1PrivKey.PubKey().(crypto.PubKeyEd25519), Moniker: "switch1", @@ -82,7 +93,7 @@ func makeSwitchPair(t testing.TB, initSwitch func(*Switch) *Switch) (*Switch, *S Version: "123.123.123", }) s1.SetNodePrivKey(s1PrivKey) - s2 := initSwitch(NewSwitch()) + s2 := initSwitch(NewSwitch(config)) s2.SetNodeInfo(&NodeInfo{ PubKey: s2PrivKey.PubKey().(crypto.PubKeyEd25519), Moniker: "switch2", From 5bd7692323ec60d6461678f09b5024a952164151 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Thu, 12 May 2016 00:10:46 -0400 Subject: [PATCH 041/309] version bump --- version.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/version.go b/version.go index d4a712f0b..e9c345cbe 100644 --- a/version.go +++ b/version.go @@ -1,3 +1,3 @@ package p2p -const Version = "0.3.2" // memory optimizations +const Version = "0.3.3" // fuzz conn From 981c6868ada7b968e1a95afde591344f7b5981bc Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Tue, 21 Jun 2016 14:35:29 -0400 Subject: [PATCH 042/309] fix race conditions in tests --- connection.go | 2 -- switch.go | 2 +- switch_test.go | 12 +++++++++--- 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/connection.go b/connection.go index aa707b97c..68b4e0b31 100644 --- a/connection.go +++ b/connection.go @@ -87,8 +87,6 @@ type MConnection struct { } func NewMConnection(config cfg.Config, conn net.Conn, chDescs []*ChannelDescriptor, onReceive receiveCbFunc, onError errorCbFunc) *MConnection { - setConfigDefaults(config) - mconn := &MConnection{ conn: conn, bufReader: bufio.NewReaderSize(conn, minReadBufferSize), diff --git a/switch.go b/switch.go index 3cb5f5c9d..921dcf981 100644 --- a/switch.go +++ b/switch.go @@ -181,8 +181,8 @@ func (sw *Switch) OnStop() { // Stop peers for _, peer := range sw.peers.List() { peer.Stop() + sw.peers.Remove(peer) } - sw.peers = NewPeerSet() // Stop reactors for _, reactor := range sw.reactors { reactor.Stop() diff --git a/switch_test.go b/switch_test.go index 783d2fd93..e46d0f853 100644 --- a/switch_test.go +++ b/switch_test.go @@ -76,6 +76,12 @@ func (tr *TestReactor) Receive(chID byte, peer *Peer, msgBytes []byte) { } } +func (tr *TestReactor) getMsgs(chID byte) []PeerMessage { + tr.mtx.Lock() + defer tr.mtx.Unlock() + return tr.msgsReceived[chID] +} + //----------------------------------------------------------------------------- // convenience method for creating two switches connected to each other. @@ -170,7 +176,7 @@ func TestSwitches(t *testing.T) { time.Sleep(5000 * time.Millisecond) // Check message on ch0 - ch0Msgs := s2.Reactor("foo").(*TestReactor).msgsReceived[byte(0x00)] + ch0Msgs := s2.Reactor("foo").(*TestReactor).getMsgs(byte(0x00)) if len(ch0Msgs) != 1 { t.Errorf("Expected to have received 1 message in ch0") } @@ -179,7 +185,7 @@ func TestSwitches(t *testing.T) { } // Check message on ch1 - ch1Msgs := s2.Reactor("foo").(*TestReactor).msgsReceived[byte(0x01)] + ch1Msgs := s2.Reactor("foo").(*TestReactor).getMsgs(byte(0x01)) if len(ch1Msgs) != 1 { t.Errorf("Expected to have received 1 message in ch1") } @@ -188,7 +194,7 @@ func TestSwitches(t *testing.T) { } // Check message on ch2 - ch2Msgs := s2.Reactor("bar").(*TestReactor).msgsReceived[byte(0x02)] + ch2Msgs := s2.Reactor("bar").(*TestReactor).getMsgs(byte(0x02)) if len(ch2Msgs) != 1 { t.Errorf("Expected to have received 1 message in ch2") } From 7376a72dd7fa4ca6667991497f69b5313aa9291d Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Tue, 21 Jun 2016 14:40:24 -0400 Subject: [PATCH 043/309] circle badge --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 3fc02e2f2..236efd367 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ # `tendermint/go-p2p` +[![CircleCI](https://circleci.com/gh/tendermint/go-p2p.svg?style=svg)](https://circleci.com/gh/tendermint/go-p2p) + `tendermint/go-p2p` provides an abstraction around peer-to-peer communication.
## Peer/MConnection/Channel From 7ea86f65066b8a9bf448ef595d72929ed9999a9a Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Tue, 21 Jun 2016 15:19:56 -0400 Subject: [PATCH 044/309] fix test race and update readme --- README.md | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++ rpc_test.go | 8 ++++---- 2 files changed, 61 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index e74cf8021..f6e725c23 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,61 @@ # go-rpc +[![CircleCI](https://circleci.com/gh/tendermint/go-rpc.svg?style=svg)](https://circleci.com/gh/tendermint/go-rpc) + HTTP RPC server supporting calls via uri params, jsonrpc, and jsonrpc over websockets +# How To + +Define some types and routes: + +``` +// Define a type for results and register concrete versions with go-wire +type Result interface{} + +type ResultStatus struct { + Value string +} + +var _ = wire.RegisterInterface( + struct{ Result }{}, + wire.ConcreteType{&ResultStatus{}, 0x1}, +) + +// Define some routes +var Routes = map[string]*rpcserver.RPCFunc{ + "status": rpcserver.NewRPCFunc(StatusResult, "arg"), +} + +// an rpc function +func StatusResult(v string) (Result, error) { + return &ResultStatus{v}, nil +} + +``` + +Now start the server: + +``` +mux := http.NewServeMux() +rpcserver.RegisterRPCFuncs(mux, Routes) +wm := rpcserver.NewWebsocketManager(Routes, nil) +mux.HandleFunc("/websocket", wm.WebsocketHandler) +go func() { + _, err := rpcserver.StartHTTPServer("0.0.0.0:46657", mux) + if err != nil { + panic(err) + } +}() + +``` + +Note that unix sockets are supported as well (eg. `/path/to/socket` instead of `0.0.0.0:46657`) + +Now see all available endpoints by sending a GET request to `0.0.0.0:46657`. +Each route is available as a GET request, as a JSONRPCv2 POST request, and via JSONRPCv2 over websockets + + +# Examples + +* [Tendermint](https://github.com/tendermint/tendermint/blob/master/rpc/core/routes.go) +* [Network Monitor](https://github.com/tendermint/netmon/blob/master/handlers/routes.go) diff --git a/rpc_test.go b/rpc_test.go index f23f6cdfb..82bdeb136 100644 --- a/rpc_test.go +++ b/rpc_test.go @@ -54,12 +54,12 @@ func init() { } }() - mux = http.NewServeMux() - rpcserver.RegisterRPCFuncs(mux, Routes) + mux2 := http.NewServeMux() + rpcserver.RegisterRPCFuncs(mux2, Routes) wm = rpcserver.NewWebsocketManager(Routes, nil) - mux.HandleFunc(websocketEndpoint, wm.WebsocketHandler) + mux2.HandleFunc(websocketEndpoint, wm.WebsocketHandler) go func() { - _, err := rpcserver.StartHTTPServer(unixAddr, mux) + _, err := rpcserver.StartHTTPServer(unixAddr, mux2) if err != nil { panic(err) } From 0c70a4636acc77ffcfdcccc5e6e57305bd7183a2 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Thu, 23 Jun 2016 20:33:04 -0400 Subject: [PATCH 045/309] add better docs to readme --- README.md | 58 +++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 54 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index f6e725c23..a68823101 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,57 @@ HTTP RPC server supporting calls via uri params, jsonrpc, and jsonrpc over websockets -# How To +# Client Requests + +Suppose we want to expose the rpc function `HelloWorld(name string, num int)`. + +## GET (URI) + +As a GET request, it would have URI encoded parameters, and look like: + +``` +curl 'http://localhost:8008/hello_world?name="my_world"&num=5' +``` + +Note the `'` around the url, which is just so bash doesn't ignore the quotes in `"my_world"`. +This should also work: + +``` +curl http://localhost:8008/hello_world?name=\"my_world\"&num=5 +``` + +A GET request to `/` returns a list of available endpoints. +For those which take arguments, the arguments will be listed in order, with `_` where the actual value should be. + +## POST (JSONRPC) + +As a POST request, we use JSONRPC. For instance, the same request would have this as the body: + +``` +{ + "jsonrpc":"2.0", + "id":"anything", + "method":"hello_world", + "params":["my_world", 5] +} +``` + +Note the `params` does not currently support key-value pairs (#1), so order matters (you can get the order from making a +GET request to `/`) + +With the above saved in file `data.json`, we can make the request with + +``` +curl --data @data.json http://localhost:8008 +``` + +## WebSocket (JSONRPC) + +All requests are exposed over websocket in the same form as the POST JSONRPC. +Websocket connections are available at their own endpoint, typically `/websocket`, +though this is configurable when starting the server. + +# Server Definition Define some types and routes: @@ -41,7 +91,7 @@ rpcserver.RegisterRPCFuncs(mux, Routes) wm := rpcserver.NewWebsocketManager(Routes, nil) mux.HandleFunc("/websocket", wm.WebsocketHandler) go func() { - _, err := rpcserver.StartHTTPServer("0.0.0.0:46657", mux) + _, err := rpcserver.StartHTTPServer("0.0.0.0:8008", mux) if err != nil { panic(err) } @@ -49,9 +99,9 @@ go func() { ``` -Note that unix sockets are supported as well (eg. `/path/to/socket` instead of `0.0.0.0:46657`) +Note that unix sockets are supported as well (eg. `/path/to/socket` instead of `0.0.0.0:8008`) -Now see all available endpoints by sending a GET request to `0.0.0.0:46657`. +Now see all available endpoints by sending a GET request to `0.0.0.0:8008`. Each route is available as a GET request, as a JSONRPCv2 POST request, and via JSONRPCv2 over websockets From a44e0e0f4b1a3d18060dc97ffca9a11e83bb2c13 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Thu, 23 Jun 2016 20:36:59 -0400 Subject: [PATCH 046/309] add test example --- Makefile | 11 +++++++++++ circle.yml | 23 +++++++++++++++++++++++ test/data.json | 6 ++++++ test/main.go | 35 +++++++++++++++++++++++++++++++++++ test/test.sh | 23 +++++++++++++++++++++++ 5 files changed, 98 insertions(+) create mode 100644 Makefile create mode 100644 circle.yml create mode 100644 test/data.json create mode 100644 test/main.go create mode 100644 test/test.sh diff --git a/Makefile b/Makefile new file mode 100644 index 000000000..6d72cf6ff --- /dev/null +++ b/Makefile @@ -0,0 +1,11 @@ +.PHONY: all test get_deps + +all: test + +test: + go test github.com/tendermint/go-rpc/... + cd ./test && bash test.sh + + +get_deps: + go get -t -d github.com/tendermint/go-rpc/... diff --git a/circle.yml b/circle.yml new file mode 100644 index 000000000..f022d5a6b --- /dev/null +++ b/circle.yml @@ -0,0 +1,23 @@ +machine: + environment: + GOPATH: /home/ubuntu/.go_workspace + REPO: $GOPATH/src/github.com/$CIRCLE_PROJECT_USERNAME/$CIRCLE_PROJECT_REPONAME + hosts: + circlehost: 127.0.0.1 + localhost: 127.0.0.1 + +checkout: + post: + - rm -rf $REPO + - mkdir -p $HOME/.go_workspace/src/github.com/$CIRCLE_PROJECT_USERNAME + - mv $HOME/$CIRCLE_PROJECT_REPONAME $REPO + # - git submodule sync + # - git submodule update --init # use submodules + +dependencies: + override: + - "cd $REPO && make get_deps" + +test: + override: + - "cd $REPO && make test" diff --git a/test/data.json b/test/data.json new file mode 100644 index 000000000..eac2e0dfe --- /dev/null +++ b/test/data.json @@ -0,0 +1,6 @@ +{ + "jsonrpc":"2.0", + "id":"", + "method":"hello_world", + "params":["my_world", 5] +} diff --git a/test/main.go b/test/main.go new file mode 100644 index 000000000..d14ab05f5 --- /dev/null +++ b/test/main.go @@ -0,0 +1,35 @@ +package main + +import ( + "fmt" + "net/http" + + . "github.com/tendermint/go-common" + rpcserver "github.com/tendermint/go-rpc/server" +) + +var routes = map[string]*rpcserver.RPCFunc{ + "hello_world": rpcserver.NewRPCFunc(HelloWorld, "name,num"), +} + +func HelloWorld(name string, num int) (Result, error) { + return Result{fmt.Sprintf("hi %s %d", name, num)}, nil +} + +type Result struct { + Result string +} + +func main() { + mux := http.NewServeMux() + rpcserver.RegisterRPCFuncs(mux, routes) + _, err := rpcserver.StartHTTPServer("0.0.0.0:8008", mux) + if err != nil { + Exit(err.Error()) + } + + // Wait forever + TrapSignal(func() { + }) + +} diff --git a/test/test.sh b/test/test.sh new file mode 100644 index 000000000..3d1f599dd --- /dev/null +++ b/test/test.sh @@ -0,0 +1,23 @@ +#! /bin/bash +set -e + +go build -o server main.go +./server > /dev/null & +PID=$! +sleep 2 + + +R1=`curl -s 'http://localhost:8008/hello_world?name="my_world"&num=5'` + + +R2=`curl -s --data @data.json http://localhost:8008` + +kill -9 $PID + +if [[ "$R1" != "$R2" ]]; then + echo "responses are not identical:" + echo "R1: $R1" + echo "R2: $R2" + exit 1 +fi +echo "Success" From a8ac81913984df85d2a848e5fc89a6d87f349662 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Thu, 23 Jun 2016 20:40:16 -0400 Subject: [PATCH 047/309] link issue from readme --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index a68823101..1a91fb693 100644 --- a/README.md +++ b/README.md @@ -39,7 +39,7 @@ As a POST request, we use JSONRPC. For instance, the same request would have thi } ``` -Note the `params` does not currently support key-value pairs (#1), so order matters (you can get the order from making a +Note the `params` does not currently support key-value pairs (https://github.com/tendermint/go-rpc/issues/1), so order matters (you can get the order from making a GET request to `/`) With the above saved in file `data.json`, we can make the request with From 711d2541f500b8c008e1efd70cfeeb687ee19e48 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Sat, 25 Jun 2016 21:59:52 -0400 Subject: [PATCH 048/309] MakeConnectedSwitches function --- listener_test.go | 40 +++++++++++++++++++++++++++++++ netaddress.go | 7 ++++-- switch.go | 42 ++++++++++++++++++++++++++++++++ switch_test.go | 62 ++++++------------------------------------------ 4 files changed, 94 insertions(+), 57 deletions(-) create mode 100644 listener_test.go diff --git a/listener_test.go b/listener_test.go new file mode 100644 index 000000000..0f8a54946 --- /dev/null +++ b/listener_test.go @@ -0,0 +1,40 @@ +package p2p + +import ( + "bytes" + "testing" +) + +func TestListener(t *testing.T) { + // Create a listener + l := NewDefaultListener("tcp", ":8001", true) + + // Dial the listener + lAddr := l.ExternalAddress() + connOut, err := lAddr.Dial() + if err != nil { + t.Fatalf("Could not connect to listener address %v", lAddr) + } else { + t.Logf("Created a connection to listener address %v", lAddr) + } + connIn, ok := <-l.Connections() + if !ok { + t.Fatalf("Could not get inbound connection from listener") + } + + msg := []byte("hi!") + go connIn.Write(msg) + b := make([]byte, 32) + n, err := connOut.Read(b) + if err != nil { + t.Fatalf("Error reading off connection: %v", err) + } + + b = b[:n] + if !bytes.Equal(msg, b) { + t.Fatalf("Got %s, expected %s", b, msg) + } + + // Close the server, no longer needed. + l.Stop() +} diff --git a/netaddress.go b/netaddress.go index bdb42a004..34dc5cafb 100644 --- a/netaddress.go +++ b/netaddress.go @@ -5,7 +5,6 @@ package p2p import ( - "fmt" "net" "strconv" "time" @@ -23,7 +22,11 @@ type NetAddress struct { func NewNetAddress(addr net.Addr) *NetAddress { tcpAddr, ok := addr.(*net.TCPAddr) if !ok { - PanicSanity(fmt.Sprintf("Only TCPAddrs are supported. Got: %v", addr)) + log.Warn(`Only TCPAddrs are supported. If used for anything but testing, + may result in undefined behaviour!`, "addr", addr) + return NewNetAddressIPPort(net.IP("0.0.0.0"), 0) + // NOTE: it would be nice to only not panic if we're in testing ... + // PanicSanity(Fmt("Only TCPAddrs are supported. Got: %v", addr)) } ip := tcpAddr.IP port := uint16(tcpAddr.Port) diff --git a/switch.go b/switch.go index 921dcf981..f9a146d2e 100644 --- a/switch.go +++ b/switch.go @@ -415,3 +415,45 @@ type SwitchEventDonePeer struct { Peer *Peer Error interface{} } + +//------------------------------------------------------------------ +// Switches connected via arbitrary net.Conn; useful for testing + +// Returns n fully connected switches. +// initSwitch defines how the ith switch should be initialized (ie. with what reactors). +func MakeConnectedSwitches(n int, initSwitch func(int, *Switch) *Switch, connPipe func() (net.Conn, net.Conn)) []*Switch { + switches := make([]*Switch, n) + for i := 0; i < n; i++ { + switches[i] = makeSwitch(i, "testing", "123.123.123", initSwitch) + } + + for i := 0; i < n; i++ { + switchI := switches[i] + for j := i; j < n; j++ { + switchJ := switches[j] + c1, c2 := connPipe() + go switchI.AddPeerWithConnection(c1, false) // AddPeer is blocking, requires handshake. + go switchJ.AddPeerWithConnection(c2, true) + } + } + // Wait for things to happen, peers to get added... + time.Sleep(100 * time.Millisecond * time.Duration(n*n)) + + return switches +} + +func makeSwitch(i int, network, version string, initSwitch func(int, *Switch) *Switch) *Switch { + privKey := crypto.GenPrivKeyEd25519() + // new switch, add reactors + // TODO: let the config be passed in? + s := initSwitch(i, NewSwitch(cfg.NewMapConfig(nil))) + s.SetNodeInfo(&NodeInfo{ + PubKey: privKey.PubKey().(crypto.PubKeyEd25519), + Moniker: Fmt("switch%d", i), + Network: network, + Version: version, + }) + s.SetNodePrivKey(privKey) + s.Start() // start switch and reactors + return s +} diff --git a/switch_test.go b/switch_test.go index e46d0f853..54d6f7527 100644 --- a/switch_test.go +++ b/switch_test.go @@ -2,13 +2,13 @@ package p2p import ( "bytes" + "net" "sync" "testing" "time" . "github.com/tendermint/go-common" cfg "github.com/tendermint/go-config" - "github.com/tendermint/go-crypto" "github.com/tendermint/go-wire" ) @@ -85,63 +85,15 @@ func (tr *TestReactor) getMsgs(chID byte) []PeerMessage { //----------------------------------------------------------------------------- // convenience method for creating two switches connected to each other. -func makeSwitchPair(t testing.TB, initSwitch func(*Switch) *Switch) (*Switch, *Switch) { - - s1PrivKey := crypto.GenPrivKeyEd25519() - s2PrivKey := crypto.GenPrivKeyEd25519() - +// XXX: note this uses net.Pipe and not a proper TCP conn +func makeSwitchPair(t testing.TB, initSwitch func(int, *Switch) *Switch) (*Switch, *Switch) { // Create two switches that will be interconnected. - s1 := initSwitch(NewSwitch(config)) - s1.SetNodeInfo(&NodeInfo{ - PubKey: s1PrivKey.PubKey().(crypto.PubKeyEd25519), - Moniker: "switch1", - Network: "testing", - Version: "123.123.123", - }) - s1.SetNodePrivKey(s1PrivKey) - s2 := initSwitch(NewSwitch(config)) - s2.SetNodeInfo(&NodeInfo{ - PubKey: s2PrivKey.PubKey().(crypto.PubKeyEd25519), - Moniker: "switch2", - Network: "testing", - Version: "123.123.123", - }) - s2.SetNodePrivKey(s2PrivKey) - - // Start switches and reactors - s1.Start() - s2.Start() - - // Create a listener for s1 - l := NewDefaultListener("tcp", ":8001", true) - - // Dial the listener & add the connection to s2. - lAddr := l.ExternalAddress() - connOut, err := lAddr.Dial() - if err != nil { - t.Fatalf("Could not connect to listener address %v", lAddr) - } else { - t.Logf("Created a connection to listener address %v", lAddr) - } - connIn, ok := <-l.Connections() - if !ok { - t.Fatalf("Could not get inbound connection from listener") - } - - go s1.AddPeerWithConnection(connIn, false) // AddPeer is blocking, requires handshake. - s2.AddPeerWithConnection(connOut, true) - - // Wait for things to happen, peers to get added... - time.Sleep(100 * time.Millisecond) - - // Close the server, no longer needed. - l.Stop() - - return s1, s2 + switches := MakeConnectedSwitches(2, initSwitch, net.Pipe) + return switches[0], switches[1] } func TestSwitches(t *testing.T) { - s1, s2 := makeSwitchPair(t, func(sw *Switch) *Switch { + s1, s2 := makeSwitchPair(t, func(i int, sw *Switch) *Switch { // Make two reactors of two channels each sw.AddReactor("foo", NewTestReactor([]*ChannelDescriptor{ &ChannelDescriptor{ID: byte(0x00), Priority: 10}, @@ -208,7 +160,7 @@ func BenchmarkSwitches(b *testing.B) { b.StopTimer() - s1, s2 := makeSwitchPair(b, func(sw *Switch) *Switch { + s1, s2 := makeSwitchPair(b, func(i int, sw *Switch) *Switch { // Make bar reactors of bar channels each sw.AddReactor("foo", NewTestReactor([]*ChannelDescriptor{ &ChannelDescriptor{ID: byte(0x00), Priority: 10}, From 929cf433b9c8e987af5f7f3ca3ce717e1e3eda53 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Sun, 26 Jun 2016 00:34:34 -0400 Subject: [PATCH 049/309] fix chDesc race --- connection.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/connection.go b/connection.go index 68b4e0b31..6c8ccd435 100644 --- a/connection.go +++ b/connection.go @@ -115,7 +115,8 @@ func NewMConnection(config cfg.Config, conn net.Conn, chDescs []*ChannelDescript var channels = []*Channel{} for _, desc := range chDescs { - channel := newChannel(mconn, desc) + descCopy := *desc // copy the desc else unsafe access across connections + channel := newChannel(mconn, &descCopy) channelsIdx[channel.id] = channel channels = append(channels, channel) } From 39ee59c26e3b25aeef7c0e2c360f0fe1a27a4182 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 22 Jul 2016 01:13:16 -0400 Subject: [PATCH 050/309] server: return result with error --- server/handlers.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/handlers.go b/server/handlers.go index 1c447c6c9..82fd7b358 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -132,7 +132,7 @@ func makeJSONRPCHandler(funcMap map[string]*RPCFunc) http.HandlerFunc { log.Info("HTTPJSONRPC", "method", request.Method, "args", args, "returns", returns) result, err := unreflectResult(returns) if err != nil { - WriteRPCResponseHTTP(w, NewRPCResponse(request.ID, nil, err.Error())) + WriteRPCResponseHTTP(w, NewRPCResponse(request.ID, result, err.Error())) return } WriteRPCResponseHTTP(w, NewRPCResponse(request.ID, result, "")) From dea910cd3e71bbfaf1973fd7ba295f0ee515a25f Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 22 Jul 2016 01:15:52 -0400 Subject: [PATCH 051/309] Makefile: go test --race --- Makefile | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Makefile b/Makefile index 6d72cf6ff..4cc7c1594 100644 --- a/Makefile +++ b/Makefile @@ -3,7 +3,7 @@ all: test test: - go test github.com/tendermint/go-rpc/... + go test --race github.com/tendermint/go-rpc/... cd ./test && bash test.sh From 479510be0e80dd9e5d6b1f941adad168df0af85f Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Wed, 10 Aug 2016 01:12:01 -0400 Subject: [PATCH 052/309] support full urls (with eg tcp:// prefix) --- client/http_client.go | 58 +++++++++++++++++++++++++++---------------- client/ws_client.go | 10 +++++--- rpc_test.go | 4 +-- server/http_server.go | 23 +++++++++++++---- version.go | 2 +- 5 files changed, 65 insertions(+), 32 deletions(-) diff --git a/client/http_client.go b/client/http_client.go index 7c0480600..63dd9a82d 100644 --- a/client/http_client.go +++ b/client/http_client.go @@ -8,26 +8,40 @@ import ( "net" "net/http" "net/url" + "strings" . "github.com/tendermint/go-common" "github.com/tendermint/go-rpc/types" "github.com/tendermint/go-wire" ) -// Set the net.Dial manually so we can do http over tcp or unix. -// Get/Post require a dummyDomain but it's over written by the Transport -var dummyDomain = "http://dummyDomain" +// TODO: Deprecate support for IP:PORT or /path/to/socket +func makeHTTPDialer(remoteAddr string) (string, func(string, string) (net.Conn, error)) { -func dialer(remote string) func(string, string) (net.Conn, error) { - return func(proto, addr string) (conn net.Conn, err error) { - return net.Dial(rpctypes.SocketType(remote), remote) + parts := strings.SplitN(remoteAddr, "://", 2) + var protocol, address string + if len(parts) != 2 { + log.Warn("WARNING (go-rpc): Please use fully formed listening addresses, including the tcp:// or unix:// prefix") + protocol = rpctypes.SocketType(remoteAddr) + address = remoteAddr + } else { + protocol, address = parts[0], parts[1] + } + + trimmedAddress := strings.Replace(address, "/", ".", -1) // replace / with . for http requests (dummy domain) + return trimmedAddress, func(proto, addr string) (net.Conn, error) { + return net.Dial(protocol, address) } } -// remote is IP:PORT or /path/to/socket -func socketTransport(remote string) *http.Transport { - return &http.Transport{ - Dial: dialer(remote), +// We overwrite the http.Client.Dial so we can do http over tcp or unix. +// remoteAddr should be fully featured (eg. with tcp:// or unix://) +func makeHTTPClient(remoteAddr string) (string, *http.Client) { + address, dialer := makeHTTPDialer(remoteAddr) + return "http://" + address, &http.Client{ + Transport: &http.Transport{ + Dial: dialer, + }, } } @@ -40,14 +54,15 @@ type Client interface { // JSON rpc takes params as a slice type ClientJSONRPC struct { - remote string - client *http.Client + address string + client *http.Client } func NewClientJSONRPC(remote string) *ClientJSONRPC { + address, client := makeHTTPClient(remote) return &ClientJSONRPC{ - remote: remote, - client: &http.Client{Transport: socketTransport(remote)}, + address: address, + client: client, } } @@ -66,7 +81,7 @@ func (c *ClientJSONRPC) call(method string, params []interface{}, result interfa requestBytes := wire.JSONBytes(request) requestBuf := bytes.NewBuffer(requestBytes) // log.Info(Fmt("RPC request to %v (%v): %v", c.remote, method, string(requestBytes))) - httpResponse, err := c.client.Post(dummyDomain, "text/json", requestBuf) + httpResponse, err := c.client.Post(c.address, "text/json", requestBuf) if err != nil { return nil, err } @@ -83,14 +98,15 @@ func (c *ClientJSONRPC) call(method string, params []interface{}, result interfa // URI takes params as a map type ClientURI struct { - remote string - client *http.Client + address string + client *http.Client } func NewClientURI(remote string) *ClientURI { + address, client := makeHTTPClient(remote) return &ClientURI{ - remote: remote, - client: &http.Client{Transport: socketTransport(remote)}, + address: address, + client: client, } } @@ -103,8 +119,8 @@ func (c *ClientURI) call(method string, params map[string]interface{}, result in if err != nil { return nil, err } - log.Info(Fmt("URI request to %v (%v): %v", c.remote, method, values)) - resp, err := c.client.PostForm(dummyDomain+"/"+method, values) + log.Info(Fmt("URI request to %v (%v): %v", c.address, method, values)) + resp, err := c.client.PostForm(c.address+"/"+method, values) if err != nil { return nil, err } diff --git a/client/ws_client.go b/client/ws_client.go index a8b8ce80c..00e4222ad 100644 --- a/client/ws_client.go +++ b/client/ws_client.go @@ -3,6 +3,7 @@ package rpcclient import ( "encoding/json" "fmt" + "net" "net/http" "time" @@ -21,15 +22,18 @@ type WSClient struct { QuitService Address string // IP:PORT or /path/to/socket Endpoint string // /websocket/url/endpoint + Dialer func(string, string) (net.Conn, error) *websocket.Conn ResultsCh chan json.RawMessage // closes upon WSClient.Stop() ErrorsCh chan error // closes upon WSClient.Stop() } // create a new connection -func NewWSClient(addr, endpoint string) *WSClient { +func NewWSClient(remoteAddr, endpoint string) *WSClient { + addr, dialer := makeHTTPDialer(remoteAddr) wsClient := &WSClient{ Address: addr, + Dialer: dialer, Endpoint: endpoint, Conn: nil, ResultsCh: make(chan json.RawMessage, wsResultsChannelCapacity), @@ -57,11 +61,11 @@ func (wsc *WSClient) dial() error { // Dial dialer := &websocket.Dialer{ - NetDial: dialer(wsc.Address), + NetDial: wsc.Dialer, Proxy: http.ProxyFromEnvironment, } rHeader := http.Header{} - con, _, err := dialer.Dial("ws://"+dummyDomain+wsc.Endpoint, rHeader) + con, _, err := dialer.Dial("ws://"+wsc.Address+wsc.Endpoint, rHeader) if err != nil { return err } diff --git a/rpc_test.go b/rpc_test.go index 82bdeb136..0c6e1dbdb 100644 --- a/rpc_test.go +++ b/rpc_test.go @@ -13,8 +13,8 @@ import ( // Client and Server should work over tcp or unix sockets var ( - tcpAddr = "0.0.0.0:46657" - unixAddr = "/tmp/go-rpc.sock" // NOTE: must remove file for test to run again + tcpAddr = "tcp://0.0.0.0:46657" + unixAddr = "unix:///tmp/go-rpc.sock" // NOTE: must remove file for test to run again websocketEndpoint = "/websocket/endpoint" ) diff --git a/server/http_server.go b/server/http_server.go index cc3da39be..26163cf12 100644 --- a/server/http_server.go +++ b/server/http_server.go @@ -8,6 +8,7 @@ import ( "net" "net/http" "runtime/debug" + "strings" "time" . "github.com/tendermint/go-common" @@ -15,11 +16,23 @@ import ( //"github.com/tendermint/go-wire" ) -func StartHTTPServer(listenAddr string, handler http.Handler) (net.Listener, error) { - // listenAddr is `IP:PORT` or /path/to/socket - socketType := SocketType(listenAddr) - log.Notice(Fmt("Starting RPC HTTP server on %s socket %v", socketType, listenAddr)) - listener, err := net.Listen(socketType, listenAddr) +func StartHTTPServer(listenAddr string, handler http.Handler) (listener net.Listener, err error) { + // listenAddr should be fully formed including tcp:// or unix:// prefix + var proto, addr string + parts := strings.SplitN(listenAddr, "://", 2) + if len(parts) != 2 { + log.Warn("WARNING (go-rpc): Please use fully formed listening addresses, including the tcp:// or unix:// prefix") + // we used to allow addrs without tcp/unix prefix by checking for a colon + // TODO: Deprecate + proto = SocketType(listenAddr) + addr = listenAddr + // return nil, fmt.Errorf("Invalid listener address %s", lisenAddr) + } else { + proto, addr = parts[0], parts[1] + } + + log.Notice(Fmt("Starting RPC HTTP server on %s socket %v", proto, addr)) + listener, err = net.Listen(proto, addr) if err != nil { return nil, fmt.Errorf("Failed to listen to %v: %v", listenAddr, err) } diff --git a/version.go b/version.go index d0a0ee9cd..edf8d40da 100644 --- a/version.go +++ b/version.go @@ -2,6 +2,6 @@ package rpc const Maj = "0" const Min = "5" // refactored out of tendermint/tendermint; RPCResponse.Result is RawJSON -const Fix = "0" +const Fix = "1" // support tcp:// or unix:// prefixes const Version = Maj + "." + Min + "." + Fix From 642901d5aae311368d91ebfb888a4f6877de9614 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Wed, 10 Aug 2016 02:33:38 -0400 Subject: [PATCH 053/309] filter conn by addr/pubkey. closes #3 --- switch.go | 37 ++++++++++++++++++++ switch_test.go | 91 ++++++++++++++++++++++++++++++++++++++++++-------- version.go | 2 +- 3 files changed, 116 insertions(+), 14 deletions(-) diff --git a/switch.go b/switch.go index f9a146d2e..e3016f31b 100644 --- a/switch.go +++ b/switch.go @@ -65,6 +65,9 @@ type Switch struct { dialing *CMap nodeInfo *NodeInfo // our node info nodePrivKey crypto.PrivKeyEd25519 // our node privkey + + filterConnByAddr func(net.Addr) error + filterConnByPubKey func(crypto.PubKeyEd25519) error } var ( @@ -192,6 +195,11 @@ func (sw *Switch) OnStop() { // NOTE: This performs a blocking handshake before the peer is added. // CONTRACT: Iff error is returned, peer is nil, and conn is immediately closed. func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool) (*Peer, error) { + // Filter by ip + if err := sw.FilterConnByAddr(conn.RemoteAddr()); err != nil { + return nil, err + } + // Set deadline for handshake so we don't block forever on conn.ReadFull conn.SetDeadline(time.Now().Add( time.Duration(sw.config.GetInt(configKeyHandshakeTimeoutSeconds)) * time.Second)) @@ -206,6 +214,12 @@ func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool) (*Peer, er return nil, err } } + + // Filter by p2p-key + if err := sw.FilterConnByPubKey(sconn.(*SecretConnection).RemotePubKey()); err != nil { + return nil, err + } + // Then, perform node handshake peerNodeInfo, err := peerHandshake(sconn, sw.nodeInfo) if err != nil { @@ -251,6 +265,29 @@ func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool) (*Peer, er return peer, nil } +func (sw *Switch) FilterConnByAddr(addr net.Addr) error { + if sw.filterConnByAddr != nil { + return sw.filterConnByAddr(addr) + } + return nil +} + +func (sw *Switch) FilterConnByPubKey(pubkey crypto.PubKeyEd25519) error { + if sw.filterConnByPubKey != nil { + return sw.filterConnByPubKey(pubkey) + } + return nil + +} + +func (sw *Switch) SetAddrFilter(f func(net.Addr) error) { + sw.filterConnByAddr = f +} + +func (sw *Switch) SetPubKeyFilter(f func(crypto.PubKeyEd25519) error) { + sw.filterConnByPubKey = f +} + func (sw *Switch) startInitPeer(peer *Peer) { peer.Start() // spawn send/recv routines sw.addPeerToReactors(peer) // run AddPeer on each reactor diff --git a/switch_test.go b/switch_test.go index 54d6f7527..f77682b66 100644 --- a/switch_test.go +++ b/switch_test.go @@ -2,6 +2,7 @@ package p2p import ( "bytes" + "fmt" "net" "sync" "testing" @@ -9,6 +10,7 @@ import ( . "github.com/tendermint/go-common" cfg "github.com/tendermint/go-config" + "github.com/tendermint/go-crypto" "github.com/tendermint/go-wire" ) @@ -92,23 +94,24 @@ func makeSwitchPair(t testing.TB, initSwitch func(int, *Switch) *Switch) (*Switc return switches[0], switches[1] } +func initSwitchFunc(i int, sw *Switch) *Switch { + // Make two reactors of two channels each + sw.AddReactor("foo", NewTestReactor([]*ChannelDescriptor{ + &ChannelDescriptor{ID: byte(0x00), Priority: 10}, + &ChannelDescriptor{ID: byte(0x01), Priority: 10}, + }, true)) + sw.AddReactor("bar", NewTestReactor([]*ChannelDescriptor{ + &ChannelDescriptor{ID: byte(0x02), Priority: 10}, + &ChannelDescriptor{ID: byte(0x03), Priority: 10}, + }, true)) + return sw +} + func TestSwitches(t *testing.T) { - s1, s2 := makeSwitchPair(t, func(i int, sw *Switch) *Switch { - // Make two reactors of two channels each - sw.AddReactor("foo", NewTestReactor([]*ChannelDescriptor{ - &ChannelDescriptor{ID: byte(0x00), Priority: 10}, - &ChannelDescriptor{ID: byte(0x01), Priority: 10}, - }, true)) - sw.AddReactor("bar", NewTestReactor([]*ChannelDescriptor{ - &ChannelDescriptor{ID: byte(0x02), Priority: 10}, - &ChannelDescriptor{ID: byte(0x03), Priority: 10}, - }, true)) - return sw - }) + s1, s2 := makeSwitchPair(t, initSwitchFunc) defer s1.Stop() defer s2.Stop() - // Lets send a message from s1 to s2. if s1.Peers().Size() != 1 { t.Errorf("Expected exactly 1 peer in s1, got %v", s1.Peers().Size()) } @@ -116,6 +119,7 @@ func TestSwitches(t *testing.T) { t.Errorf("Expected exactly 1 peer in s2, got %v", s2.Peers().Size()) } + // Lets send some messages ch0Msg := "channel zero" ch1Msg := "channel foo" ch2Msg := "channel bar" @@ -156,6 +160,67 @@ func TestSwitches(t *testing.T) { } +func TestConnAddrFilter(t *testing.T) { + s1 := makeSwitch(1, "testing", "123.123.123", initSwitchFunc) + s2 := makeSwitch(1, "testing", "123.123.123", initSwitchFunc) + + c1, c2 := net.Pipe() + + s1.SetAddrFilter(func(addr net.Addr) error { + if addr.String() == c1.RemoteAddr().String() { + return fmt.Errorf("Error: pipe is blacklisted") + } + return nil + }) + + // connect to good peer + go s1.AddPeerWithConnection(c1, false) // AddPeer is blocking, requires handshake. + go s2.AddPeerWithConnection(c2, true) + + // Wait for things to happen, peers to get added... + time.Sleep(100 * time.Millisecond * time.Duration(4)) + + defer s1.Stop() + defer s2.Stop() + if s1.Peers().Size() != 0 { + t.Errorf("Expected s1 not to connect to peers, got %d", s1.Peers().Size()) + } + if s2.Peers().Size() != 0 { + t.Errorf("Expected s2 not to connect to peers, got %d", s2.Peers().Size()) + } +} + +func TestConnPubKeyFilter(t *testing.T) { + s1 := makeSwitch(1, "testing", "123.123.123", initSwitchFunc) + s2 := makeSwitch(1, "testing", "123.123.123", initSwitchFunc) + + c1, c2 := net.Pipe() + + // set pubkey filter + s1.SetPubKeyFilter(func(pubkey crypto.PubKeyEd25519) error { + if bytes.Equal(pubkey.Bytes(), s2.nodeInfo.PubKey.Bytes()) { + return fmt.Errorf("Error: pipe is blacklisted") + } + return nil + }) + + // connect to good peer + go s1.AddPeerWithConnection(c1, false) // AddPeer is blocking, requires handshake. + go s2.AddPeerWithConnection(c2, true) + + // Wait for things to happen, peers to get added... + time.Sleep(100 * time.Millisecond * time.Duration(4)) + + defer s1.Stop() + defer s2.Stop() + if s1.Peers().Size() != 0 { + t.Errorf("Expected s1 not to connect to peers, got %d", s1.Peers().Size()) + } + if s2.Peers().Size() != 0 { + t.Errorf("Expected s2 not to connect to peers, got %d", s2.Peers().Size()) + } +} + func BenchmarkSwitches(b *testing.B) { b.StopTimer() diff --git a/version.go b/version.go index e9c345cbe..8608f2757 100644 --- a/version.go +++ b/version.go @@ -1,3 +1,3 @@ package p2p -const Version = "0.3.3" // fuzz conn +const Version = "0.3.4" // filter by addr or pubkey From 153ac88672de9b49b10ee216a535c0bd241d2654 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Wed, 14 Sep 2016 00:57:53 -0400 Subject: [PATCH 054/309] update MakeConnectedSwitches --- switch.go | 40 +++++++++++++++++++++++++++++++--------- switch_test.go | 2 +- 2 files changed, 32 insertions(+), 10 deletions(-) diff --git a/switch.go b/switch.go index e3016f31b..61d269491 100644 --- a/switch.go +++ b/switch.go @@ -195,7 +195,7 @@ func (sw *Switch) OnStop() { // NOTE: This performs a blocking handshake before the peer is added. // CONTRACT: Iff error is returned, peer is nil, and conn is immediately closed. func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool) (*Peer, error) { - // Filter by ip + // Filter by addr (ie. ip:port) if err := sw.FilterConnByAddr(conn.RemoteAddr()); err != nil { return nil, err } @@ -456,29 +456,52 @@ type SwitchEventDonePeer struct { //------------------------------------------------------------------ // Switches connected via arbitrary net.Conn; useful for testing -// Returns n fully connected switches. +// Returns n switches, connected according to the connect func. +// If connect==Connect2Switches, the switches will be fully connected. // initSwitch defines how the ith switch should be initialized (ie. with what reactors). -func MakeConnectedSwitches(n int, initSwitch func(int, *Switch) *Switch, connPipe func() (net.Conn, net.Conn)) []*Switch { +// NOTE: panics if any switch fails to start. +func MakeConnectedSwitches(n int, initSwitch func(int, *Switch) *Switch, connect func([]*Switch, int, int)) []*Switch { switches := make([]*Switch, n) for i := 0; i < n; i++ { switches[i] = makeSwitch(i, "testing", "123.123.123", initSwitch) } for i := 0; i < n; i++ { - switchI := switches[i] for j := i; j < n; j++ { - switchJ := switches[j] - c1, c2 := connPipe() - go switchI.AddPeerWithConnection(c1, false) // AddPeer is blocking, requires handshake. - go switchJ.AddPeerWithConnection(c2, true) + connect(switches, i, j) } } // Wait for things to happen, peers to get added... + // TODO: better time.Sleep(100 * time.Millisecond * time.Duration(n*n)) + if err := StartSwitches(switches); err != nil { + panic(err) + } + return switches } +// Will connect switches i and j via net.Pipe() +// NOTE: caller ensures i and j are within bounds +func Connect2Switches(switches []*Switch, i, j int) { + switchI := switches[i] + switchJ := switches[j] + c1, c2 := net.Pipe() + go switchI.AddPeerWithConnection(c1, false) // AddPeer is blocking, requires handshake. + go switchJ.AddPeerWithConnection(c2, true) +} + +func StartSwitches(switches []*Switch) error { + for _, s := range switches { + _, err := s.Start() // start switch and reactors + if err != nil { + return err + } + } + return nil +} + func makeSwitch(i int, network, version string, initSwitch func(int, *Switch) *Switch) *Switch { privKey := crypto.GenPrivKeyEd25519() // new switch, add reactors @@ -491,6 +514,5 @@ func makeSwitch(i int, network, version string, initSwitch func(int, *Switch) *S Version: version, }) s.SetNodePrivKey(privKey) - s.Start() // start switch and reactors return s } diff --git a/switch_test.go b/switch_test.go index f77682b66..1b2ccd743 100644 --- a/switch_test.go +++ b/switch_test.go @@ -90,7 +90,7 @@ func (tr *TestReactor) getMsgs(chID byte) []PeerMessage { // XXX: note this uses net.Pipe and not a proper TCP conn func makeSwitchPair(t testing.TB, initSwitch func(int, *Switch) *Switch) (*Switch, *Switch) { // Create two switches that will be interconnected. - switches := MakeConnectedSwitches(2, initSwitch, net.Pipe) + switches := MakeConnectedSwitches(2, initSwitch, Connect2Switches) return switches[0], switches[1] } From 855255d73eecd25097288be70f3fb208a5817d80 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Mon, 10 Oct 2016 03:22:34 -0400 Subject: [PATCH 055/309] use EventSwitch interface; less logging --- client/http_client.go | 12 ++++++++---- server/handlers.go | 22 ++++++++++++---------- types/types.go | 2 +- 3 files changed, 21 insertions(+), 15 deletions(-) diff --git a/client/http_client.go b/client/http_client.go index 63dd9a82d..816791b5c 100644 --- a/client/http_client.go +++ b/client/http_client.go @@ -119,7 +119,7 @@ func (c *ClientURI) call(method string, params map[string]interface{}, result in if err != nil { return nil, err } - log.Info(Fmt("URI request to %v (%v): %v", c.address, method, values)) + //log.Info(Fmt("URI request to %v (%v): %v", c.address, method, values)) resp, err := c.client.PostForm(c.address+"/"+method, values) if err != nil { return nil, err @@ -138,19 +138,23 @@ func unmarshalResponseBytes(responseBytes []byte, result interface{}) (interface // read response // if rpc/core/types is imported, the result will unmarshal // into the correct type + // log.Notice("response", "response", string(responseBytes)) var err error response := &rpctypes.RPCResponse{} err = json.Unmarshal(responseBytes, response) if err != nil { - return nil, err + return nil, errors.New(Fmt("Error unmarshalling rpc response: %v", err)) } errorStr := response.Error if errorStr != "" { - return nil, errors.New(errorStr) + return nil, errors.New(Fmt("Response error: %v", errorStr)) } // unmarshal the RawMessage into the result result = wire.ReadJSONPtr(result, *response.Result, &err) - return result, err + if err != nil { + return nil, errors.New(Fmt("Error unmarshalling rpc response result: %v", err)) + } + return result, nil } func argsToURLValues(args map[string]interface{}) (url.Values, error) { diff --git a/server/handlers.go b/server/handlers.go index 82fd7b358..2b2bb90ce 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -107,7 +107,7 @@ func makeJSONRPCHandler(funcMap map[string]*RPCFunc) http.HandlerFunc { var request RPCRequest err := json.Unmarshal(b, &request) if err != nil { - WriteRPCResponseHTTP(w, NewRPCResponse("", nil, err.Error())) + WriteRPCResponseHTTP(w, NewRPCResponse("", nil, fmt.Sprintf("Error unmarshalling request: %v", err.Error()))) return } if len(r.URL.Path) > 1 { @@ -125,14 +125,14 @@ func makeJSONRPCHandler(funcMap map[string]*RPCFunc) http.HandlerFunc { } args, err := jsonParamsToArgs(rpcFunc, request.Params) if err != nil { - WriteRPCResponseHTTP(w, NewRPCResponse(request.ID, nil, err.Error())) + WriteRPCResponseHTTP(w, NewRPCResponse(request.ID, nil, fmt.Sprintf("Error converting json params to arguments: %v", err.Error()))) return } returns := rpcFunc.f.Call(args) log.Info("HTTPJSONRPC", "method", request.Method, "args", args, "returns", returns) result, err := unreflectResult(returns) if err != nil { - WriteRPCResponseHTTP(w, NewRPCResponse(request.ID, result, err.Error())) + WriteRPCResponseHTTP(w, NewRPCResponse(request.ID, result, fmt.Sprintf("Error unreflecting result: %v", err.Error()))) return } WriteRPCResponseHTTP(w, NewRPCResponse(request.ID, result, "")) @@ -201,16 +201,17 @@ func makeHTTPHandler(rpcFunc *RPCFunc) func(http.ResponseWriter, *http.Request) } // All other endpoints return func(w http.ResponseWriter, r *http.Request) { + log.Debug("HTTP HANDLER", "req", r) args, err := httpParamsToArgs(rpcFunc, r) if err != nil { - WriteRPCResponseHTTP(w, NewRPCResponse("", nil, err.Error())) + WriteRPCResponseHTTP(w, NewRPCResponse("", nil, fmt.Sprintf("Error converting http params to args: %v", err.Error()))) return } returns := rpcFunc.f.Call(args) log.Info("HTTPRestRPC", "method", r.URL.Path, "args", args, "returns", returns) result, err := unreflectResult(returns) if err != nil { - WriteRPCResponseHTTP(w, NewRPCResponse("", nil, err.Error())) + WriteRPCResponseHTTP(w, NewRPCResponse("", nil, fmt.Sprintf("Error unreflecting result: %v", err.Error()))) return } WriteRPCResponseHTTP(w, NewRPCResponse("", result, "")) @@ -228,6 +229,7 @@ func httpParamsToArgs(rpcFunc *RPCFunc, r *http.Request) ([]reflect.Value, error for i, name := range argNames { ty := argTypes[i] arg := GetParam(r, name) + //log.Notice("param to arg", "ty", ty, "name", name, "arg", arg) values[i], err = _jsonStringToArg(ty, arg) if err != nil { return nil, err @@ -271,11 +273,11 @@ type wsConnection struct { pingTicker *time.Ticker funcMap map[string]*RPCFunc - evsw *events.EventSwitch + evsw events.EventSwitch } // new websocket connection wrapper -func NewWSConnection(baseConn *websocket.Conn, funcMap map[string]*RPCFunc, evsw *events.EventSwitch) *wsConnection { +func NewWSConnection(baseConn *websocket.Conn, funcMap map[string]*RPCFunc, evsw events.EventSwitch) *wsConnection { wsc := &wsConnection{ remoteAddr: baseConn.RemoteAddr().String(), baseConn: baseConn, @@ -341,7 +343,7 @@ func (wsc *wsConnection) GetRemoteAddr() string { } // Implements WSRPCConnection -func (wsc *wsConnection) GetEventSwitch() *events.EventSwitch { +func (wsc *wsConnection) GetEventSwitch() events.EventSwitch { return wsc.evsw } @@ -472,10 +474,10 @@ func (wsc *wsConnection) writeRoutine() { type WebsocketManager struct { websocket.Upgrader funcMap map[string]*RPCFunc - evsw *events.EventSwitch + evsw events.EventSwitch } -func NewWebsocketManager(funcMap map[string]*RPCFunc, evsw *events.EventSwitch) *WebsocketManager { +func NewWebsocketManager(funcMap map[string]*RPCFunc, evsw events.EventSwitch) *WebsocketManager { return &WebsocketManager{ funcMap: funcMap, evsw: evsw, diff --git a/types/types.go b/types/types.go index 5d79c4a66..ee4a63cc8 100644 --- a/types/types.go +++ b/types/types.go @@ -68,7 +68,7 @@ func NewRPCResponse(id string, res interface{}, err string) RPCResponse { // *wsConnection implements this interface. type WSRPCConnection interface { GetRemoteAddr() string - GetEventSwitch() *events.EventSwitch + GetEventSwitch() events.EventSwitch WriteRPCResponse(resp RPCResponse) TryWriteRPCResponse(resp RPCResponse) bool } From 161e36fd56c2f95ad133dd03ddb33db0363ca742 Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Fri, 28 Oct 2016 12:04:58 -0700 Subject: [PATCH 056/309] QuitService->BaseService --- client/ws_client.go | 8 ++++---- server/handlers.go | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/client/ws_client.go b/client/ws_client.go index 00e4222ad..4d975f8ec 100644 --- a/client/ws_client.go +++ b/client/ws_client.go @@ -19,7 +19,7 @@ const ( ) type WSClient struct { - QuitService + BaseService Address string // IP:PORT or /path/to/socket Endpoint string // /websocket/url/endpoint Dialer func(string, string) (net.Conn, error) @@ -39,7 +39,7 @@ func NewWSClient(remoteAddr, endpoint string) *WSClient { ResultsCh: make(chan json.RawMessage, wsResultsChannelCapacity), ErrorsCh: make(chan error, wsErrorsChannelCapacity), } - wsClient.QuitService = *NewQuitService(log, "WSClient", wsClient) + wsClient.BaseService = *NewBaseService(log, "WSClient", wsClient) return wsClient } @@ -48,7 +48,7 @@ func (wsc *WSClient) String() string { } func (wsc *WSClient) OnStart() error { - wsc.QuitService.OnStart() + wsc.BaseService.OnStart() err := wsc.dial() if err != nil { return err @@ -84,7 +84,7 @@ func (wsc *WSClient) dial() error { } func (wsc *WSClient) OnStop() { - wsc.QuitService.OnStop() + wsc.BaseService.OnStop() // ResultsCh/ErrorsCh is closed in receiveEventsRoutine. } diff --git a/server/handlers.go b/server/handlers.go index 2b2bb90ce..dbc5c6e75 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -264,7 +264,7 @@ const ( // contains listener id, underlying ws connection, // and the event switch for subscribing to events type wsConnection struct { - QuitService + BaseService remoteAddr string baseConn *websocket.Conn @@ -285,13 +285,13 @@ func NewWSConnection(baseConn *websocket.Conn, funcMap map[string]*RPCFunc, evsw funcMap: funcMap, evsw: evsw, } - wsc.QuitService = *NewQuitService(log, "wsConnection", wsc) + wsc.BaseService = *NewBaseService(log, "wsConnection", wsc) return wsc } // wsc.Start() blocks until the connection closes. func (wsc *wsConnection) OnStart() error { - wsc.QuitService.OnStart() + wsc.BaseService.OnStart() // Read subscriptions/unsubscriptions to events go wsc.readRoutine() @@ -318,7 +318,7 @@ func (wsc *wsConnection) OnStart() error { } func (wsc *wsConnection) OnStop() { - wsc.QuitService.OnStop() + wsc.BaseService.OnStop() wsc.evsw.RemoveListener(wsc.remoteAddr) wsc.readTimeout.Stop() wsc.pingTicker.Stop() From 2cee3646927182964268e63c4248db3def69ac4e Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Wed, 30 Nov 2016 22:57:21 -0500 Subject: [PATCH 057/309] addrbook: toggle strict routability --- addrbook.go | 50 +++++++++++++++++++++++++----------------------- addrbook_test.go | 14 ++++++++------ 2 files changed, 34 insertions(+), 30 deletions(-) diff --git a/addrbook.go b/addrbook.go index 0b1525646..d2e4d48e6 100644 --- a/addrbook.go +++ b/addrbook.go @@ -77,17 +77,18 @@ const ( type AddrBook struct { QuitService - mtx sync.Mutex - filePath string - rand *rand.Rand - key string - ourAddrs map[string]*NetAddress - addrLookup map[string]*knownAddress // new & old - addrNew []map[string]*knownAddress - addrOld []map[string]*knownAddress - wg sync.WaitGroup - nOld int - nNew int + mtx sync.Mutex + filePath string + routabilityStrict bool + rand *rand.Rand + key string + ourAddrs map[string]*NetAddress + addrLookup map[string]*knownAddress // new & old + addrNew []map[string]*knownAddress + addrOld []map[string]*knownAddress + wg sync.WaitGroup + nOld int + nNew int } const ( @@ -96,12 +97,13 @@ const ( ) // Use Start to begin processing asynchronous address updates. -func NewAddrBook(filePath string) *AddrBook { +func NewAddrBook(filePath string, routabilityStrict bool) *AddrBook { am := &AddrBook{ - rand: rand.New(rand.NewSource(time.Now().UnixNano())), - ourAddrs: make(map[string]*NetAddress), - addrLookup: make(map[string]*knownAddress), - filePath: filePath, + rand: rand.New(rand.NewSource(time.Now().UnixNano())), + ourAddrs: make(map[string]*NetAddress), + addrLookup: make(map[string]*knownAddress), + filePath: filePath, + routabilityStrict: routabilityStrict, } am.init() am.QuitService = *NewQuitService(log, "AddrBook", am) @@ -513,7 +515,7 @@ func (a *AddrBook) pickOldest(bucketType byte, bucketIdx int) *knownAddress { } func (a *AddrBook) addAddress(addr, src *NetAddress) { - if !addr.Routable() { + if a.routabilityStrict && !addr.Routable() { log.Warn(Fmt("Cannot add non-routable address %v", addr)) return } @@ -616,8 +618,8 @@ func (a *AddrBook) moveToOld(ka *knownAddress) { func (a *AddrBook) calcNewBucket(addr, src *NetAddress) int { data1 := []byte{} data1 = append(data1, []byte(a.key)...) - data1 = append(data1, []byte(groupKey(addr))...) - data1 = append(data1, []byte(groupKey(src))...) + data1 = append(data1, []byte(a.groupKey(addr))...) + data1 = append(data1, []byte(a.groupKey(src))...) hash1 := doubleSha256(data1) hash64 := binary.BigEndian.Uint64(hash1) hash64 %= newBucketsPerGroup @@ -625,7 +627,7 @@ func (a *AddrBook) calcNewBucket(addr, src *NetAddress) int { binary.BigEndian.PutUint64(hashbuf[:], hash64) data2 := []byte{} data2 = append(data2, []byte(a.key)...) - data2 = append(data2, groupKey(src)...) + data2 = append(data2, a.groupKey(src)...) data2 = append(data2, hashbuf[:]...) hash2 := doubleSha256(data2) @@ -645,7 +647,7 @@ func (a *AddrBook) calcOldBucket(addr *NetAddress) int { binary.BigEndian.PutUint64(hashbuf[:], hash64) data2 := []byte{} data2 = append(data2, []byte(a.key)...) - data2 = append(data2, groupKey(addr)...) + data2 = append(data2, a.groupKey(addr)...) data2 = append(data2, hashbuf[:]...) hash2 := doubleSha256(data2) @@ -656,11 +658,11 @@ func (a *AddrBook) calcOldBucket(addr *NetAddress) int { // This is the /16 for IPv6, the /32 (/36 for he.net) for IPv6, the string // "local" for a local address and the string "unroutable for an unroutable // address. -func groupKey(na *NetAddress) string { - if na.Local() { +func (a *AddrBook) groupKey(na *NetAddress) string { + if a.routabilityStrict && na.Local() { return "local" } - if !na.Routable() { + if a.routabilityStrict && !na.Routable() { return "unroutable" } diff --git a/addrbook_test.go b/addrbook_test.go index 50986452e..d5a83da88 100644 --- a/addrbook_test.go +++ b/addrbook_test.go @@ -7,6 +7,8 @@ import ( "testing" ) +const addrBookStrict = true + func createTempFileName(prefix string) string { f, err := ioutil.TempFile("", prefix) if err != nil { @@ -25,10 +27,10 @@ func TestEmpty(t *testing.T) { // t.Logf("New tempfile name: %v", fname) // Save an empty book & load it - book := NewAddrBook(fname) + book := NewAddrBook(fname, addrBookStrict) book.saveToFile(fname) - book = NewAddrBook(fname) + book = NewAddrBook(fname, addrBookStrict) book.loadFromFile(fname) if book.Size() != 0 { @@ -74,7 +76,7 @@ func TestSaveAddresses(t *testing.T) { } // Create the book & populate & save - book := NewAddrBook(fname) + book := NewAddrBook(fname, addrBookStrict) for _, addrSrc := range randAddrs { book.AddAddress(addrSrc.addr, addrSrc.src) } @@ -84,7 +86,7 @@ func TestSaveAddresses(t *testing.T) { book.saveToFile(fname) // Reload the book - book = NewAddrBook(fname) + book = NewAddrBook(fname, addrBookStrict) book.loadFromFile(fname) // Test ... @@ -128,7 +130,7 @@ func TestPromoteToOld(t *testing.T) { } // Create the book & populate & save - book := NewAddrBook(fname) + book := NewAddrBook(fname, addrBookStrict) for _, addrSrc := range randAddrs { book.AddAddress(addrSrc.addr, addrSrc.src) } @@ -145,7 +147,7 @@ func TestPromoteToOld(t *testing.T) { book.saveToFile(fname) // Reload the book - book = NewAddrBook(fname) + book = NewAddrBook(fname, addrBookStrict) book.loadFromFile(fname) // Test ... From eab2baa363de01b052b88c559e803776cd2c7dd6 Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Sun, 4 Dec 2016 18:20:18 -0800 Subject: [PATCH 058/309] use go-flowrate instead of flowcontrol --- connection.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/connection.go b/connection.go index 6c8ccd435..4428e0da7 100644 --- a/connection.go +++ b/connection.go @@ -10,9 +10,9 @@ import ( "sync/atomic" "time" - flow "github.com/tendermint/flowcontrol" . "github.com/tendermint/go-common" cfg "github.com/tendermint/go-config" + flow "github.com/tendermint/go-flowrate/flowrate" "github.com/tendermint/go-wire" //"github.com/tendermint/log15" ) From 34a806578ac0dd578c5595365a9c1478e0a689a0 Mon Sep 17 00:00:00 2001 From: Matt Bell Date: Mon, 2 Jan 2017 09:50:20 -0800 Subject: [PATCH 059/309] Handle hex strings and quoted strings in HTTP params Use 0x-prefixed hex strings in client server: Decode hex string args Encode all string args as 0x without trying to encode as JSON Added tests for special string arguments Fix server handling quoted string args Added string arg handling test cases to bash test script --- client/http_client.go | 19 ++++++++++++++++++- rpc_test.go | 36 ++++++++++++++++++++++++++++++++++++ server/handlers.go | 31 ++++++++++++++++++++++++++++++- test/test.sh | 35 +++++++++++++++++++++++++++-------- 4 files changed, 111 insertions(+), 10 deletions(-) mode change 100644 => 100755 test/test.sh diff --git a/client/http_client.go b/client/http_client.go index 816791b5c..54fbd1c2b 100644 --- a/client/http_client.go +++ b/client/http_client.go @@ -4,10 +4,12 @@ import ( "bytes" "encoding/json" "errors" + "fmt" "io/ioutil" "net" "net/http" "net/url" + "reflect" "strings" . "github.com/tendermint/go-common" @@ -119,7 +121,7 @@ func (c *ClientURI) call(method string, params map[string]interface{}, result in if err != nil { return nil, err } - //log.Info(Fmt("URI request to %v (%v): %v", c.address, method, values)) + log.Info(Fmt("URI request to %v (%v): %v", c.address, method, values)) resp, err := c.client.PostForm(c.address+"/"+method, values) if err != nil { return nil, err @@ -176,6 +178,21 @@ func argsToJson(args map[string]interface{}) error { var n int var err error for k, v := range args { + // Convert strings to "0x"-prefixed hex + str, isString := reflect.ValueOf(v).Interface().(string) + if isString { + args[k] = fmt.Sprintf("0x%X", str) + continue + } + + // Convert byte slices to "0x"-prefixed hex + byteSlice, isByteSlice := reflect.ValueOf(v).Interface().([]byte) + if isByteSlice { + args[k] = fmt.Sprintf("0x%X", byteSlice) + continue + } + + // Pass everything else to go-wire buf := new(bytes.Buffer) wire.WriteJSON(v, buf, &n, &err) if err != nil { diff --git a/rpc_test.go b/rpc_test.go index 0c6e1dbdb..1fcda0e5e 100644 --- a/rpc_test.go +++ b/rpc_test.go @@ -164,3 +164,39 @@ func TestWS_UNIX(t *testing.T) { } testWS(t, cl) } + +func TestHexStringArg(t *testing.T) { + cl := rpcclient.NewClientURI(tcpAddr) + // should NOT be handled as hex + val := "0xabc" + params := map[string]interface{}{ + "arg": val, + } + var result Result + _, err := cl.Call("status", params, &result) + if err != nil { + t.Fatal(err) + } + got := result.(*ResultStatus).Value + if got != val { + t.Fatalf("Got: %v .... Expected: %v \n", got, val) + } +} + +func TestQuotedStringArg(t *testing.T) { + cl := rpcclient.NewClientURI(tcpAddr) + // should NOT be unquoted + val := "\"abc\"" + params := map[string]interface{}{ + "arg": val, + } + var result Result + _, err := cl.Call("status", params, &result) + if err != nil { + t.Fatal(err) + } + got := result.(*ResultStatus).Value + if got != val { + t.Fatalf("Got: %v .... Expected: %v \n", got, val) + } +} diff --git a/server/handlers.go b/server/handlers.go index dbc5c6e75..f5730213b 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -2,6 +2,7 @@ package rpcserver import ( "bytes" + "encoding/hex" "encoding/json" "errors" "fmt" @@ -229,7 +230,35 @@ func httpParamsToArgs(rpcFunc *RPCFunc, r *http.Request) ([]reflect.Value, error for i, name := range argNames { ty := argTypes[i] arg := GetParam(r, name) - //log.Notice("param to arg", "ty", ty, "name", name, "arg", arg) + // log.Notice("param to arg", "ty", ty, "name", name, "arg", arg) + + // Handle quoted strings + if strings.HasPrefix(arg, "\"") && strings.HasSuffix(arg, "\"") { + data := arg[1 : len(arg)-1] + if ty.Kind() == reflect.String { + values[i] = reflect.ValueOf(string(data)) + } else { + values[i] = reflect.ValueOf(data) + } + continue + } + + // Handle hex strings + if strings.HasPrefix(strings.ToLower(arg), "0x") { + var value []byte + value, err = hex.DecodeString(arg[2:]) + if err != nil { + return nil, err + } + if ty.Kind() == reflect.String { + values[i] = reflect.ValueOf(string(value)) + } else { + values[i] = reflect.ValueOf(value) + } + continue + } + + // Pass values to go-wire values[i], err = _jsonStringToArg(ty, arg) if err != nil { return nil, err diff --git a/test/test.sh b/test/test.sh old mode 100644 new mode 100755 index 3d1f599dd..a5f8abd44 --- a/test/test.sh +++ b/test/test.sh @@ -6,18 +6,37 @@ go build -o server main.go PID=$! sleep 2 - +# simple JSONRPC request R1=`curl -s 'http://localhost:8008/hello_world?name="my_world"&num=5'` - - R2=`curl -s --data @data.json http://localhost:8008` - -kill -9 $PID - if [[ "$R1" != "$R2" ]]; then echo "responses are not identical:" echo "R1: $R1" echo "R2: $R2" - exit 1 +else + echo "Success" fi -echo "Success" + +# request with 0x-prefixed hex string arg +R1=`curl -s 'http://localhost:8008/hello_world?name=0x41424344&num=123'` +R2='{"jsonrpc":"2.0","id":"","result":{"Result":"hi ABCD 123"},"error":""}' +if [[ "$R1" != "$R2" ]]; then + echo "responses are not identical:" + echo "R1: $R1" + echo "R2: $R2" +else + echo "Success" +fi + +# request with unquoted string arg +R1=`curl -s 'http://localhost:8008/hello_world?name=abcd&num=123'` +R2="{\"jsonrpc\":\"2.0\",\"id\":\"\",\"result\":null,\"error\":\"Error converting http params to args: invalid character 'a' looking for beginning of value\"}" +if [[ "$R1" != "$R2" ]]; then + echo "responses are not identical:" + echo "R1: $R1" + echo "R2: $R2" +else + echo "Success" +fi + +kill -9 $PID From af1212897cfb1b2c43c02508e85babcf88fb5343 Mon Sep 17 00:00:00 2001 From: Matt Bell Date: Sat, 7 Jan 2017 14:00:27 -0800 Subject: [PATCH 060/309] Exit early in bash tests --- test/test.sh | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test/test.sh b/test/test.sh index a5f8abd44..2db809948 100755 --- a/test/test.sh +++ b/test/test.sh @@ -13,6 +13,7 @@ if [[ "$R1" != "$R2" ]]; then echo "responses are not identical:" echo "R1: $R1" echo "R2: $R2" + exit 1 else echo "Success" fi @@ -24,6 +25,7 @@ if [[ "$R1" != "$R2" ]]; then echo "responses are not identical:" echo "R1: $R1" echo "R2: $R2" + exit 1 else echo "Success" fi @@ -35,6 +37,7 @@ if [[ "$R1" != "$R2" ]]; then echo "responses are not identical:" echo "R1: $R1" echo "R2: $R2" + exit 1 else echo "Success" fi From 86506cd4f83f67c307e5f32ad8ca39a337158fe8 Mon Sep 17 00:00:00 2001 From: Matt Bell Date: Sat, 7 Jan 2017 14:21:10 -0800 Subject: [PATCH 061/309] Handle quoted and hex string type HTTP args for both 'string' and '[]byte' type function args --- client/http_client.go | 9 +----- server/handlers.go | 66 ++++++++++++++++++++++++++++--------------- 2 files changed, 44 insertions(+), 31 deletions(-) diff --git a/client/http_client.go b/client/http_client.go index 54fbd1c2b..57da5d6ec 100644 --- a/client/http_client.go +++ b/client/http_client.go @@ -121,7 +121,7 @@ func (c *ClientURI) call(method string, params map[string]interface{}, result in if err != nil { return nil, err } - log.Info(Fmt("URI request to %v (%v): %v", c.address, method, values)) + // log.Info(Fmt("URI request to %v (%v): %v", c.address, method, values)) resp, err := c.client.PostForm(c.address+"/"+method, values) if err != nil { return nil, err @@ -178,13 +178,6 @@ func argsToJson(args map[string]interface{}) error { var n int var err error for k, v := range args { - // Convert strings to "0x"-prefixed hex - str, isString := reflect.ValueOf(v).Interface().(string) - if isString { - args[k] = fmt.Sprintf("0x%X", str) - continue - } - // Convert byte slices to "0x"-prefixed hex byteSlice, isByteSlice := reflect.ValueOf(v).Interface().([]byte) if isByteSlice { diff --git a/server/handlers.go b/server/handlers.go index f5730213b..7a4ec1a45 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -225,36 +225,18 @@ func httpParamsToArgs(rpcFunc *RPCFunc, r *http.Request) ([]reflect.Value, error argTypes := rpcFunc.args argNames := rpcFunc.argNames - var err error values := make([]reflect.Value, len(argNames)) for i, name := range argNames { ty := argTypes[i] arg := GetParam(r, name) // log.Notice("param to arg", "ty", ty, "name", name, "arg", arg) - // Handle quoted strings - if strings.HasPrefix(arg, "\"") && strings.HasSuffix(arg, "\"") { - data := arg[1 : len(arg)-1] - if ty.Kind() == reflect.String { - values[i] = reflect.ValueOf(string(data)) - } else { - values[i] = reflect.ValueOf(data) - } - continue + v, err, ok := nonJsonToArg(ty, arg) + if err != nil { + return nil, err } - - // Handle hex strings - if strings.HasPrefix(strings.ToLower(arg), "0x") { - var value []byte - value, err = hex.DecodeString(arg[2:]) - if err != nil { - return nil, err - } - if ty.Kind() == reflect.String { - values[i] = reflect.ValueOf(string(value)) - } else { - values[i] = reflect.ValueOf(value) - } + if ok { + values[i] = v continue } @@ -278,6 +260,44 @@ func _jsonStringToArg(ty reflect.Type, arg string) (reflect.Value, error) { return v, nil } +func nonJsonToArg(ty reflect.Type, arg string) (reflect.Value, error, bool) { + isQuotedString := strings.HasPrefix(arg, `"`) && strings.HasSuffix(arg, `"`) + isHexString := strings.HasPrefix(strings.ToLower(arg), "0x") + expectingString := ty.Kind() == reflect.String + expectingByteSlice := ty.Kind() == reflect.Slice && ty.Elem().Kind() == reflect.Uint8 + + if isHexString { + if !expectingString && !expectingByteSlice { + err := fmt.Errorf("Got a hex string arg, but expected '%s'", + ty.Kind().String()) + return reflect.ValueOf(nil), err, false + } + + var value []byte + value, err := hex.DecodeString(arg[2:]) + if err != nil { + return reflect.ValueOf(nil), err, false + } + if ty.Kind() == reflect.String { + return reflect.ValueOf(string(value)), nil, true + } + return reflect.ValueOf([]byte(value)), nil, true + } + + if isQuotedString && expectingByteSlice { + var err error + v := reflect.New(reflect.TypeOf("")) + wire.ReadJSONPtr(v.Interface(), []byte(arg), &err) + if err != nil { + return reflect.ValueOf(nil), err, false + } + v = v.Elem() + return reflect.ValueOf([]byte(v.String())), nil, true + } + + return reflect.ValueOf(nil), nil, false +} + // rpc.http //----------------------------------------------------------------------------- // rpc.websocket From 4d7aa62a10068450f977ebe786ea1412bf633658 Mon Sep 17 00:00:00 2001 From: Matt Bell Date: Sat, 7 Jan 2017 14:21:49 -0800 Subject: [PATCH 062/309] Added test for unexpected hex string type HTTP args --- test/test.sh | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/test/test.sh b/test/test.sh index 2db809948..dc22ad2f3 100755 --- a/test/test.sh +++ b/test/test.sh @@ -6,7 +6,7 @@ go build -o server main.go PID=$! sleep 2 -# simple JSONRPC request +# simple request R1=`curl -s 'http://localhost:8008/hello_world?name="my_world"&num=5'` R2=`curl -s --data @data.json http://localhost:8008` if [[ "$R1" != "$R2" ]]; then @@ -42,4 +42,16 @@ else echo "Success" fi -kill -9 $PID +# request with string type when expecting number arg +R1=`curl -s 'http://localhost:8008/hello_world?name="abcd"&num=0xabcd'` +R2="{\"jsonrpc\":\"2.0\",\"id\":\"\",\"result\":null,\"error\":\"Error converting http params to args: Got a 'hex string' arg, but expected 'int'\"}" +if [[ "$R1" != "$R2" ]]; then + echo "responses are not identical:" + echo "R1: $R1" + echo "R2: $R2" + exit 1 +else + echo "Success" +fi + +kill -9 $PID || exit 0 From 0eb278ad3b6ca0a1fcb7f012c02360bfb77da8ee Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Thu, 12 Jan 2017 00:13:20 -0500 Subject: [PATCH 063/309] version bump 0.6.0 --- version.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/version.go b/version.go index edf8d40da..33eb7fe51 100644 --- a/version.go +++ b/version.go @@ -1,7 +1,7 @@ package rpc const Maj = "0" -const Min = "5" // refactored out of tendermint/tendermint; RPCResponse.Result is RawJSON -const Fix = "1" // support tcp:// or unix:// prefixes +const Min = "6" // 0x-prefixed string args handled as hex +const Fix = "0" // const Version = Maj + "." + Min + "." + Fix From 94fed25975c31e5d405369f0e3558da3cff85c2b Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Thu, 12 Jan 2017 10:22:23 -0500 Subject: [PATCH 064/309] fix test --- test/test.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/test.sh b/test/test.sh index dc22ad2f3..c38059016 100755 --- a/test/test.sh +++ b/test/test.sh @@ -44,7 +44,7 @@ fi # request with string type when expecting number arg R1=`curl -s 'http://localhost:8008/hello_world?name="abcd"&num=0xabcd'` -R2="{\"jsonrpc\":\"2.0\",\"id\":\"\",\"result\":null,\"error\":\"Error converting http params to args: Got a 'hex string' arg, but expected 'int'\"}" +R2="{\"jsonrpc\":\"2.0\",\"id\":\"\",\"result\":null,\"error\":\"Error converting http params to args: Got a hex string arg, but expected 'int'\"}" if [[ "$R1" != "$R2" ]]; then echo "responses are not identical:" echo "R1: $R1" From bd353e004abd50d5e2a63b2ffc2ed12c0a78adf9 Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Fri, 28 Oct 2016 12:03:21 -0700 Subject: [PATCH 065/309] QuitService->BaseService --- addrbook.go | 8 ++++---- switch.go | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/addrbook.go b/addrbook.go index d2e4d48e6..2bbae64f5 100644 --- a/addrbook.go +++ b/addrbook.go @@ -75,7 +75,7 @@ const ( /* AddrBook - concurrency safe peer address manager */ type AddrBook struct { - QuitService + BaseService mtx sync.Mutex filePath string @@ -106,7 +106,7 @@ func NewAddrBook(filePath string, routabilityStrict bool) *AddrBook { routabilityStrict: routabilityStrict, } am.init() - am.QuitService = *NewQuitService(log, "AddrBook", am) + am.BaseService = *NewBaseService(log, "AddrBook", am) return am } @@ -126,7 +126,7 @@ func (a *AddrBook) init() { } func (a *AddrBook) OnStart() error { - a.QuitService.OnStart() + a.BaseService.OnStart() a.loadFromFile(a.filePath) a.wg.Add(1) go a.saveRoutine() @@ -134,7 +134,7 @@ func (a *AddrBook) OnStart() error { } func (a *AddrBook) OnStop() { - a.QuitService.OnStop() + a.BaseService.OnStop() a.wg.Wait() } diff --git a/switch.go b/switch.go index 61d269491..bbb73805e 100644 --- a/switch.go +++ b/switch.go @@ -26,13 +26,13 @@ type Reactor interface { //-------------------------------------- type BaseReactor struct { - QuitService // Provides Start, Stop, .Quit + BaseService // Provides Start, Stop, .Quit Switch *Switch } func NewBaseReactor(log log15.Logger, name string, impl Reactor) *BaseReactor { return &BaseReactor{ - QuitService: *NewQuitService(log, name, impl), + BaseService: *NewBaseService(log, name, impl), Switch: nil, } } From 58e42397f839d35a95dc0ca6d39367f47ae3206f Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Wed, 23 Nov 2016 18:16:40 -0500 Subject: [PATCH 066/309] close conns on filter; fix order in MakeConnectedSwitch --- switch.go | 14 +++++++------- types.go | 2 +- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/switch.go b/switch.go index bbb73805e..d029854e7 100644 --- a/switch.go +++ b/switch.go @@ -195,8 +195,10 @@ func (sw *Switch) OnStop() { // NOTE: This performs a blocking handshake before the peer is added. // CONTRACT: Iff error is returned, peer is nil, and conn is immediately closed. func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool) (*Peer, error) { + // Filter by addr (ie. ip:port) if err := sw.FilterConnByAddr(conn.RemoteAddr()); err != nil { + conn.Close() return nil, err } @@ -217,6 +219,7 @@ func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool) (*Peer, er // Filter by p2p-key if err := sw.FilterConnByPubKey(sconn.(*SecretConnection).RemotePubKey()); err != nil { + sconn.Close() return nil, err } @@ -466,18 +469,15 @@ func MakeConnectedSwitches(n int, initSwitch func(int, *Switch) *Switch, connect switches[i] = makeSwitch(i, "testing", "123.123.123", initSwitch) } + if err := StartSwitches(switches); err != nil { + panic(err) + } + for i := 0; i < n; i++ { for j := i; j < n; j++ { connect(switches, i, j) } } - // Wait for things to happen, peers to get added... - // TODO: better - time.Sleep(100 * time.Millisecond * time.Duration(n*n)) - - if err := StartSwitches(switches); err != nil { - panic(err) - } return switches } diff --git a/types.go b/types.go index 0db2c957b..4f3e4c1d8 100644 --- a/types.go +++ b/types.go @@ -21,7 +21,7 @@ type NodeInfo struct { Other []string `json:"other"` // other application specific data } -// CONTRACT: two nodes are compactible if the major/minor versions match and network match +// CONTRACT: two nodes are compatible if the major/minor versions match and network match func (info *NodeInfo) CompatibleWith(other *NodeInfo) error { iMajor, iMinor, _, iErr := splitVersion(info.Version) oMajor, oMinor, _, oErr := splitVersion(other.Version) From 2b750ea49f39c0ac113fd60cee52c7f150a6da60 Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Tue, 6 Dec 2016 01:13:03 -0800 Subject: [PATCH 067/309] Make Connect2Switches blocking --- switch.go | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/switch.go b/switch.go index d029854e7..f39ed092e 100644 --- a/switch.go +++ b/switch.go @@ -483,13 +483,23 @@ func MakeConnectedSwitches(n int, initSwitch func(int, *Switch) *Switch, connect } // Will connect switches i and j via net.Pipe() +// Blocks until a conection is established. // NOTE: caller ensures i and j are within bounds func Connect2Switches(switches []*Switch, i, j int) { switchI := switches[i] switchJ := switches[j] c1, c2 := net.Pipe() - go switchI.AddPeerWithConnection(c1, false) // AddPeer is blocking, requires handshake. - go switchJ.AddPeerWithConnection(c2, true) + doneCh := make(chan struct{}) + go func() { + switchI.AddPeerWithConnection(c1, false) // AddPeer is blocking, requires handshake. + doneCh <- struct{}{} + }() + go func() { + switchJ.AddPeerWithConnection(c2, true) + doneCh <- struct{}{} + }() + <-doneCh + <-doneCh } func StartSwitches(switches []*Switch) error { From e47722ecb2999baaf7a77131a421b8a3788a2267 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Mon, 19 Dec 2016 18:24:51 -0500 Subject: [PATCH 068/309] Connect2Switches: panic on err --- switch.go | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/switch.go b/switch.go index f39ed092e..7fabe21a4 100644 --- a/switch.go +++ b/switch.go @@ -491,11 +491,17 @@ func Connect2Switches(switches []*Switch, i, j int) { c1, c2 := net.Pipe() doneCh := make(chan struct{}) go func() { - switchI.AddPeerWithConnection(c1, false) // AddPeer is blocking, requires handshake. + _, err := switchI.AddPeerWithConnection(c1, false) // AddPeer is blocking, requires handshake. + if err != nil { + panic(err) + } doneCh <- struct{}{} }() go func() { - switchJ.AddPeerWithConnection(c2, true) + _, err := switchJ.AddPeerWithConnection(c2, true) + if err != nil { + panic(err) + } doneCh <- struct{}{} }() <-doneCh From 67c9086b7458eb45b1970483decd01cd744c477a Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Thu, 12 Jan 2017 21:09:24 -0500 Subject: [PATCH 069/309] optional panic on AddPeer err --- switch.go | 6 ++++-- version.go | 2 +- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/switch.go b/switch.go index 7fabe21a4..841c44f86 100644 --- a/switch.go +++ b/switch.go @@ -482,6 +482,8 @@ func MakeConnectedSwitches(n int, initSwitch func(int, *Switch) *Switch, connect return switches } +var PanicOnAddPeerErr = false + // Will connect switches i and j via net.Pipe() // Blocks until a conection is established. // NOTE: caller ensures i and j are within bounds @@ -492,14 +494,14 @@ func Connect2Switches(switches []*Switch, i, j int) { doneCh := make(chan struct{}) go func() { _, err := switchI.AddPeerWithConnection(c1, false) // AddPeer is blocking, requires handshake. - if err != nil { + if PanicOnAddPeerErr && err != nil { panic(err) } doneCh <- struct{}{} }() go func() { _, err := switchJ.AddPeerWithConnection(c2, true) - if err != nil { + if PanicOnAddPeerErr && err != nil { panic(err) } doneCh <- struct{}{} diff --git a/version.go b/version.go index 8608f2757..af98bef33 100644 --- a/version.go +++ b/version.go @@ -1,3 +1,3 @@ package p2p -const Version = "0.3.4" // filter by addr or pubkey +const Version = "0.3.5" // minor fixes From 08f2b5bc84f6c7b8151bd19a1d90da98207ea805 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Thu, 12 Jan 2017 21:46:50 -0500 Subject: [PATCH 070/309] get deps for testing --- Makefile | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 4cc7c1594..e73849878 100644 --- a/Makefile +++ b/Makefile @@ -2,10 +2,10 @@ all: test -test: +test: get_deps go test --race github.com/tendermint/go-rpc/... cd ./test && bash test.sh get_deps: - go get -t -d github.com/tendermint/go-rpc/... + go get -t -u github.com/tendermint/go-rpc/... From ac443fa61f30bbc65d7abfe71e897caaa9338bbc Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Thu, 12 Jan 2017 21:59:02 -0500 Subject: [PATCH 071/309] run tests from bash script --- Makefile | 6 ++---- circle.yml | 4 ---- test/test.sh | 12 ++++++++++++ 3 files changed, 14 insertions(+), 8 deletions(-) diff --git a/Makefile b/Makefile index e73849878..3b005ea36 100644 --- a/Makefile +++ b/Makefile @@ -2,10 +2,8 @@ all: test -test: get_deps - go test --race github.com/tendermint/go-rpc/... - cd ./test && bash test.sh - +test: + bash ./test/test.sh get_deps: go get -t -u github.com/tendermint/go-rpc/... diff --git a/circle.yml b/circle.yml index f022d5a6b..1b3c8c609 100644 --- a/circle.yml +++ b/circle.yml @@ -14,10 +14,6 @@ checkout: # - git submodule sync # - git submodule update --init # use submodules -dependencies: - override: - - "cd $REPO && make get_deps" - test: override: - "cd $REPO && make test" diff --git a/test/test.sh b/test/test.sh index c38059016..f5e740241 100755 --- a/test/test.sh +++ b/test/test.sh @@ -1,4 +1,16 @@ #! /bin/bash + +cd $GOPATH/src/github.com/tendermint/go-rpc + +# get deps +go get -u -t ./... + +# go tests +go test --race github.com/tendermint/go-rpc/... + + +# integration tests +cd test set -e go build -o server main.go From 6177eb8398ebd4613fbecb71fd96d7c7d97303ec Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Thu, 12 Jan 2017 22:01:20 -0500 Subject: [PATCH 072/309] love you circley --- circle.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/circle.yml b/circle.yml index 1b3c8c609..99af678c6 100644 --- a/circle.yml +++ b/circle.yml @@ -14,6 +14,10 @@ checkout: # - git submodule sync # - git submodule update --init # use submodules +dependencies: + override: + - "cd $REPO" + test: override: - "cd $REPO && make test" From 26275ba66c54486fdc28bf75c908282b05343ee1 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Thu, 2 Mar 2017 22:00:50 -0500 Subject: [PATCH 073/309] dial seeds error handling --- .gitignore | 16 ++++++++++++++++ addrbook_test.go | 15 +++++++++------ listener.go | 6 +++++- netaddress.go | 14 +++++++++----- pex_reactor.go | 8 +++++++- switch.go | 46 ++++++++++++++++++++++++++++++++++++++++++---- switch_test.go | 10 ++++++++++ 7 files changed, 98 insertions(+), 17 deletions(-) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 000000000..c4694b3e1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ +*.swp +*.swo +.bak +*.bak +.DS_Store +build/* +rpc/test/.tendermint +.debora +.tendermint +remote_dump +.revision +vendor +.vagrant +test/p2p/data/ +test/logs +.glide diff --git a/addrbook_test.go b/addrbook_test.go index d5a83da88..5eb7c0b6a 100644 --- a/addrbook_test.go +++ b/addrbook_test.go @@ -5,6 +5,8 @@ import ( "io/ioutil" "math/rand" "testing" + + "github.com/stretchr/testify/assert" ) const addrBookStrict = true @@ -38,7 +40,7 @@ func TestEmpty(t *testing.T) { } } -func randIPv4Address() *NetAddress { +func randIPv4Address(t *testing.T) *NetAddress { for { ip := fmt.Sprintf("%v.%v.%v.%v", rand.Intn(254)+1, @@ -47,7 +49,8 @@ func randIPv4Address() *NetAddress { rand.Intn(255), ) port := rand.Intn(65535-1) + 1 - addr := NewNetAddressString(fmt.Sprintf("%v:%v", ip, port)) + addr, err := NewNetAddressString(fmt.Sprintf("%v:%v", ip, port)) + assert.Nil(t, err, "error generating rand network address") if addr.Routable() { return addr } @@ -64,8 +67,8 @@ func TestSaveAddresses(t *testing.T) { src *NetAddress }{} for i := 0; i < 100; i++ { - addr := randIPv4Address() - src := randIPv4Address() + addr := randIPv4Address(t) + src := randIPv4Address(t) randAddrs = append(randAddrs, struct { addr *NetAddress src *NetAddress @@ -118,8 +121,8 @@ func TestPromoteToOld(t *testing.T) { src *NetAddress }{} for i := 0; i < 100; i++ { - addr := randIPv4Address() - src := randIPv4Address() + addr := randIPv4Address(t) + src := randIPv4Address(t) randAddrs = append(randAddrs, struct { addr *NetAddress src *NetAddress diff --git a/listener.go b/listener.go index 1d7fb9569..962c2b14c 100644 --- a/listener.go +++ b/listener.go @@ -70,7 +70,11 @@ func NewDefaultListener(protocol string, lAddr string, skipUPNP bool) Listener { log.Info("Local listener", "ip", listenerIP, "port", listenerPort) // Determine internal address... - var intAddr *NetAddress = NewNetAddressString(lAddr) + var intAddr *NetAddress + intAddr, err = NewNetAddressString(lAddr) + if err != nil { + PanicCrisis(err) + } // Determine external address... var extAddr *NetAddress diff --git a/netaddress.go b/netaddress.go index 34dc5cafb..331dc44d9 100644 --- a/netaddress.go +++ b/netaddress.go @@ -34,27 +34,31 @@ func NewNetAddress(addr net.Addr) *NetAddress { } // Also resolves the host if host is not an IP. -func NewNetAddressString(addr string) *NetAddress { +func NewNetAddressString(addr string) (*NetAddress, error) { + host, portStr, err := net.SplitHostPort(addr) if err != nil { - PanicSanity(err) + return nil, err } + ip := net.ParseIP(host) if ip == nil { if len(host) > 0 { ips, err := net.LookupIP(host) if err != nil { - PanicSanity(err) + return nil, err } ip = ips[0] } } + port, err := strconv.ParseUint(portStr, 10, 16) if err != nil { - PanicSanity(err) + return nil, err } + na := NewNetAddressIPPort(ip, uint16(port)) - return na + return na, nil } func NewNetAddressIPPort(ip net.IP, port uint16) *NetAddress { diff --git a/pex_reactor.go b/pex_reactor.go index d7ccc7613..536da3a0a 100644 --- a/pex_reactor.go +++ b/pex_reactor.go @@ -64,7 +64,12 @@ func (pexR *PEXReactor) GetChannels() []*ChannelDescriptor { // Implements Reactor func (pexR *PEXReactor) AddPeer(peer *Peer) { // Add the peer to the address book - netAddr := NewNetAddressString(peer.ListenAddr) + netAddr, err := NewNetAddressString(peer.ListenAddr) + if err != nil { + log.Warn("Error decoding message", "error", err) + return + } + if peer.IsOutbound() { if pexR.book.NeedMoreAddrs() { pexR.RequestPEX(peer) @@ -74,6 +79,7 @@ func (pexR *PEXReactor) AddPeer(peer *Peer) { // (For outbound peers, the address is already in the books) pexR.book.AddAddress(netAddr, netAddr) } + return } // Implements Reactor diff --git a/switch.go b/switch.go index 841c44f86..9ee933640 100644 --- a/switch.go +++ b/switch.go @@ -296,20 +296,58 @@ func (sw *Switch) startInitPeer(peer *Peer) { sw.addPeerToReactors(peer) // run AddPeer on each reactor } +//error type for seed errors +type SeedError struct { + seed string + err error +} + +type SeedErrors []SeedError + +func (se SeedErrors) Error() string { + var str string + for _, e := range se { + str += ("seed: " + e.seed + " error: " + e.err.Error() + "; ") + } + return str +} + // Dial a list of seeds in random order -// Spawns a go routine for each dial -func (sw *Switch) DialSeeds(seeds []string) { +func (sw *Switch) DialSeeds(seeds []string) error { + + ch := make(chan SeedError) //channel for collecting errors + passing := 0 //number of passing seeds + // permute the list, dial them in random order. perm := rand.Perm(len(seeds)) for i := 0; i < len(perm); i++ { + go func(i int) { time.Sleep(time.Duration(rand.Int63n(3000)) * time.Millisecond) j := perm[i] - addr := NewNetAddressString(seeds[j]) - sw.dialSeed(addr) + addr, err := NewNetAddressString(seeds[j]) + + if err != nil { + ch <- SeedError{seeds[j], err} + } else { + sw.dialSeed(addr) + passing++ + } }(i) } + + //collect any errors from the channel + var seedErrs SeedErrors + for { + seedErr := <-ch + seedErrs = append(seedErrs, seedErr) + if len(seedErrs)+passing == len(perm) { + break + } + } + + return seedErrs } func (sw *Switch) dialSeed(addr *NetAddress) { diff --git a/switch_test.go b/switch_test.go index 1b2ccd743..85a1e080e 100644 --- a/switch_test.go +++ b/switch_test.go @@ -8,6 +8,8 @@ import ( "testing" "time" + "github.com/stretchr/testify/assert" + . "github.com/tendermint/go-common" cfg "github.com/tendermint/go-config" "github.com/tendermint/go-crypto" @@ -119,6 +121,14 @@ func TestSwitches(t *testing.T) { t.Errorf("Expected exactly 1 peer in s2, got %v", s2.Peers().Size()) } + //Test DialSeeds + err := s1.DialSeeds([]string{s1.NodeInfo().Network}) //"0.0.0.0:46658"}) + assert.Nil(t, err, "expected successful dial seeds") + + //Test Bad Dial Seeds + err = s1.DialSeeds([]string{"0.0.0:46658"}) + assert.NotNil(t, err, "expected unsuccessful dial seeds") + // Lets send some messages ch0Msg := "channel zero" ch1Msg := "channel foo" From 0e7baf027bec8de118b0ac52f114d1a393e3d29e Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 3 Mar 2017 16:08:19 -0500 Subject: [PATCH 074/309] some dial seeds fixes --- netaddress.go | 17 +++++++++++++++-- switch.go | 48 +++++++----------------------------------------- switch_test.go | 10 ---------- 3 files changed, 22 insertions(+), 53 deletions(-) diff --git a/netaddress.go b/netaddress.go index 331dc44d9..90fcf6a43 100644 --- a/netaddress.go +++ b/netaddress.go @@ -5,11 +5,12 @@ package p2p import ( + "errors" "net" "strconv" "time" - . "github.com/tendermint/go-common" + cmn "github.com/tendermint/go-common" ) type NetAddress struct { @@ -61,6 +62,18 @@ func NewNetAddressString(addr string) (*NetAddress, error) { return na, nil } +func NewNetAddressStrings(addrs []string) ([]*NetAddress, error) { + netAddrs := make([]*NetAddress, len(addrs)) + for i, addr := range addrs { + netAddr, err := NewNetAddressString(addr) + if err != nil { + return nil, errors.New(cmn.Fmt("Error in address %s: %v", addr, err)) + } + netAddrs[i] = netAddr + } + return netAddrs, nil +} + func NewNetAddressIPPort(ip net.IP, port uint16) *NetAddress { na := &NetAddress{ IP: ip, @@ -85,7 +98,7 @@ func (na *NetAddress) Less(other interface{}) bool { if o, ok := other.(*NetAddress); ok { return na.String() < o.String() } else { - PanicSanity("Cannot compare unequal types") + cmn.PanicSanity("Cannot compare unequal types") return false } } diff --git a/switch.go b/switch.go index 9ee933640..2f7177bf0 100644 --- a/switch.go +++ b/switch.go @@ -296,58 +296,24 @@ func (sw *Switch) startInitPeer(peer *Peer) { sw.addPeerToReactors(peer) // run AddPeer on each reactor } -//error type for seed errors -type SeedError struct { - seed string - err error -} - -type SeedErrors []SeedError - -func (se SeedErrors) Error() string { - var str string - for _, e := range se { - str += ("seed: " + e.seed + " error: " + e.err.Error() + "; ") - } - return str -} - -// Dial a list of seeds in random order +// Dial a list of seeds asynchronously in random order func (sw *Switch) DialSeeds(seeds []string) error { - ch := make(chan SeedError) //channel for collecting errors - passing := 0 //number of passing seeds + netAddrs, err := NewNetAddressStrings(seeds) + if err != nil { + return err + } // permute the list, dial them in random order. perm := rand.Perm(len(seeds)) for i := 0; i < len(perm); i++ { - go func(i int) { time.Sleep(time.Duration(rand.Int63n(3000)) * time.Millisecond) j := perm[i] - - addr, err := NewNetAddressString(seeds[j]) - - if err != nil { - ch <- SeedError{seeds[j], err} - } else { - sw.dialSeed(addr) - passing++ - } + sw.dialSeed(netAddrs[j]) }(i) } - - //collect any errors from the channel - var seedErrs SeedErrors - for { - seedErr := <-ch - seedErrs = append(seedErrs, seedErr) - if len(seedErrs)+passing == len(perm) { - break - } - } - - return seedErrs + return nil } func (sw *Switch) dialSeed(addr *NetAddress) { diff --git a/switch_test.go b/switch_test.go index 85a1e080e..1b2ccd743 100644 --- a/switch_test.go +++ b/switch_test.go @@ -8,8 +8,6 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" - . "github.com/tendermint/go-common" cfg "github.com/tendermint/go-config" "github.com/tendermint/go-crypto" @@ -121,14 +119,6 @@ func TestSwitches(t *testing.T) { t.Errorf("Expected exactly 1 peer in s2, got %v", s2.Peers().Size()) } - //Test DialSeeds - err := s1.DialSeeds([]string{s1.NodeInfo().Network}) //"0.0.0.0:46658"}) - assert.Nil(t, err, "expected successful dial seeds") - - //Test Bad Dial Seeds - err = s1.DialSeeds([]string{"0.0.0:46658"}) - assert.NotNil(t, err, "expected unsuccessful dial seeds") - // Lets send some messages ch0Msg := "channel zero" ch1Msg := "channel foo" From dab31d01661fc9a0d0993cfeec10c3ef2914bcf6 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 3 Mar 2017 17:24:48 -0500 Subject: [PATCH 075/309] version bump to 0.4.0 --- .gitignore | 11 ----------- pex_reactor.go | 5 ++--- version.go | 2 +- 3 files changed, 3 insertions(+), 15 deletions(-) diff --git a/.gitignore b/.gitignore index c4694b3e1..c765108df 100644 --- a/.gitignore +++ b/.gitignore @@ -1,16 +1,5 @@ *.swp *.swo -.bak *.bak .DS_Store -build/* -rpc/test/.tendermint -.debora -.tendermint -remote_dump -.revision vendor -.vagrant -test/p2p/data/ -test/logs -.glide diff --git a/pex_reactor.go b/pex_reactor.go index 536da3a0a..c02d9a679 100644 --- a/pex_reactor.go +++ b/pex_reactor.go @@ -66,7 +66,8 @@ func (pexR *PEXReactor) AddPeer(peer *Peer) { // Add the peer to the address book netAddr, err := NewNetAddressString(peer.ListenAddr) if err != nil { - log.Warn("Error decoding message", "error", err) + // this should never happen + log.Error("Error in AddPeer: invalid peer address", "addr", peer.ListenAddr, "error", err) return } @@ -79,7 +80,6 @@ func (pexR *PEXReactor) AddPeer(peer *Peer) { // (For outbound peers, the address is already in the books) pexR.book.AddAddress(netAddr, netAddr) } - return } // Implements Reactor @@ -115,7 +115,6 @@ func (pexR *PEXReactor) Receive(chID byte, src *Peer, msgBytes []byte) { default: log.Warn(Fmt("Unknown message type %v", reflect.TypeOf(msg))) } - } // Asks peer for more addresses. diff --git a/version.go b/version.go index af98bef33..c13ec447b 100644 --- a/version.go +++ b/version.go @@ -1,3 +1,3 @@ package p2p -const Version = "0.3.5" // minor fixes +const Version = "0.4.0" // DialSeeds returns an error From 332f7056f721fb8bfd9359f2586e6b906a752613 Mon Sep 17 00:00:00 2001 From: Anton Kalyaev Date: Fri, 13 Jan 2017 19:33:31 +0400 Subject: [PATCH 076/309] start/stop the book with reactor Refs https://github.com/tendermint/tendermint/issues/335 --- pex_reactor.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/pex_reactor.go b/pex_reactor.go index c02d9a679..ed0ab76e8 100644 --- a/pex_reactor.go +++ b/pex_reactor.go @@ -42,12 +42,14 @@ func NewPEXReactor(book *AddrBook) *PEXReactor { func (pexR *PEXReactor) OnStart() error { pexR.BaseReactor.OnStart() + pexR.book.OnStart() go pexR.ensurePeersRoutine() return nil } func (pexR *PEXReactor) OnStop() { pexR.BaseReactor.OnStop() + pexR.book.OnStop() } // Implements Reactor From e7656873c1f290883d3272cc5182cbf2f8890abe Mon Sep 17 00:00:00 2001 From: Anton Kalyaev Date: Fri, 13 Jan 2017 20:48:42 +0400 Subject: [PATCH 077/309] public save API --- addrbook.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/addrbook.go b/addrbook.go index 2bbae64f5..c5415f022 100644 --- a/addrbook.go +++ b/addrbook.go @@ -368,6 +368,12 @@ func (a *AddrBook) loadFromFile(filePath string) bool { return true } +// Save saves the book. +func (a *AddrBook) Save() { + log.Info("Saving AddrBook to file", "size", a.Size()) + a.saveToFile(a.filePath) +} + /* Private methods */ func (a *AddrBook) saveRoutine() { From 2773410de43d48c7c1a49591ccdb194db355bd7d Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Mon, 16 Jan 2017 12:39:57 +0400 Subject: [PATCH 078/309] prevent nil addr Error: ``` Error: runtime error: invalid memoryaddress or nil pointer dereference\nStack: goroutine 549 [running]:\nruntime/debug.Stack(0x0, 0x0, 0x0)\n\t/usr/local/go/src/runtime/debug/stack.go:24 +0x80\ngithub.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p.(*MConnection)._recover(0xc821723b00)\n\t/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p/connection.go:173 +0x53\npanic(0xbe1500, 0xc820012080)\n\t/usr/local/go/src/runtime/panic.go:443 +0x4e9\ngithub.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p.(*NetAddress).Valid(0x0, 0x0)\n\t/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p/netaddress.go:125 +0x1c\ngithub.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p.(*NetAddress).Routable(0x0, 0xc8217bb740)\n\t/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p/netaddress.go:117 +0x25\ngithub.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p.(*AddrBook).addAddress(0xc820108380, 0x0, 0xc821739590)\n\t/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p/addrbook.go:524 +0x45\ngithub.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p.(*AddrBook).AddAddress(0xc820108380, 0x0, 0xc821739590)\n\t/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p/addrbook.go:160 +0x286\ngithub.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p.(*PEXReactor).Receive(0xc82000be60, 0xc820149f00, 0xc8218163f0, 0xc82184e000, 0x5b, 0x1000)\n\t/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p/pex_reactor.go:109 +0x457\ngithub.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p.newPeer.func1(0xc82011d500, 0xc82184e000, 0x5b, 0x1000)\n\t/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p/peer.go:58 +0x202\ngithub.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p.(*MConnection).recvRoutine(0xc821723b00)\n\t/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p/connection.go:439 +0x1177\ncreated by github.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p.(*MConnection).OnStart\n\t/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-p2p/connection.go:138 +0x1a1\n ``` --- pex_reactor.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/pex_reactor.go b/pex_reactor.go index ed0ab76e8..b8cb43f80 100644 --- a/pex_reactor.go +++ b/pex_reactor.go @@ -112,7 +112,9 @@ func (pexR *PEXReactor) Receive(chID byte, src *Peer, msgBytes []byte) { // (We don't want to get spammed with bad peers) srcAddr := src.Connection().RemoteAddress for _, addr := range msg.Addrs { - pexR.book.AddAddress(addr, srcAddr) + if addr != nil { + pexR.book.AddAddress(addr, srcAddr) + } } default: log.Warn(Fmt("Unknown message type %v", reflect.TypeOf(msg))) From 108beae7a83092692ca079f1fff17b879e71fdc3 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Mon, 16 Jan 2017 15:57:08 +0400 Subject: [PATCH 079/309] more tests for AddrBook --- addrbook_test.go | 218 ++++++++++++++++++++++------------------------- 1 file changed, 101 insertions(+), 117 deletions(-) diff --git a/addrbook_test.go b/addrbook_test.go index 5eb7c0b6a..7e8cb8d76 100644 --- a/addrbook_test.go +++ b/addrbook_test.go @@ -9,8 +9,6 @@ import ( "github.com/stretchr/testify/assert" ) -const addrBookStrict = true - func createTempFileName(prefix string) string { f, err := ioutil.TempFile("", prefix) if err != nil { @@ -24,20 +22,114 @@ func createTempFileName(prefix string) string { return fname } -func TestEmpty(t *testing.T) { +func TestAddrBookSaveLoad(t *testing.T) { fname := createTempFileName("addrbook_test") - // t.Logf("New tempfile name: %v", fname) - // Save an empty book & load it - book := NewAddrBook(fname, addrBookStrict) + // 0 addresses + book := NewAddrBook(fname, true) book.saveToFile(fname) - book = NewAddrBook(fname, addrBookStrict) + book = NewAddrBook(fname, true) book.loadFromFile(fname) - if book.Size() != 0 { - t.Errorf("Expected 0 addresses, found %v", book.Size()) + assert.Zero(t, book.Size()) + + // 100 addresses + randAddrs := randNetAddressPairs(t, 100) + + for _, addrSrc := range randAddrs { + book.AddAddress(addrSrc.addr, addrSrc.src) } + + assert.Equal(t, 100, book.Size()) + book.saveToFile(fname) + + book = NewAddrBook(fname, true) + book.loadFromFile(fname) + + assert.Equal(t, 100, book.Size()) +} + +func TestAddrBookLookup(t *testing.T) { + fname := createTempFileName("addrbook_test") + + randAddrs := randNetAddressPairs(t, 100) + + book := NewAddrBook(fname, true) + for _, addrSrc := range randAddrs { + addr := addrSrc.addr + src := addrSrc.src + book.AddAddress(addr, src) + + ka := book.addrLookup[addr.String()] + assert.NotNil(t, ka, "Expected to find KnownAddress %v but wasn't there.", addr) + + if !(ka.Addr.Equals(addr) && ka.Src.Equals(src)) { + t.Fatalf("KnownAddress doesn't match addr & src") + } + } +} + +func TestAddrBookPromoteToOld(t *testing.T) { + fname := createTempFileName("addrbook_test") + + randAddrs := randNetAddressPairs(t, 100) + + book := NewAddrBook(fname, true) + for _, addrSrc := range randAddrs { + book.AddAddress(addrSrc.addr, addrSrc.src) + } + + // Attempt all addresses. + for _, addrSrc := range randAddrs { + book.MarkAttempt(addrSrc.addr) + } + + // Promote half of them + for i, addrSrc := range randAddrs { + if i%2 == 0 { + book.MarkGood(addrSrc.addr) + } + } + + // TODO: do more testing :) + + selection := book.GetSelection() + t.Logf("selection: %v", selection) + + if len(selection) > book.Size() { + t.Errorf("selection could not be bigger than the book") + } +} + +func TestAddrBookHandlesDuplicates(t *testing.T) { + fname := createTempFileName("addrbook_test") + + book := NewAddrBook(fname, true) + + randAddrs := randNetAddressPairs(t, 100) + + differentSrc := randIPv4Address(t) + for _, addrSrc := range randAddrs { + book.AddAddress(addrSrc.addr, addrSrc.src) + book.AddAddress(addrSrc.addr, addrSrc.src) // duplicate + book.AddAddress(addrSrc.addr, differentSrc) // different src + } + + assert.Equal(t, 100, book.Size()) +} + +type netAddressPair struct { + addr *NetAddress + src *NetAddress +} + +func randNetAddressPairs(t *testing.T, n int) []netAddressPair { + randAddrs := make([]netAddressPair, n) + for i := 0; i < n; i++ { + randAddrs[i] = netAddressPair{addr: randIPv4Address(t), src: randIPv4Address(t)} + } + return randAddrs } func randIPv4Address(t *testing.T) *NetAddress { @@ -56,111 +148,3 @@ func randIPv4Address(t *testing.T) *NetAddress { } } } - -func TestSaveAddresses(t *testing.T) { - fname := createTempFileName("addrbook_test") - //t.Logf("New tempfile name: %v", fname) - - // Create some random addresses - randAddrs := []struct { - addr *NetAddress - src *NetAddress - }{} - for i := 0; i < 100; i++ { - addr := randIPv4Address(t) - src := randIPv4Address(t) - randAddrs = append(randAddrs, struct { - addr *NetAddress - src *NetAddress - }{ - addr: addr, - src: src, - }) - } - - // Create the book & populate & save - book := NewAddrBook(fname, addrBookStrict) - for _, addrSrc := range randAddrs { - book.AddAddress(addrSrc.addr, addrSrc.src) - } - if book.Size() != 100 { - t.Errorf("Expected 100 addresses, found %v", book.Size()) - } - book.saveToFile(fname) - - // Reload the book - book = NewAddrBook(fname, addrBookStrict) - book.loadFromFile(fname) - - // Test ... - - if book.Size() != 100 { - t.Errorf("Expected 100 addresses, found %v", book.Size()) - } - - for _, addrSrc := range randAddrs { - addr := addrSrc.addr - src := addrSrc.src - ka := book.addrLookup[addr.String()] - if ka == nil { - t.Fatalf("Expected to find KnownAddress %v but wasn't there.", addr) - } - if !(ka.Addr.Equals(addr) && ka.Src.Equals(src)) { - t.Fatalf("KnownAddress doesn't match addr & src") - } - } -} - -func TestPromoteToOld(t *testing.T) { - fname := createTempFileName("addrbook_test") - t.Logf("New tempfile name: %v", fname) - - // Create some random addresses - randAddrs := []struct { - addr *NetAddress - src *NetAddress - }{} - for i := 0; i < 100; i++ { - addr := randIPv4Address(t) - src := randIPv4Address(t) - randAddrs = append(randAddrs, struct { - addr *NetAddress - src *NetAddress - }{ - addr: addr, - src: src, - }) - } - - // Create the book & populate & save - book := NewAddrBook(fname, addrBookStrict) - for _, addrSrc := range randAddrs { - book.AddAddress(addrSrc.addr, addrSrc.src) - } - // Attempt all addresses. - for _, addrSrc := range randAddrs { - book.MarkAttempt(addrSrc.addr) - } - // Promote half of them - for i, addrSrc := range randAddrs { - if i%2 == 0 { - book.MarkGood(addrSrc.addr) - } - } - book.saveToFile(fname) - - // Reload the book - book = NewAddrBook(fname, addrBookStrict) - book.loadFromFile(fname) - - // Test ... - - if book.Size() != 100 { - t.Errorf("Expected 100 addresses, found %v", book.Size()) - } - - // TODO: do more testing :) - - selection := book.GetSelection() - t.Logf("selection: %v", selection) -} From 65b1756978fb6fe1c247dd361e3ef56dbd4a5165 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Mon, 16 Jan 2017 18:00:39 +0400 Subject: [PATCH 080/309] expose 2 API functions for tendermint#node/node.go --- pex_reactor.go | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/pex_reactor.go b/pex_reactor.go index b8cb43f80..2948c58f9 100644 --- a/pex_reactor.go +++ b/pex_reactor.go @@ -130,6 +130,16 @@ func (pexR *PEXReactor) SendAddrs(peer *Peer, addrs []*NetAddress) { peer.Send(PexChannel, struct{ PexMessage }{&pexAddrsMessage{Addrs: addrs}}) } +// SaveAddrBook saves underlying address book +func (r *PEXReactor) SaveAddrBook() { + r.book.Save() +} + +// AddPeerAddress adds raw NetAddress to the address book +func (r *PEXReactor) AddPeerAddress(peerAddr, srcAddr *NetAddress) { + r.book.AddAddress(peerAddr, srcAddr) +} + // Ensures that sufficient peers are connected. (continuous) func (pexR *PEXReactor) ensurePeersRoutine() { // Randomize when routine starts From 88b5c724f26f99d4094e2b8dcef72fb9bf89c5c4 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Sat, 4 Mar 2017 22:55:42 -0500 Subject: [PATCH 081/309] remove public addr book funcs from pex --- addrbook.go | 1 + pex_reactor.go | 10 ---------- 2 files changed, 1 insertion(+), 10 deletions(-) diff --git a/addrbook.go b/addrbook.go index c5415f022..ea438120b 100644 --- a/addrbook.go +++ b/addrbook.go @@ -153,6 +153,7 @@ func (a *AddrBook) OurAddresses() []*NetAddress { return addrs } +// NOTE: addr must not be nil func (a *AddrBook) AddAddress(addr *NetAddress, src *NetAddress) { a.mtx.Lock() defer a.mtx.Unlock() diff --git a/pex_reactor.go b/pex_reactor.go index 2948c58f9..b8cb43f80 100644 --- a/pex_reactor.go +++ b/pex_reactor.go @@ -130,16 +130,6 @@ func (pexR *PEXReactor) SendAddrs(peer *Peer, addrs []*NetAddress) { peer.Send(PexChannel, struct{ PexMessage }{&pexAddrsMessage{Addrs: addrs}}) } -// SaveAddrBook saves underlying address book -func (r *PEXReactor) SaveAddrBook() { - r.book.Save() -} - -// AddPeerAddress adds raw NetAddress to the address book -func (r *PEXReactor) AddPeerAddress(peerAddr, srcAddr *NetAddress) { - r.book.AddAddress(peerAddr, srcAddr) -} - // Ensures that sufficient peers are connected. (continuous) func (pexR *PEXReactor) ensurePeersRoutine() { // Randomize when routine starts From c94bc2bc2b3f0fe01f6666bd059b44f1703b7844 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Sun, 5 Mar 2017 21:57:07 -0500 Subject: [PATCH 082/309] DialSeeds takes an addrbook --- switch.go | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/switch.go b/switch.go index 2f7177bf0..eed8ceea5 100644 --- a/switch.go +++ b/switch.go @@ -297,15 +297,29 @@ func (sw *Switch) startInitPeer(peer *Peer) { } // Dial a list of seeds asynchronously in random order -func (sw *Switch) DialSeeds(seeds []string) error { +func (sw *Switch) DialSeeds(addrBook *AddrBook, seeds []string) error { netAddrs, err := NewNetAddressStrings(seeds) if err != nil { return err } + if addrBook != nil { + // add seeds to `addrBook` + ourAddrS := sw.nodeInfo.ListenAddr + ourAddr, _ := NewNetAddressString(ourAddrS) + for _, netAddr := range netAddrs { + // do not add ourselves + if netAddr.Equals(ourAddr) { + continue + } + addrBook.AddAddress(netAddr, ourAddr) + } + addrBook.Save() + } + // permute the list, dial them in random order. - perm := rand.Perm(len(seeds)) + perm := rand.Perm(len(netAddrs)) for i := 0; i < len(perm); i++ { go func(i int) { time.Sleep(time.Duration(rand.Int63n(3000)) * time.Millisecond) From beb3eda438fbbfc3b566ead4be5705474a12e50a Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Sun, 5 Mar 2017 22:59:18 -0500 Subject: [PATCH 083/309] fix addrbook start/stop --- addrbook.go | 3 +++ pex_reactor.go | 4 ++-- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/addrbook.go b/addrbook.go index ea438120b..ace0dba4a 100644 --- a/addrbook.go +++ b/addrbook.go @@ -135,6 +135,9 @@ func (a *AddrBook) OnStart() error { func (a *AddrBook) OnStop() { a.BaseService.OnStop() +} + +func (a *AddrBook) Wait() { a.wg.Wait() } diff --git a/pex_reactor.go b/pex_reactor.go index b8cb43f80..45c4c96d8 100644 --- a/pex_reactor.go +++ b/pex_reactor.go @@ -42,14 +42,14 @@ func NewPEXReactor(book *AddrBook) *PEXReactor { func (pexR *PEXReactor) OnStart() error { pexR.BaseReactor.OnStart() - pexR.book.OnStart() + pexR.book.Start() go pexR.ensurePeersRoutine() return nil } func (pexR *PEXReactor) OnStop() { pexR.BaseReactor.OnStop() - pexR.book.OnStop() + pexR.book.Stop() } // Implements Reactor From 53d777a2d54aa904a70119010e6c71a9bf367153 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Mon, 6 Mar 2017 01:30:41 -0500 Subject: [PATCH 084/309] CHANGELOG.md --- CHANGELOG.md | 57 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 CHANGELOG.md diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 000000000..81e30fcca --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,57 @@ +# Changelog + +## 0.4.0 (March 6, 2017) + +BREAKING CHANGES: + +- DialSeeds now takes an AddrBook and returns an error: `DialSeeds(*AddrBook, []string) error` +- NewNetAddressString now returns an error: `NewNetAddressString(string) (*NetAddress, error)` + +FEATURES: + +- `NewNetAddressStrings([]string) ([]*NetAddress, error)` +- `AddrBook.Save()` + +IMPROVEMENTS: + +- PexReactor responsible for starting and stopping the AddrBook + +BUG FIXES: + +- DialSeeds returns an error instead of panicking on bad addresses + +## 0.3.5 (January 12, 2017) + +FEATURES + +- Toggle strict routability in the AddrBook + +BUG FIXES + +- Close filtered out connections +- Fixes for MakeConnectedSwitches and Connect2Switches + +## 0.3.4 (August 10, 2016) + +FEATURES: + +- Optionally filter connections by address or public key + +## 0.3.3 (May 12, 2016) + +FEATURES: + +- FuzzConn + +## 0.3.2 (March 12, 2016) + +IMPROVEMENTS: + +- Memory optimizations + +## 0.3.1 () + +FEATURES: + +- Configurable parameters + From b03facd828da4fe8ec325a57a89d72510308eeb7 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Tue, 7 Mar 2017 18:34:13 +0400 Subject: [PATCH 085/309] add Dockerfile --- Dockerfile | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Dockerfile diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 000000000..c23c911ce --- /dev/null +++ b/Dockerfile @@ -0,0 +1,12 @@ +FROM golang:latest + +RUN mkdir -p /go/src/github.com/tendermint/go-rpc +WORKDIR /go/src/github.com/tendermint/go-rpc + +COPY Makefile /go/src/github.com/tendermint/go-rpc/ +# COPY glide.yaml /go/src/github.com/tendermint/go-rpc/ +# COPY glide.lock /go/src/github.com/tendermint/go-rpc/ + +COPY . /go/src/github.com/tendermint/go-rpc + +RUN make get_deps From e1d5873bdfc95728971a38297ec3150a556397f9 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Tue, 7 Mar 2017 18:34:54 +0400 Subject: [PATCH 086/309] support key-value params in JSONRPC (Refs #1) More changes: - remove Client interface (reason: empty) - introduce HTTPClient interface, which can be used for both ClientURI and ClientJSONRPC clients (so our users don't have to create their own) (Refs #8) - rename integration tests script to `integration_test.sh` - do not update deps on `get_deps` --- Makefile | 14 +++- README.md | 20 ++--- client/http_client.go | 32 ++++---- client/ws_client.go | 12 +-- rpc_test.go | 16 ++-- server/handlers.go | 107 ++++++++++++++++---------- test/data.json | 11 ++- test/{test.sh => integration_test.sh} | 33 ++++---- test/main.go | 6 +- types/types.go | 14 ++-- 10 files changed, 150 insertions(+), 115 deletions(-) rename test/{test.sh => integration_test.sh} (65%) diff --git a/Makefile b/Makefile index 3b005ea36..e17fa06ac 100644 --- a/Makefile +++ b/Makefile @@ -1,9 +1,15 @@ -.PHONY: all test get_deps +PACKAGES=$(shell go list ./...) all: test -test: - bash ./test/test.sh +test: + @echo "--> Running go test --race" + @go test --race $(PACKAGES) + @echo "--> Running integration tests" + @bash ./test/integration_test.sh get_deps: - go get -t -u github.com/tendermint/go-rpc/... + @echo "--> Running go get" + @go get -v -d $(PACKAGES) + +.PHONY: all test get_deps diff --git a/README.md b/README.md index 1a91fb693..4da0e5634 100644 --- a/README.md +++ b/README.md @@ -32,16 +32,16 @@ As a POST request, we use JSONRPC. For instance, the same request would have thi ``` { - "jsonrpc":"2.0", - "id":"anything", - "method":"hello_world", - "params":["my_world", 5] + "jsonrpc": "2.0", + "id": "anything", + "method": "hello_world", + "params": { + "name": "my_world", + "num": 5 + } } ``` -Note the `params` does not currently support key-value pairs (https://github.com/tendermint/go-rpc/issues/1), so order matters (you can get the order from making a -GET request to `/`) - With the above saved in file `data.json`, we can make the request with ``` @@ -50,8 +50,8 @@ curl --data @data.json http://localhost:8008 ## WebSocket (JSONRPC) -All requests are exposed over websocket in the same form as the POST JSONRPC. -Websocket connections are available at their own endpoint, typically `/websocket`, +All requests are exposed over websocket in the same form as the POST JSONRPC. +Websocket connections are available at their own endpoint, typically `/websocket`, though this is configurable when starting the server. # Server Definition @@ -102,7 +102,7 @@ go func() { Note that unix sockets are supported as well (eg. `/path/to/socket` instead of `0.0.0.0:8008`) Now see all available endpoints by sending a GET request to `0.0.0.0:8008`. -Each route is available as a GET request, as a JSONRPCv2 POST request, and via JSONRPCv2 over websockets +Each route is available as a GET request, as a JSONRPCv2 POST request, and via JSONRPCv2 over websockets. # Examples diff --git a/client/http_client.go b/client/http_client.go index 57da5d6ec..0c8bb6363 100644 --- a/client/http_client.go +++ b/client/http_client.go @@ -3,7 +3,6 @@ package rpcclient import ( "bytes" "encoding/json" - "errors" "fmt" "io/ioutil" "net" @@ -12,11 +11,16 @@ import ( "reflect" "strings" - . "github.com/tendermint/go-common" - "github.com/tendermint/go-rpc/types" - "github.com/tendermint/go-wire" + // cmn "github.com/tendermint/go-common" + rpctypes "github.com/tendermint/go-rpc/types" + wire "github.com/tendermint/go-wire" ) +// HTTPClient is a common interface for ClientJSONRPC and ClientURI. +type HTTPClient interface { + Call(method string, params []interface{}, result interface{}) (interface{}, error) +} + // TODO: Deprecate support for IP:PORT or /path/to/socket func makeHTTPDialer(remoteAddr string) (string, func(string, string) (net.Conn, error)) { @@ -49,11 +53,6 @@ func makeHTTPClient(remoteAddr string) (string, *http.Client) { //------------------------------------------------------------------------------------ -type Client interface { -} - -//------------------------------------------------------------------------------------ - // JSON rpc takes params as a slice type ClientJSONRPC struct { address string @@ -68,11 +67,11 @@ func NewClientJSONRPC(remote string) *ClientJSONRPC { } } -func (c *ClientJSONRPC) Call(method string, params []interface{}, result interface{}) (interface{}, error) { +func (c *ClientJSONRPC) Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) { return c.call(method, params, result) } -func (c *ClientJSONRPC) call(method string, params []interface{}, result interface{}) (interface{}, error) { +func (c *ClientJSONRPC) call(method string, params map[string]interface{}, result interface{}) (interface{}, error) { // Make request and get responseBytes request := rpctypes.RPCRequest{ JSONRPC: "2.0", @@ -80,7 +79,10 @@ func (c *ClientJSONRPC) call(method string, params []interface{}, result interfa Params: params, ID: "", } - requestBytes := wire.JSONBytes(request) + requestBytes, err := json.Marshal(request) + if err != nil { + return nil, err + } requestBuf := bytes.NewBuffer(requestBytes) // log.Info(Fmt("RPC request to %v (%v): %v", c.remote, method, string(requestBytes))) httpResponse, err := c.client.Post(c.address, "text/json", requestBuf) @@ -145,16 +147,16 @@ func unmarshalResponseBytes(responseBytes []byte, result interface{}) (interface response := &rpctypes.RPCResponse{} err = json.Unmarshal(responseBytes, response) if err != nil { - return nil, errors.New(Fmt("Error unmarshalling rpc response: %v", err)) + return nil, fmt.Errorf("Error unmarshalling rpc response: %v", err) } errorStr := response.Error if errorStr != "" { - return nil, errors.New(Fmt("Response error: %v", errorStr)) + return nil, fmt.Errorf("Response error: %v", errorStr) } // unmarshal the RawMessage into the result result = wire.ReadJSONPtr(result, *response.Result, &err) if err != nil { - return nil, errors.New(Fmt("Error unmarshalling rpc response result: %v", err)) + return nil, fmt.Errorf("Error unmarshalling rpc response result: %v", err) } return result, nil } diff --git a/client/ws_client.go b/client/ws_client.go index 4d975f8ec..e5135d0af 100644 --- a/client/ws_client.go +++ b/client/ws_client.go @@ -8,8 +8,8 @@ import ( "time" "github.com/gorilla/websocket" - . "github.com/tendermint/go-common" - "github.com/tendermint/go-rpc/types" + cmn "github.com/tendermint/go-common" + rpctypes "github.com/tendermint/go-rpc/types" ) const ( @@ -19,7 +19,7 @@ const ( ) type WSClient struct { - BaseService + cmn.BaseService Address string // IP:PORT or /path/to/socket Endpoint string // /websocket/url/endpoint Dialer func(string, string) (net.Conn, error) @@ -39,7 +39,7 @@ func NewWSClient(remoteAddr, endpoint string) *WSClient { ResultsCh: make(chan json.RawMessage, wsResultsChannelCapacity), ErrorsCh: make(chan error, wsErrorsChannelCapacity), } - wsClient.BaseService = *NewBaseService(log, "WSClient", wsClient) + wsClient.BaseService = *cmn.NewBaseService(log, "WSClient", wsClient) return wsClient } @@ -122,7 +122,7 @@ func (wsc *WSClient) Subscribe(eventid string) error { JSONRPC: "2.0", ID: "", Method: "subscribe", - Params: []interface{}{eventid}, + Params: map[string]interface{}{"event": eventid}, }) return err } @@ -133,7 +133,7 @@ func (wsc *WSClient) Unsubscribe(eventid string) error { JSONRPC: "2.0", ID: "", Method: "unsubscribe", - Params: []interface{}{eventid}, + Params: map[string]interface{}{"event": eventid}, }) return err } diff --git a/rpc_test.go b/rpc_test.go index 1fcda0e5e..2c45c4c13 100644 --- a/rpc_test.go +++ b/rpc_test.go @@ -5,10 +5,10 @@ import ( "testing" "time" - "github.com/tendermint/go-rpc/client" - "github.com/tendermint/go-rpc/server" - "github.com/tendermint/go-rpc/types" - "github.com/tendermint/go-wire" + rpcclient "github.com/tendermint/go-rpc/client" + rpcserver "github.com/tendermint/go-rpc/server" + rpctypes "github.com/tendermint/go-rpc/types" + wire "github.com/tendermint/go-wire" ) // Client and Server should work over tcp or unix sockets @@ -88,7 +88,9 @@ func testURI(t *testing.T, cl *rpcclient.ClientURI) { func testJSONRPC(t *testing.T, cl *rpcclient.ClientJSONRPC) { val := "acbd" - params := []interface{}{val} + params := map[string]interface{}{ + "arg": val, + } var result Result _, err := cl.Call("status", params, &result) if err != nil { @@ -102,7 +104,9 @@ func testJSONRPC(t *testing.T, cl *rpcclient.ClientJSONRPC) { func testWS(t *testing.T, cl *rpcclient.WSClient) { val := "acbd" - params := []interface{}{val} + params := map[string]interface{}{ + "arg": val, + } err := cl.WriteJSON(rpctypes.RPCRequest{ JSONRPC: "2.0", ID: "", diff --git a/server/handlers.go b/server/handlers.go index 7a4ec1a45..beb664d9f 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -4,7 +4,6 @@ import ( "bytes" "encoding/hex" "encoding/json" - "errors" "fmt" "io/ioutil" "net/http" @@ -14,10 +13,10 @@ import ( "time" "github.com/gorilla/websocket" - . "github.com/tendermint/go-common" - "github.com/tendermint/go-events" - . "github.com/tendermint/go-rpc/types" - "github.com/tendermint/go-wire" + cmn "github.com/tendermint/go-common" + events "github.com/tendermint/go-events" + types "github.com/tendermint/go-rpc/types" + wire "github.com/tendermint/go-wire" ) // Adds a route for each function in the funcMap, as well as general jsonrpc and websocket handlers for all functions. @@ -105,75 +104,99 @@ func makeJSONRPCHandler(funcMap map[string]*RPCFunc) http.HandlerFunc { return } - var request RPCRequest + var request types.RPCRequest err := json.Unmarshal(b, &request) if err != nil { - WriteRPCResponseHTTP(w, NewRPCResponse("", nil, fmt.Sprintf("Error unmarshalling request: %v", err.Error()))) + WriteRPCResponseHTTP(w, types.NewRPCResponse("", nil, fmt.Sprintf("Error unmarshalling request: %v", err.Error()))) return } if len(r.URL.Path) > 1 { - WriteRPCResponseHTTP(w, NewRPCResponse(request.ID, nil, fmt.Sprintf("Invalid JSONRPC endpoint %s", r.URL.Path))) + WriteRPCResponseHTTP(w, types.NewRPCResponse(request.ID, nil, fmt.Sprintf("Invalid JSONRPC endpoint %s", r.URL.Path))) return } rpcFunc := funcMap[request.Method] if rpcFunc == nil { - WriteRPCResponseHTTP(w, NewRPCResponse(request.ID, nil, "RPC method unknown: "+request.Method)) + WriteRPCResponseHTTP(w, types.NewRPCResponse(request.ID, nil, "RPC method unknown: "+request.Method)) return } if rpcFunc.ws { - WriteRPCResponseHTTP(w, NewRPCResponse(request.ID, nil, "RPC method is only for websockets: "+request.Method)) + WriteRPCResponseHTTP(w, types.NewRPCResponse(request.ID, nil, "RPC method is only for websockets: "+request.Method)) return } args, err := jsonParamsToArgs(rpcFunc, request.Params) if err != nil { - WriteRPCResponseHTTP(w, NewRPCResponse(request.ID, nil, fmt.Sprintf("Error converting json params to arguments: %v", err.Error()))) + WriteRPCResponseHTTP(w, types.NewRPCResponse(request.ID, nil, fmt.Sprintf("Error converting json params to arguments: %v", err.Error()))) return } returns := rpcFunc.f.Call(args) log.Info("HTTPJSONRPC", "method", request.Method, "args", args, "returns", returns) result, err := unreflectResult(returns) if err != nil { - WriteRPCResponseHTTP(w, NewRPCResponse(request.ID, result, fmt.Sprintf("Error unreflecting result: %v", err.Error()))) + WriteRPCResponseHTTP(w, types.NewRPCResponse(request.ID, result, fmt.Sprintf("Error unreflecting result: %v", err.Error()))) return } - WriteRPCResponseHTTP(w, NewRPCResponse(request.ID, result, "")) + WriteRPCResponseHTTP(w, types.NewRPCResponse(request.ID, result, "")) } } // Convert a list of interfaces to properly typed values -func jsonParamsToArgs(rpcFunc *RPCFunc, params []interface{}) ([]reflect.Value, error) { +func jsonParamsToArgs(rpcFunc *RPCFunc, params map[string]interface{}) ([]reflect.Value, error) { if len(rpcFunc.argNames) != len(params) { - return nil, errors.New(fmt.Sprintf("Expected %v parameters (%v), got %v (%v)", - len(rpcFunc.argNames), rpcFunc.argNames, len(params), params)) + return nil, fmt.Errorf("Expected %v parameters (%v), got %v (%v)", + len(rpcFunc.argNames), rpcFunc.argNames, len(params), params) } + values := make([]reflect.Value, len(params)) - for i, p := range params { + + for name, param := range params { + i := indexOf(name, rpcFunc.argNames) + if -1 == i { + return nil, fmt.Errorf("%s is not an argument (args: %v)", name, rpcFunc.argNames) + } ty := rpcFunc.args[i] - v, err := _jsonObjectToArg(ty, p) + v, err := _jsonObjectToArg(ty, param) if err != nil { return nil, err } values[i] = v } + return values, nil } -// Same as above, but with the first param the websocket connection -func jsonParamsToArgsWS(rpcFunc *RPCFunc, params []interface{}, wsCtx WSRPCContext) ([]reflect.Value, error) { - if len(rpcFunc.argNames) != len(params) { - return nil, errors.New(fmt.Sprintf("Expected %v parameters (%v), got %v (%v)", - len(rpcFunc.argNames)-1, rpcFunc.argNames[1:], len(params), params)) +// indexOf returns index of a string in a slice of strings, -1 if not found. +func indexOf(value string, values []string) int { + for i, v := range values { + if v == value { + return i + } } + return -1 +} + +// Same as above, but with the first param the websocket connection +func jsonParamsToArgsWS(rpcFunc *RPCFunc, params map[string]interface{}, wsCtx types.WSRPCContext) ([]reflect.Value, error) { + if len(rpcFunc.argNames) != len(params) { + return nil, fmt.Errorf("Expected %v parameters (%v), got %v (%v)", + len(rpcFunc.argNames)-1, rpcFunc.argNames[1:], len(params), params) + } + values := make([]reflect.Value, len(params)+1) values[0] = reflect.ValueOf(wsCtx) - for i, p := range params { + + for name, param := range params { + i := indexOf(name, rpcFunc.argNames) + if -1 == i { + return nil, fmt.Errorf("%s is not an argument (args: %v)", name, rpcFunc.argNames) + } ty := rpcFunc.args[i+1] - v, err := _jsonObjectToArg(ty, p) + v, err := _jsonObjectToArg(ty, param) if err != nil { return nil, err } values[i+1] = v } + return values, nil } @@ -197,7 +220,7 @@ func makeHTTPHandler(rpcFunc *RPCFunc) func(http.ResponseWriter, *http.Request) // Exception for websocket endpoints if rpcFunc.ws { return func(w http.ResponseWriter, r *http.Request) { - WriteRPCResponseHTTP(w, NewRPCResponse("", nil, "This RPC method is only for websockets")) + WriteRPCResponseHTTP(w, types.NewRPCResponse("", nil, "This RPC method is only for websockets")) } } // All other endpoints @@ -205,17 +228,17 @@ func makeHTTPHandler(rpcFunc *RPCFunc) func(http.ResponseWriter, *http.Request) log.Debug("HTTP HANDLER", "req", r) args, err := httpParamsToArgs(rpcFunc, r) if err != nil { - WriteRPCResponseHTTP(w, NewRPCResponse("", nil, fmt.Sprintf("Error converting http params to args: %v", err.Error()))) + WriteRPCResponseHTTP(w, types.NewRPCResponse("", nil, fmt.Sprintf("Error converting http params to args: %v", err.Error()))) return } returns := rpcFunc.f.Call(args) log.Info("HTTPRestRPC", "method", r.URL.Path, "args", args, "returns", returns) result, err := unreflectResult(returns) if err != nil { - WriteRPCResponseHTTP(w, NewRPCResponse("", nil, fmt.Sprintf("Error unreflecting result: %v", err.Error()))) + WriteRPCResponseHTTP(w, types.NewRPCResponse("", nil, fmt.Sprintf("Error unreflecting result: %v", err.Error()))) return } - WriteRPCResponseHTTP(w, NewRPCResponse("", result, "")) + WriteRPCResponseHTTP(w, types.NewRPCResponse("", result, "")) } } @@ -313,11 +336,11 @@ const ( // contains listener id, underlying ws connection, // and the event switch for subscribing to events type wsConnection struct { - BaseService + cmn.BaseService remoteAddr string baseConn *websocket.Conn - writeChan chan RPCResponse + writeChan chan types.RPCResponse readTimeout *time.Timer pingTicker *time.Ticker @@ -330,11 +353,11 @@ func NewWSConnection(baseConn *websocket.Conn, funcMap map[string]*RPCFunc, evsw wsc := &wsConnection{ remoteAddr: baseConn.RemoteAddr().String(), baseConn: baseConn, - writeChan: make(chan RPCResponse, writeChanCapacity), // error when full. + writeChan: make(chan types.RPCResponse, writeChanCapacity), // error when full. funcMap: funcMap, evsw: evsw, } - wsc.BaseService = *NewBaseService(log, "wsConnection", wsc) + wsc.BaseService = *cmn.NewBaseService(log, "wsConnection", wsc) return wsc } @@ -399,7 +422,7 @@ func (wsc *wsConnection) GetEventSwitch() events.EventSwitch { // Implements WSRPCConnection // Blocking write to writeChan until service stops. // Goroutine-safe -func (wsc *wsConnection) WriteRPCResponse(resp RPCResponse) { +func (wsc *wsConnection) WriteRPCResponse(resp types.RPCResponse) { select { case <-wsc.Quit: return @@ -410,7 +433,7 @@ func (wsc *wsConnection) WriteRPCResponse(resp RPCResponse) { // Implements WSRPCConnection // Nonblocking write. // Goroutine-safe -func (wsc *wsConnection) TryWriteRPCResponse(resp RPCResponse) bool { +func (wsc *wsConnection) TryWriteRPCResponse(resp types.RPCResponse) bool { select { case <-wsc.Quit: return false @@ -444,11 +467,11 @@ func (wsc *wsConnection) readRoutine() { wsc.Stop() return } - var request RPCRequest + var request types.RPCRequest err = json.Unmarshal(in, &request) if err != nil { errStr := fmt.Sprintf("Error unmarshaling data: %s", err.Error()) - wsc.WriteRPCResponse(NewRPCResponse(request.ID, nil, errStr)) + wsc.WriteRPCResponse(types.NewRPCResponse(request.ID, nil, errStr)) continue } @@ -456,28 +479,28 @@ func (wsc *wsConnection) readRoutine() { rpcFunc := wsc.funcMap[request.Method] if rpcFunc == nil { - wsc.WriteRPCResponse(NewRPCResponse(request.ID, nil, "RPC method unknown: "+request.Method)) + wsc.WriteRPCResponse(types.NewRPCResponse(request.ID, nil, "RPC method unknown: "+request.Method)) continue } var args []reflect.Value if rpcFunc.ws { - wsCtx := WSRPCContext{Request: request, WSRPCConnection: wsc} + wsCtx := types.WSRPCContext{Request: request, WSRPCConnection: wsc} args, err = jsonParamsToArgsWS(rpcFunc, request.Params, wsCtx) } else { args, err = jsonParamsToArgs(rpcFunc, request.Params) } if err != nil { - wsc.WriteRPCResponse(NewRPCResponse(request.ID, nil, err.Error())) + wsc.WriteRPCResponse(types.NewRPCResponse(request.ID, nil, err.Error())) continue } returns := rpcFunc.f.Call(args) log.Info("WSJSONRPC", "method", request.Method, "args", args, "returns", returns) result, err := unreflectResult(returns) if err != nil { - wsc.WriteRPCResponse(NewRPCResponse(request.ID, nil, err.Error())) + wsc.WriteRPCResponse(types.NewRPCResponse(request.ID, nil, err.Error())) continue } else { - wsc.WriteRPCResponse(NewRPCResponse(request.ID, result, "")) + wsc.WriteRPCResponse(types.NewRPCResponse(request.ID, result, "")) continue } diff --git a/test/data.json b/test/data.json index eac2e0dfe..83283ec33 100644 --- a/test/data.json +++ b/test/data.json @@ -1,6 +1,9 @@ { - "jsonrpc":"2.0", - "id":"", - "method":"hello_world", - "params":["my_world", 5] + "jsonrpc": "2.0", + "id": "", + "method": "hello_world", + "params": { + "name": "my_world", + "num": 5 + } } diff --git a/test/test.sh b/test/integration_test.sh similarity index 65% rename from test/test.sh rename to test/integration_test.sh index f5e740241..739708068 100755 --- a/test/test.sh +++ b/test/integration_test.sh @@ -1,26 +1,22 @@ -#! /bin/bash - -cd $GOPATH/src/github.com/tendermint/go-rpc - -# get deps -go get -u -t ./... - -# go tests -go test --race github.com/tendermint/go-rpc/... - - -# integration tests -cd test +#!/usr/bin/env bash set -e +# Get the directory of where this script is. +SOURCE="${BASH_SOURCE[0]}" +while [ -h "$SOURCE" ] ; do SOURCE="$(readlink "$SOURCE")"; done +DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" + +# Change into that dir because we expect that. +pushd "$DIR" + go build -o server main.go ./server > /dev/null & PID=$! sleep 2 # simple request -R1=`curl -s 'http://localhost:8008/hello_world?name="my_world"&num=5'` -R2=`curl -s --data @data.json http://localhost:8008` +R1=$(curl -s 'http://localhost:8008/hello_world?name="my_world"&num=5') +R2=$(curl -s --data @data.json http://localhost:8008) if [[ "$R1" != "$R2" ]]; then echo "responses are not identical:" echo "R1: $R1" @@ -31,7 +27,7 @@ else fi # request with 0x-prefixed hex string arg -R1=`curl -s 'http://localhost:8008/hello_world?name=0x41424344&num=123'` +R1=$(curl -s 'http://localhost:8008/hello_world?name=0x41424344&num=123') R2='{"jsonrpc":"2.0","id":"","result":{"Result":"hi ABCD 123"},"error":""}' if [[ "$R1" != "$R2" ]]; then echo "responses are not identical:" @@ -43,7 +39,7 @@ else fi # request with unquoted string arg -R1=`curl -s 'http://localhost:8008/hello_world?name=abcd&num=123'` +R1=$(curl -s 'http://localhost:8008/hello_world?name=abcd&num=123') R2="{\"jsonrpc\":\"2.0\",\"id\":\"\",\"result\":null,\"error\":\"Error converting http params to args: invalid character 'a' looking for beginning of value\"}" if [[ "$R1" != "$R2" ]]; then echo "responses are not identical:" @@ -55,7 +51,7 @@ else fi # request with string type when expecting number arg -R1=`curl -s 'http://localhost:8008/hello_world?name="abcd"&num=0xabcd'` +R1=$(curl -s 'http://localhost:8008/hello_world?name="abcd"&num=0xabcd') R2="{\"jsonrpc\":\"2.0\",\"id\":\"\",\"result\":null,\"error\":\"Error converting http params to args: Got a hex string arg, but expected 'int'\"}" if [[ "$R1" != "$R2" ]]; then echo "responses are not identical:" @@ -67,3 +63,4 @@ else fi kill -9 $PID || exit 0 +popd diff --git a/test/main.go b/test/main.go index d14ab05f5..28de2be88 100644 --- a/test/main.go +++ b/test/main.go @@ -4,7 +4,7 @@ import ( "fmt" "net/http" - . "github.com/tendermint/go-common" + cmn "github.com/tendermint/go-common" rpcserver "github.com/tendermint/go-rpc/server" ) @@ -25,11 +25,11 @@ func main() { rpcserver.RegisterRPCFuncs(mux, routes) _, err := rpcserver.StartHTTPServer("0.0.0.0:8008", mux) if err != nil { - Exit(err.Error()) + cmn.Exit(err.Error()) } // Wait forever - TrapSignal(func() { + cmn.TrapSignal(func() { }) } diff --git a/types/types.go b/types/types.go index ee4a63cc8..cebd7564a 100644 --- a/types/types.go +++ b/types/types.go @@ -4,18 +4,18 @@ import ( "encoding/json" "strings" - "github.com/tendermint/go-events" - "github.com/tendermint/go-wire" + events "github.com/tendermint/go-events" + wire "github.com/tendermint/go-wire" ) type RPCRequest struct { - JSONRPC string `json:"jsonrpc"` - ID string `json:"id"` - Method string `json:"method"` - Params []interface{} `json:"params"` + JSONRPC string `json:"jsonrpc"` + ID string `json:"id"` + Method string `json:"method"` + Params map[string]interface{} `json:"params"` } -func NewRPCRequest(id string, method string, params []interface{}) RPCRequest { +func NewRPCRequest(id string, method string, params map[string]interface{}) RPCRequest { return RPCRequest{ JSONRPC: "2.0", ID: id, From 66867bf94984dced859e24075dd5b462f3f09b8b Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Tue, 7 Mar 2017 19:04:24 +0400 Subject: [PATCH 087/309] remove "rpc" prefix from package imports --- client/http_client.go | 9 ++++---- client/ws_client.go | 8 +++---- rpc_test.go | 49 ++++++++++++++++++++++--------------------- server/http_server.go | 14 ++++++------- 4 files changed, 39 insertions(+), 41 deletions(-) diff --git a/client/http_client.go b/client/http_client.go index 0c8bb6363..c11f8b3e3 100644 --- a/client/http_client.go +++ b/client/http_client.go @@ -11,8 +11,7 @@ import ( "reflect" "strings" - // cmn "github.com/tendermint/go-common" - rpctypes "github.com/tendermint/go-rpc/types" + types "github.com/tendermint/go-rpc/types" wire "github.com/tendermint/go-wire" ) @@ -28,7 +27,7 @@ func makeHTTPDialer(remoteAddr string) (string, func(string, string) (net.Conn, var protocol, address string if len(parts) != 2 { log.Warn("WARNING (go-rpc): Please use fully formed listening addresses, including the tcp:// or unix:// prefix") - protocol = rpctypes.SocketType(remoteAddr) + protocol = types.SocketType(remoteAddr) address = remoteAddr } else { protocol, address = parts[0], parts[1] @@ -73,7 +72,7 @@ func (c *ClientJSONRPC) Call(method string, params map[string]interface{}, resul func (c *ClientJSONRPC) call(method string, params map[string]interface{}, result interface{}) (interface{}, error) { // Make request and get responseBytes - request := rpctypes.RPCRequest{ + request := types.RPCRequest{ JSONRPC: "2.0", Method: method, Params: params, @@ -144,7 +143,7 @@ func unmarshalResponseBytes(responseBytes []byte, result interface{}) (interface // into the correct type // log.Notice("response", "response", string(responseBytes)) var err error - response := &rpctypes.RPCResponse{} + response := &types.RPCResponse{} err = json.Unmarshal(responseBytes, response) if err != nil { return nil, fmt.Errorf("Error unmarshalling rpc response: %v", err) diff --git a/client/ws_client.go b/client/ws_client.go index e5135d0af..d27e499dd 100644 --- a/client/ws_client.go +++ b/client/ws_client.go @@ -9,7 +9,7 @@ import ( "github.com/gorilla/websocket" cmn "github.com/tendermint/go-common" - rpctypes "github.com/tendermint/go-rpc/types" + types "github.com/tendermint/go-rpc/types" ) const ( @@ -96,7 +96,7 @@ func (wsc *WSClient) receiveEventsRoutine() { wsc.Stop() break } else { - var response rpctypes.RPCResponse + var response types.RPCResponse err := json.Unmarshal(data, &response) if err != nil { log.Info("WSClient failed to parse message", "error", err, "data", string(data)) @@ -118,7 +118,7 @@ func (wsc *WSClient) receiveEventsRoutine() { // subscribe to an event func (wsc *WSClient) Subscribe(eventid string) error { - err := wsc.WriteJSON(rpctypes.RPCRequest{ + err := wsc.WriteJSON(types.RPCRequest{ JSONRPC: "2.0", ID: "", Method: "subscribe", @@ -129,7 +129,7 @@ func (wsc *WSClient) Subscribe(eventid string) error { // unsubscribe from an event func (wsc *WSClient) Unsubscribe(eventid string) error { - err := wsc.WriteJSON(rpctypes.RPCRequest{ + err := wsc.WriteJSON(types.RPCRequest{ JSONRPC: "2.0", ID: "", Method: "unsubscribe", diff --git a/rpc_test.go b/rpc_test.go index 2c45c4c13..c77799199 100644 --- a/rpc_test.go +++ b/rpc_test.go @@ -5,14 +5,14 @@ import ( "testing" "time" - rpcclient "github.com/tendermint/go-rpc/client" - rpcserver "github.com/tendermint/go-rpc/server" - rpctypes "github.com/tendermint/go-rpc/types" + client "github.com/tendermint/go-rpc/client" + server "github.com/tendermint/go-rpc/server" + types "github.com/tendermint/go-rpc/types" wire "github.com/tendermint/go-wire" ) // Client and Server should work over tcp or unix sockets -var ( +const ( tcpAddr = "tcp://0.0.0.0:46657" unixAddr = "unix:///tmp/go-rpc.sock" // NOTE: must remove file for test to run again @@ -32,8 +32,8 @@ var _ = wire.RegisterInterface( ) // Define some routes -var Routes = map[string]*rpcserver.RPCFunc{ - "status": rpcserver.NewRPCFunc(StatusResult, "arg"), +var Routes = map[string]*server.RPCFunc{ + "status": server.NewRPCFunc(StatusResult, "arg"), } // an rpc function @@ -43,23 +43,24 @@ func StatusResult(v string) (Result, error) { // launch unix and tcp servers func init() { + mux := http.NewServeMux() - rpcserver.RegisterRPCFuncs(mux, Routes) - wm := rpcserver.NewWebsocketManager(Routes, nil) + server.RegisterRPCFuncs(mux, Routes) + wm := server.NewWebsocketManager(Routes, nil) mux.HandleFunc(websocketEndpoint, wm.WebsocketHandler) go func() { - _, err := rpcserver.StartHTTPServer(tcpAddr, mux) + _, err := server.StartHTTPServer(tcpAddr, mux) if err != nil { panic(err) } }() mux2 := http.NewServeMux() - rpcserver.RegisterRPCFuncs(mux2, Routes) - wm = rpcserver.NewWebsocketManager(Routes, nil) + server.RegisterRPCFuncs(mux2, Routes) + wm = server.NewWebsocketManager(Routes, nil) mux2.HandleFunc(websocketEndpoint, wm.WebsocketHandler) go func() { - _, err := rpcserver.StartHTTPServer(unixAddr, mux2) + _, err := server.StartHTTPServer(unixAddr, mux2) if err != nil { panic(err) } @@ -70,7 +71,7 @@ func init() { } -func testURI(t *testing.T, cl *rpcclient.ClientURI) { +func testURI(t *testing.T, cl *client.ClientURI) { val := "acbd" params := map[string]interface{}{ "arg": val, @@ -86,7 +87,7 @@ func testURI(t *testing.T, cl *rpcclient.ClientURI) { } } -func testJSONRPC(t *testing.T, cl *rpcclient.ClientJSONRPC) { +func testJSONRPC(t *testing.T, cl *client.ClientJSONRPC) { val := "acbd" params := map[string]interface{}{ "arg": val, @@ -102,12 +103,12 @@ func testJSONRPC(t *testing.T, cl *rpcclient.ClientJSONRPC) { } } -func testWS(t *testing.T, cl *rpcclient.WSClient) { +func testWS(t *testing.T, cl *client.WSClient) { val := "acbd" params := map[string]interface{}{ "arg": val, } - err := cl.WriteJSON(rpctypes.RPCRequest{ + err := cl.WriteJSON(types.RPCRequest{ JSONRPC: "2.0", ID: "", Method: "status", @@ -132,27 +133,27 @@ func testWS(t *testing.T, cl *rpcclient.WSClient) { //------------- func TestURI_TCP(t *testing.T) { - cl := rpcclient.NewClientURI(tcpAddr) + cl := client.NewClientURI(tcpAddr) testURI(t, cl) } func TestURI_UNIX(t *testing.T) { - cl := rpcclient.NewClientURI(unixAddr) + cl := client.NewClientURI(unixAddr) testURI(t, cl) } func TestJSONRPC_TCP(t *testing.T) { - cl := rpcclient.NewClientJSONRPC(tcpAddr) + cl := client.NewClientJSONRPC(tcpAddr) testJSONRPC(t, cl) } func TestJSONRPC_UNIX(t *testing.T) { - cl := rpcclient.NewClientJSONRPC(unixAddr) + cl := client.NewClientJSONRPC(unixAddr) testJSONRPC(t, cl) } func TestWS_TCP(t *testing.T) { - cl := rpcclient.NewWSClient(tcpAddr, websocketEndpoint) + cl := client.NewWSClient(tcpAddr, websocketEndpoint) _, err := cl.Start() if err != nil { t.Fatal(err) @@ -161,7 +162,7 @@ func TestWS_TCP(t *testing.T) { } func TestWS_UNIX(t *testing.T) { - cl := rpcclient.NewWSClient(unixAddr, websocketEndpoint) + cl := client.NewWSClient(unixAddr, websocketEndpoint) _, err := cl.Start() if err != nil { t.Fatal(err) @@ -170,7 +171,7 @@ func TestWS_UNIX(t *testing.T) { } func TestHexStringArg(t *testing.T) { - cl := rpcclient.NewClientURI(tcpAddr) + cl := client.NewClientURI(tcpAddr) // should NOT be handled as hex val := "0xabc" params := map[string]interface{}{ @@ -188,7 +189,7 @@ func TestHexStringArg(t *testing.T) { } func TestQuotedStringArg(t *testing.T) { - cl := rpcclient.NewClientURI(tcpAddr) + cl := client.NewClientURI(tcpAddr) // should NOT be unquoted val := "\"abc\"" params := map[string]interface{}{ diff --git a/server/http_server.go b/server/http_server.go index 26163cf12..24b9f18af 100644 --- a/server/http_server.go +++ b/server/http_server.go @@ -11,9 +11,7 @@ import ( "strings" "time" - . "github.com/tendermint/go-common" - . "github.com/tendermint/go-rpc/types" - //"github.com/tendermint/go-wire" + types "github.com/tendermint/go-rpc/types" ) func StartHTTPServer(listenAddr string, handler http.Handler) (listener net.Listener, err error) { @@ -24,14 +22,14 @@ func StartHTTPServer(listenAddr string, handler http.Handler) (listener net.List log.Warn("WARNING (go-rpc): Please use fully formed listening addresses, including the tcp:// or unix:// prefix") // we used to allow addrs without tcp/unix prefix by checking for a colon // TODO: Deprecate - proto = SocketType(listenAddr) + proto = types.SocketType(listenAddr) addr = listenAddr // return nil, fmt.Errorf("Invalid listener address %s", lisenAddr) } else { proto, addr = parts[0], parts[1] } - log.Notice(Fmt("Starting RPC HTTP server on %s socket %v", proto, addr)) + log.Notice(fmt.Sprintf("Starting RPC HTTP server on %s socket %v", proto, addr)) listener, err = net.Listen(proto, addr) if err != nil { return nil, fmt.Errorf("Failed to listen to %v: %v", listenAddr, err) @@ -47,7 +45,7 @@ func StartHTTPServer(listenAddr string, handler http.Handler) (listener net.List return listener, nil } -func WriteRPCResponseHTTP(w http.ResponseWriter, res RPCResponse) { +func WriteRPCResponseHTTP(w http.ResponseWriter, res types.RPCResponse) { // jsonBytes := wire.JSONBytesPretty(res) jsonBytes, err := json.Marshal(res) if err != nil { @@ -83,13 +81,13 @@ func RecoverAndLogHandler(handler http.Handler) http.Handler { if e := recover(); e != nil { // If RPCResponse - if res, ok := e.(RPCResponse); ok { + if res, ok := e.(types.RPCResponse); ok { WriteRPCResponseHTTP(rww, res) } else { // For the rest, log.Error("Panic in RPC HTTP handler", "error", e, "stack", string(debug.Stack())) rww.WriteHeader(http.StatusInternalServerError) - WriteRPCResponseHTTP(rww, NewRPCResponse("", nil, Fmt("Internal Server Error: %v", e))) + WriteRPCResponseHTTP(rww, types.NewRPCResponse("", nil, fmt.Sprintf("Internal Server Error: %v", e))) } } From c128957723b151972ec65a3d3bf4e168ead09f1b Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Tue, 7 Mar 2017 19:09:58 +0400 Subject: [PATCH 088/309] "must remove file for test to run again" - no way I am doing this by hands, too lazy :) --- rpc_test.go | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/rpc_test.go b/rpc_test.go index c77799199..990122517 100644 --- a/rpc_test.go +++ b/rpc_test.go @@ -2,6 +2,7 @@ package rpc import ( "net/http" + "os/exec" "testing" "time" @@ -13,8 +14,10 @@ import ( // Client and Server should work over tcp or unix sockets const ( - tcpAddr = "tcp://0.0.0.0:46657" - unixAddr = "unix:///tmp/go-rpc.sock" // NOTE: must remove file for test to run again + tcpAddr = "tcp://0.0.0.0:46657" + + unixSocket = "/tmp/go-rpc.sock" + unixAddr = "unix:///tmp/go-rpc.sock" websocketEndpoint = "/websocket/endpoint" ) @@ -43,6 +46,12 @@ func StatusResult(v string) (Result, error) { // launch unix and tcp servers func init() { + cmd := exec.Command("rm", "-f", unixSocket) + err := cmd.Start() + if err != nil { + panic(err) + } + err = cmd.Wait() mux := http.NewServeMux() server.RegisterRPCFuncs(mux, Routes) From 26ccb4c94a0d214f4e1bd635b07c830620f5c6d5 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Tue, 7 Mar 2017 19:16:36 +0400 Subject: [PATCH 089/309] remove private call methods Q: what was the reason to create them? --- client/http_client.go | 8 -------- 1 file changed, 8 deletions(-) diff --git a/client/http_client.go b/client/http_client.go index c11f8b3e3..1585fd3b5 100644 --- a/client/http_client.go +++ b/client/http_client.go @@ -67,10 +67,6 @@ func NewClientJSONRPC(remote string) *ClientJSONRPC { } func (c *ClientJSONRPC) Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) { - return c.call(method, params, result) -} - -func (c *ClientJSONRPC) call(method string, params map[string]interface{}, result interface{}) (interface{}, error) { // Make request and get responseBytes request := types.RPCRequest{ JSONRPC: "2.0", @@ -114,10 +110,6 @@ func NewClientURI(remote string) *ClientURI { } func (c *ClientURI) Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) { - return c.call(method, params, result) -} - -func (c *ClientURI) call(method string, params map[string]interface{}, result interface{}) (interface{}, error) { values, err := argsToURLValues(params) if err != nil { return nil, err From d43e3db9789ba0baac1fbcbd3f9945c32ef4c9e0 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Tue, 7 Mar 2017 19:20:19 +0400 Subject: [PATCH 090/309] fix circleci --- Makefile | 2 +- circle.yml | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/Makefile b/Makefile index e17fa06ac..759c5cc09 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ PACKAGES=$(shell go list ./...) -all: test +all: get_deps test test: @echo "--> Running go test --race" diff --git a/circle.yml b/circle.yml index 99af678c6..0308a4e79 100644 --- a/circle.yml +++ b/circle.yml @@ -11,12 +11,10 @@ checkout: - rm -rf $REPO - mkdir -p $HOME/.go_workspace/src/github.com/$CIRCLE_PROJECT_USERNAME - mv $HOME/$CIRCLE_PROJECT_REPONAME $REPO - # - git submodule sync - # - git submodule update --init # use submodules dependencies: override: - - "cd $REPO" + - "cd $REPO && make get_deps" test: override: From 22ba8bdef81b246965469374fe0e3521124d0356 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Wed, 8 Mar 2017 10:26:13 +0400 Subject: [PATCH 091/309] fix Call method signature in HTTPClient interface --- client/http_client.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/client/http_client.go b/client/http_client.go index 1585fd3b5..3eb35aa3c 100644 --- a/client/http_client.go +++ b/client/http_client.go @@ -17,7 +17,7 @@ import ( // HTTPClient is a common interface for ClientJSONRPC and ClientURI. type HTTPClient interface { - Call(method string, params []interface{}, result interface{}) (interface{}, error) + Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) } // TODO: Deprecate support for IP:PORT or /path/to/socket From 51d760f29f4e54283498e2dec433d5a36e0e0814 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Wed, 8 Mar 2017 16:23:38 +0400 Subject: [PATCH 092/309] use local import for testing --- Makefile | 2 +- test/main.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 759c5cc09..a2e3bea7f 100644 --- a/Makefile +++ b/Makefile @@ -1,4 +1,4 @@ -PACKAGES=$(shell go list ./...) +PACKAGES=$(shell go list ./... | grep -v "test") all: get_deps test diff --git a/test/main.go b/test/main.go index 28de2be88..670e3deae 100644 --- a/test/main.go +++ b/test/main.go @@ -4,8 +4,8 @@ import ( "fmt" "net/http" + rpcserver "../server" cmn "github.com/tendermint/go-common" - rpcserver "github.com/tendermint/go-rpc/server" ) var routes = map[string]*rpcserver.RPCFunc{ From 6d66cc68ed17c50985c4bae24158d9dc7eb4d58e Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Wed, 8 Mar 2017 16:24:04 +0400 Subject: [PATCH 093/309] make sure we are using correct server also remove it afterwards --- test/integration_test.sh | 32 ++++++++++++++++++++++---------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/test/integration_test.sh b/test/integration_test.sh index 739708068..5c85704be 100755 --- a/test/integration_test.sh +++ b/test/integration_test.sh @@ -9,12 +9,19 @@ DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" # Change into that dir because we expect that. pushd "$DIR" -go build -o server main.go -./server > /dev/null & +echo "==> Building the server" +go build -o rpcserver main.go + +echo "==> (Re)starting the server" +PID=$(pgrep rpcserver || echo "") +if [[ $PID != "" ]]; then + kill -9 "$PID" +fi +./rpcserver & PID=$! sleep 2 -# simple request +echo "==> simple request" R1=$(curl -s 'http://localhost:8008/hello_world?name="my_world"&num=5') R2=$(curl -s --data @data.json http://localhost:8008) if [[ "$R1" != "$R2" ]]; then @@ -23,10 +30,10 @@ if [[ "$R1" != "$R2" ]]; then echo "R2: $R2" exit 1 else - echo "Success" + echo "OK" fi -# request with 0x-prefixed hex string arg +echo "==> request with 0x-prefixed hex string arg" R1=$(curl -s 'http://localhost:8008/hello_world?name=0x41424344&num=123') R2='{"jsonrpc":"2.0","id":"","result":{"Result":"hi ABCD 123"},"error":""}' if [[ "$R1" != "$R2" ]]; then @@ -35,7 +42,7 @@ if [[ "$R1" != "$R2" ]]; then echo "R2: $R2" exit 1 else - echo "Success" + echo "OK" fi # request with unquoted string arg @@ -47,10 +54,10 @@ if [[ "$R1" != "$R2" ]]; then echo "R2: $R2" exit 1 else - echo "Success" + echo "OK" fi -# request with string type when expecting number arg +echo "==> request with string type when expecting number arg" R1=$(curl -s 'http://localhost:8008/hello_world?name="abcd"&num=0xabcd') R2="{\"jsonrpc\":\"2.0\",\"id\":\"\",\"result\":null,\"error\":\"Error converting http params to args: Got a hex string arg, but expected 'int'\"}" if [[ "$R1" != "$R2" ]]; then @@ -59,8 +66,13 @@ if [[ "$R1" != "$R2" ]]; then echo "R2: $R2" exit 1 else - echo "Success" + echo "OK" fi -kill -9 $PID || exit 0 +echo "==> Stopping the server" +kill -9 $PID + +rm -f rpcserver + popd +exit 0 From 2dc6ab3896e876d7ec2371b3faa6112971e9e849 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Wed, 8 Mar 2017 17:16:01 +0400 Subject: [PATCH 094/309] use golang default if an arg is missing (Refs #7) --- server/handlers.go | 54 +++++++++++++++++++++++----------------- test/integration_test.sh | 19 +++++++++++++- 2 files changed, 49 insertions(+), 24 deletions(-) diff --git a/server/handlers.go b/server/handlers.go index beb664d9f..7085b81e2 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -141,20 +141,20 @@ func makeJSONRPCHandler(funcMap map[string]*RPCFunc) http.HandlerFunc { // Convert a list of interfaces to properly typed values func jsonParamsToArgs(rpcFunc *RPCFunc, params map[string]interface{}) ([]reflect.Value, error) { - if len(rpcFunc.argNames) != len(params) { - return nil, fmt.Errorf("Expected %v parameters (%v), got %v (%v)", - len(rpcFunc.argNames), rpcFunc.argNames, len(params), params) - } + values := make([]reflect.Value, len(rpcFunc.args)) - values := make([]reflect.Value, len(params)) + // fill each value with default + for i, argType := range rpcFunc.args { + values[i] = reflect.Zero(argType) + } for name, param := range params { i := indexOf(name, rpcFunc.argNames) if -1 == i { return nil, fmt.Errorf("%s is not an argument (args: %v)", name, rpcFunc.argNames) } - ty := rpcFunc.args[i] - v, err := _jsonObjectToArg(ty, param) + argType := rpcFunc.args[i] + v, err := _jsonObjectToArg(argType, param) if err != nil { return nil, err } @@ -176,21 +176,21 @@ func indexOf(value string, values []string) int { // Same as above, but with the first param the websocket connection func jsonParamsToArgsWS(rpcFunc *RPCFunc, params map[string]interface{}, wsCtx types.WSRPCContext) ([]reflect.Value, error) { - if len(rpcFunc.argNames) != len(params) { - return nil, fmt.Errorf("Expected %v parameters (%v), got %v (%v)", - len(rpcFunc.argNames)-1, rpcFunc.argNames[1:], len(params), params) - } - - values := make([]reflect.Value, len(params)+1) + values := make([]reflect.Value, len(rpcFunc.args)) values[0] = reflect.ValueOf(wsCtx) + // fill each value with default + for i, argType := range rpcFunc.args { + values[i+1] = reflect.Zero(argType) + } + for name, param := range params { i := indexOf(name, rpcFunc.argNames) if -1 == i { return nil, fmt.Errorf("%s is not an argument (args: %v)", name, rpcFunc.argNames) } - ty := rpcFunc.args[i+1] - v, err := _jsonObjectToArg(ty, param) + argType := rpcFunc.args[i+1] + v, err := _jsonObjectToArg(argType, param) if err != nil { return nil, err } @@ -245,16 +245,23 @@ func makeHTTPHandler(rpcFunc *RPCFunc) func(http.ResponseWriter, *http.Request) // Covert an http query to a list of properly typed values. // To be properly decoded the arg must be a concrete type from tendermint (if its an interface). func httpParamsToArgs(rpcFunc *RPCFunc, r *http.Request) ([]reflect.Value, error) { - argTypes := rpcFunc.args - argNames := rpcFunc.argNames + values := make([]reflect.Value, len(rpcFunc.args)) - values := make([]reflect.Value, len(argNames)) - for i, name := range argNames { - ty := argTypes[i] + // fill each value with default + for i, argType := range rpcFunc.args { + values[i] = reflect.Zero(argType) + } + + for i, name := range rpcFunc.argNames { + argType := rpcFunc.args[i] arg := GetParam(r, name) - // log.Notice("param to arg", "ty", ty, "name", name, "arg", arg) + // log.Notice("param to arg", "argType", argType, "name", name, "arg", arg) - v, err, ok := nonJsonToArg(ty, arg) + if "" == arg { + continue + } + + v, err, ok := nonJsonToArg(argType, arg) if err != nil { return nil, err } @@ -264,11 +271,12 @@ func httpParamsToArgs(rpcFunc *RPCFunc, r *http.Request) ([]reflect.Value, error } // Pass values to go-wire - values[i], err = _jsonStringToArg(ty, arg) + values[i], err = _jsonStringToArg(argType, arg) if err != nil { return nil, err } } + return values, nil } diff --git a/test/integration_test.sh b/test/integration_test.sh index 5c85704be..ea246c896 100755 --- a/test/integration_test.sh +++ b/test/integration_test.sh @@ -28,6 +28,7 @@ if [[ "$R1" != "$R2" ]]; then echo "responses are not identical:" echo "R1: $R1" echo "R2: $R2" + echo "FAIL" exit 1 else echo "OK" @@ -40,18 +41,33 @@ if [[ "$R1" != "$R2" ]]; then echo "responses are not identical:" echo "R1: $R1" echo "R2: $R2" + echo "FAIL" exit 1 else echo "OK" fi -# request with unquoted string arg +echo "==> request with missing params" +R1=$(curl -s 'http://localhost:8008/hello_world') +R2='{"jsonrpc":"2.0","id":"","result":{"Result":"hi 0"},"error":""}' +if [[ "$R1" != "$R2" ]]; then + echo "responses are not identical:" + echo "R1: $R1" + echo "R2: $R2" + echo "FAIL" + exit 1 +else + echo "OK" +fi + +echo "==> request with unquoted string arg" R1=$(curl -s 'http://localhost:8008/hello_world?name=abcd&num=123') R2="{\"jsonrpc\":\"2.0\",\"id\":\"\",\"result\":null,\"error\":\"Error converting http params to args: invalid character 'a' looking for beginning of value\"}" if [[ "$R1" != "$R2" ]]; then echo "responses are not identical:" echo "R1: $R1" echo "R2: $R2" + echo "FAIL" exit 1 else echo "OK" @@ -64,6 +80,7 @@ if [[ "$R1" != "$R2" ]]; then echo "responses are not identical:" echo "R1: $R1" echo "R2: $R2" + echo "FAIL" exit 1 else echo "OK" From d033cd54b8c48a5621bbe8fa67833612643fb7d4 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Wed, 8 Mar 2017 17:17:00 +0400 Subject: [PATCH 095/309] add editorconfig --- .editorconfig | 15 +++++++++++++++ test/integration_test.sh | 12 ++++++------ 2 files changed, 21 insertions(+), 6 deletions(-) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 000000000..d587999e1 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,15 @@ +# top-most EditorConfig file +root = true + +# Unix-style newlines with a newline ending every file +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true + +[Makefile] +indent_style = tab + +[*.sh] +indent_style = tab diff --git a/test/integration_test.sh b/test/integration_test.sh index ea246c896..7c23be7d3 100755 --- a/test/integration_test.sh +++ b/test/integration_test.sh @@ -15,7 +15,7 @@ go build -o rpcserver main.go echo "==> (Re)starting the server" PID=$(pgrep rpcserver || echo "") if [[ $PID != "" ]]; then - kill -9 "$PID" + kill -9 "$PID" fi ./rpcserver & PID=$! @@ -51,13 +51,13 @@ echo "==> request with missing params" R1=$(curl -s 'http://localhost:8008/hello_world') R2='{"jsonrpc":"2.0","id":"","result":{"Result":"hi 0"},"error":""}' if [[ "$R1" != "$R2" ]]; then - echo "responses are not identical:" - echo "R1: $R1" - echo "R2: $R2" + echo "responses are not identical:" + echo "R1: $R1" + echo "R2: $R2" echo "FAIL" - exit 1 + exit 1 else - echo "OK" + echo "OK" fi echo "==> request with unquoted string arg" From 1842e03315833fd61c070ba7ba13fd5bbf51e42b Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Wed, 8 Mar 2017 17:33:46 +0400 Subject: [PATCH 096/309] revert using local import this breaks the client's code (e.g. tendermint) --- test/main.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/main.go b/test/main.go index 670e3deae..28de2be88 100644 --- a/test/main.go +++ b/test/main.go @@ -4,8 +4,8 @@ import ( "fmt" "net/http" - rpcserver "../server" cmn "github.com/tendermint/go-common" + rpcserver "github.com/tendermint/go-rpc/server" ) var routes = map[string]*rpcserver.RPCFunc{ From fed84f875cfc59a22dfe98e68b93e1fb5151fef9 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Wed, 8 Mar 2017 17:55:08 +0400 Subject: [PATCH 097/309] fix jsonParamsToArgsWS index error Error from tendermint: ``` panic: runtime error: index out of range goroutine 82 [running]: github.com/tendermint/tendermint/vendor/github.com/tendermint/go-rpc/server.jsonParamsToArgsWS(0xc4200960e0, 0xc42024d4a0, 0xc420215380, 0x3, 0x0, 0x0, 0xc420215383, 0x9, 0xc42024d4a0, 0xf1ecc0, ...) /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-rpc/server/handlers.go:184 +0x654 github.com/tendermint/tendermint/vendor/github.com/tendermint/go-rpc/server.(*wsConnection).readRoutine(0xc4201fd0e0) /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-rpc/server/handlers.go:496 +0x3a9 created by github.com/tendermint/tendermint/vendor/github.com/tendermint/go-rpc/server.(*wsConnection).OnStart /home/vagrant/go/src/github.com/tendermint/tendermint/vendor/github.com/tendermint/go-rpc/server/handlers.go:377 +0x45 ``` --- server/handlers.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server/handlers.go b/server/handlers.go index 7085b81e2..2a6102d1e 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -176,7 +176,7 @@ func indexOf(value string, values []string) int { // Same as above, but with the first param the websocket connection func jsonParamsToArgsWS(rpcFunc *RPCFunc, params map[string]interface{}, wsCtx types.WSRPCContext) ([]reflect.Value, error) { - values := make([]reflect.Value, len(rpcFunc.args)) + values := make([]reflect.Value, len(rpcFunc.args)+1) values[0] = reflect.ValueOf(wsCtx) // fill each value with default @@ -189,7 +189,7 @@ func jsonParamsToArgsWS(rpcFunc *RPCFunc, params map[string]interface{}, wsCtx t if -1 == i { return nil, fmt.Errorf("%s is not an argument (args: %v)", name, rpcFunc.argNames) } - argType := rpcFunc.args[i+1] + argType := rpcFunc.args[i] v, err := _jsonObjectToArg(argType, param) if err != nil { return nil, err From 1ddb60b6e73b2bb5c2d1845eaa763e0a8ad57855 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Thu, 9 Mar 2017 12:23:21 +0400 Subject: [PATCH 098/309] refactor jsonParamsToArgs Suggested in https://github.com/tendermint/go-rpc/pull/9#discussion_r105098390 --- server/handlers.go | 68 ++++++++++++---------------------------------- 1 file changed, 18 insertions(+), 50 deletions(-) diff --git a/server/handlers.go b/server/handlers.go index 2a6102d1e..6e746a26b 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -143,61 +143,31 @@ func makeJSONRPCHandler(funcMap map[string]*RPCFunc) http.HandlerFunc { func jsonParamsToArgs(rpcFunc *RPCFunc, params map[string]interface{}) ([]reflect.Value, error) { values := make([]reflect.Value, len(rpcFunc.args)) - // fill each value with default - for i, argType := range rpcFunc.args { - values[i] = reflect.Zero(argType) - } - - for name, param := range params { - i := indexOf(name, rpcFunc.argNames) - if -1 == i { - return nil, fmt.Errorf("%s is not an argument (args: %v)", name, rpcFunc.argNames) - } + for i, argName := range rpcFunc.argNames { argType := rpcFunc.args[i] - v, err := _jsonObjectToArg(argType, param) - if err != nil { - return nil, err + + // decode param if provided + if param, ok := params[argName]; ok && "" != param { + v, err := _jsonObjectToArg(argType, param) + if err != nil { + return nil, err + } + values[i] = v + } else { // use default for that type + values[i] = reflect.Zero(argType) } - values[i] = v } return values, nil } -// indexOf returns index of a string in a slice of strings, -1 if not found. -func indexOf(value string, values []string) int { - for i, v := range values { - if v == value { - return i - } - } - return -1 -} - // Same as above, but with the first param the websocket connection func jsonParamsToArgsWS(rpcFunc *RPCFunc, params map[string]interface{}, wsCtx types.WSRPCContext) ([]reflect.Value, error) { - values := make([]reflect.Value, len(rpcFunc.args)+1) - values[0] = reflect.ValueOf(wsCtx) - - // fill each value with default - for i, argType := range rpcFunc.args { - values[i+1] = reflect.Zero(argType) + values, err := jsonParamsToArgs(rpcFunc, params) + if err != nil { + return nil, err } - - for name, param := range params { - i := indexOf(name, rpcFunc.argNames) - if -1 == i { - return nil, fmt.Errorf("%s is not an argument (args: %v)", name, rpcFunc.argNames) - } - argType := rpcFunc.args[i] - v, err := _jsonObjectToArg(argType, param) - if err != nil { - return nil, err - } - values[i+1] = v - } - - return values, nil + return append([]reflect.Value{reflect.ValueOf(wsCtx)}, values...), nil } func _jsonObjectToArg(ty reflect.Type, object interface{}) (reflect.Value, error) { @@ -247,13 +217,11 @@ func makeHTTPHandler(rpcFunc *RPCFunc) func(http.ResponseWriter, *http.Request) func httpParamsToArgs(rpcFunc *RPCFunc, r *http.Request) ([]reflect.Value, error) { values := make([]reflect.Value, len(rpcFunc.args)) - // fill each value with default - for i, argType := range rpcFunc.args { - values[i] = reflect.Zero(argType) - } - for i, name := range rpcFunc.argNames { argType := rpcFunc.args[i] + + values[i] = reflect.Zero(argType) // set default for that type + arg := GetParam(r, name) // log.Notice("param to arg", "argType", argType, "name", name, "arg", arg) From cf11e6ba65423f81b9db3bc2550303d1a325e8ae Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Thu, 9 Mar 2017 12:43:24 +0400 Subject: [PATCH 099/309] add CHANGELOG --- README.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/README.md b/README.md index 4da0e5634..149ecdf51 100644 --- a/README.md +++ b/README.md @@ -109,3 +109,18 @@ Each route is available as a GET request, as a JSONRPCv2 POST request, and via J * [Tendermint](https://github.com/tendermint/tendermint/blob/master/rpc/core/routes.go) * [Network Monitor](https://github.com/tendermint/netmon/blob/master/handlers/routes.go) + +## CHANGELOG + +### 0.7.0 + +BREAKING CHANGES: + +- removed `Client` empty interface +- `ClientJSONRPC#Call` `params` argument became a map + +IMPROVEMENTS: + +- added `HTTPClient` interface, which can be used for both `ClientURI` +and `ClientJSONRPC` +- all params are now optional (Golang's default will be used if some param is missing) From 05e1a22d5b6e91c9c00b0824f4f95e0efd0a34da Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Thu, 9 Mar 2017 13:46:48 +0400 Subject: [PATCH 100/309] encode params before sending in JSONRPC --- client/http_client.go | 9 +++++++-- rpc_test.go | 41 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 2 deletions(-) diff --git a/client/http_client.go b/client/http_client.go index 3eb35aa3c..960869b75 100644 --- a/client/http_client.go +++ b/client/http_client.go @@ -67,11 +67,16 @@ func NewClientJSONRPC(remote string) *ClientJSONRPC { } func (c *ClientJSONRPC) Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) { - // Make request and get responseBytes + // we need this step because we attempt to decode values using `go-wire` + // (handlers.go:176) on the server side + encodedParams := make(map[string]interface{}) + for k, v := range params { + encodedParams[k] = json.RawMessage(wire.JSONBytes(v)) + } request := types.RPCRequest{ JSONRPC: "2.0", Method: method, - Params: params, + Params: encodedParams, ID: "", } requestBytes, err := json.Marshal(request) diff --git a/rpc_test.go b/rpc_test.go index 990122517..a719aee55 100644 --- a/rpc_test.go +++ b/rpc_test.go @@ -1,6 +1,9 @@ package rpc import ( + "bytes" + crand "crypto/rand" + "math/rand" "net/http" "os/exec" "testing" @@ -29,14 +32,20 @@ type ResultStatus struct { Value string } +type ResultBytes struct { + Value []byte +} + var _ = wire.RegisterInterface( struct{ Result }{}, wire.ConcreteType{&ResultStatus{}, 0x1}, + wire.ConcreteType{&ResultBytes{}, 0x2}, ) // Define some routes var Routes = map[string]*server.RPCFunc{ "status": server.NewRPCFunc(StatusResult, "arg"), + "bytes": server.NewRPCFunc(BytesResult, "arg"), } // an rpc function @@ -44,6 +53,10 @@ func StatusResult(v string) (Result, error) { return &ResultStatus{v}, nil } +func BytesResult(v []byte) (Result, error) { + return &ResultBytes{v}, nil +} + // launch unix and tcp servers func init() { cmd := exec.Command("rm", "-f", unixSocket) @@ -214,3 +227,31 @@ func TestQuotedStringArg(t *testing.T) { t.Fatalf("Got: %v .... Expected: %v \n", got, val) } } + +func randBytes(t *testing.T) []byte { + n := rand.Intn(10) + 2 + buf := make([]byte, n) + _, err := crand.Read(buf) + if err != nil { + t.Fatal(err) + } + return bytes.Replace(buf, []byte("="), []byte{100}, -1) +} + +func TestByteSliceViaJSONRPC(t *testing.T) { + cl := client.NewClientJSONRPC(unixAddr) + + val := randBytes(t) + params := map[string]interface{}{ + "arg": val, + } + var result Result + _, err := cl.Call("bytes", params, &result) + if err != nil { + t.Fatal(err) + } + got := result.(*ResultBytes).Value + if bytes.Compare(got, val) != 0 { + t.Fatalf("Got: %v .... Expected: %v \n", got, val) + } +} From 720b74d89edd0b9e7406e7b4557352448b4c0c16 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Thu, 9 Mar 2017 17:44:00 +0400 Subject: [PATCH 101/309] read from ErrorsCh also --- rpc_test.go | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/rpc_test.go b/rpc_test.go index a719aee55..074c212a8 100644 --- a/rpc_test.go +++ b/rpc_test.go @@ -140,16 +140,20 @@ func testWS(t *testing.T, cl *client.WSClient) { t.Fatal(err) } - msg := <-cl.ResultsCh - result := new(Result) - wire.ReadJSONPtr(result, msg, &err) - if err != nil { + select { + case msg := <-cl.ResultsCh: + result := new(Result) + wire.ReadJSONPtr(result, msg, &err) + if err != nil { + t.Fatal(err) + } + got := (*result).(*ResultStatus).Value + if got != val { + t.Fatalf("Got: %v .... Expected: %v \n", got, val) + } + case err := <-cl.ErrorsCh: t.Fatal(err) } - got := (*result).(*ResultStatus).Value - if got != val { - t.Fatalf("Got: %v .... Expected: %v \n", got, val) - } } //------------- From ff90224ba8166ebb2df545af44f3f832ac3452c5 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Thu, 9 Mar 2017 18:30:55 +0400 Subject: [PATCH 102/309] fix "Expected map but got type string" error Error from tendermint: ``` panic: Expected map but got type string [recovered] panic: Expected map but got type string goroutine 82 [running]: testing.tRunner.func1(0xc420464000) /usr/local/go/src/testing/testing.go:622 +0x29d panic(0xa1fda0, 0xc4201eecd0) /usr/local/go/src/runtime/panic.go:489 +0x2cf github.com/tendermint/tendermint/rpc/test.waitForEvent(0xc420464000, 0xc420064000, 0xae6fae, 0x8, 0xae6f01, 0xc2e998, 0xc2e9a0) /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/test/helpers.go:179 +0x53a github.com/tendermint/tendermint/rpc/test.TestWSNewBlock(0xc420464000) /home/vagrant/go/src/github.com/tendermint/tendermint/rpc/test/client_test.go:190 +0x12e testing.tRunner(0xc420464000, 0xc2e9a8) /usr/local/go/src/testing/testing.go:657 +0x96 created by testing.(*T).Run /usr/local/go/src/testing/testing.go:697 +0x2ca ``` --- rpc_test.go | 47 ++++++++++++++++++++++++++++++++++++++++++++-- server/handlers.go | 17 +++++++++++------ 2 files changed, 56 insertions(+), 8 deletions(-) diff --git a/rpc_test.go b/rpc_test.go index 074c212a8..334909f1f 100644 --- a/rpc_test.go +++ b/rpc_test.go @@ -44,8 +44,9 @@ var _ = wire.RegisterInterface( // Define some routes var Routes = map[string]*server.RPCFunc{ - "status": server.NewRPCFunc(StatusResult, "arg"), - "bytes": server.NewRPCFunc(BytesResult, "arg"), + "status": server.NewRPCFunc(StatusResult, "arg"), + "status_ws": server.NewWSRPCFunc(StatusWSResult, "arg"), + "bytes": server.NewRPCFunc(BytesResult, "arg"), } // an rpc function @@ -53,6 +54,10 @@ func StatusResult(v string) (Result, error) { return &ResultStatus{v}, nil } +func StatusWSResult(wsCtx types.WSRPCContext, v string) (Result, error) { + return &ResultStatus{v}, nil +} + func BytesResult(v []byte) (Result, error) { return &ResultBytes{v}, nil } @@ -259,3 +264,41 @@ func TestByteSliceViaJSONRPC(t *testing.T) { t.Fatalf("Got: %v .... Expected: %v \n", got, val) } } + +func TestWSNewWSRPCFunc(t *testing.T) { + cl := client.NewWSClient(unixAddr, websocketEndpoint) + _, err := cl.Start() + if err != nil { + t.Fatal(err) + } + defer cl.Stop() + + val := "acbd" + params := map[string]interface{}{ + "arg": val, + } + err = cl.WriteJSON(types.RPCRequest{ + JSONRPC: "2.0", + ID: "", + Method: "status_ws", + Params: params, + }) + if err != nil { + t.Fatal(err) + } + + select { + case msg := <-cl.ResultsCh: + result := new(Result) + wire.ReadJSONPtr(result, msg, &err) + if err != nil { + t.Fatal(err) + } + got := (*result).(*ResultStatus).Value + if got != val { + t.Fatalf("Got: %v .... Expected: %v \n", got, val) + } + case err := <-cl.ErrorsCh: + t.Fatal(err) + } +} diff --git a/server/handlers.go b/server/handlers.go index 6e746a26b..e590a45fd 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -123,7 +123,7 @@ func makeJSONRPCHandler(funcMap map[string]*RPCFunc) http.HandlerFunc { WriteRPCResponseHTTP(w, types.NewRPCResponse(request.ID, nil, "RPC method is only for websockets: "+request.Method)) return } - args, err := jsonParamsToArgs(rpcFunc, request.Params) + args, err := jsonParamsToArgs(rpcFunc, request.Params, 0) if err != nil { WriteRPCResponseHTTP(w, types.NewRPCResponse(request.ID, nil, fmt.Sprintf("Error converting json params to arguments: %v", err.Error()))) return @@ -140,11 +140,16 @@ func makeJSONRPCHandler(funcMap map[string]*RPCFunc) http.HandlerFunc { } // Convert a list of interfaces to properly typed values -func jsonParamsToArgs(rpcFunc *RPCFunc, params map[string]interface{}) ([]reflect.Value, error) { - values := make([]reflect.Value, len(rpcFunc.args)) +// +// argsOffset is used in jsonParamsToArgsWS, where len(rpcFunc.args) != len(rpcFunc.argNames). +// Example: +// rpcFunc.args = [rpctypes.WSRPCContext string] +// rpcFunc.argNames = ["arg"] +func jsonParamsToArgs(rpcFunc *RPCFunc, params map[string]interface{}, argsOffset int) ([]reflect.Value, error) { + values := make([]reflect.Value, len(rpcFunc.argNames)) for i, argName := range rpcFunc.argNames { - argType := rpcFunc.args[i] + argType := rpcFunc.args[i+argsOffset] // decode param if provided if param, ok := params[argName]; ok && "" != param { @@ -163,7 +168,7 @@ func jsonParamsToArgs(rpcFunc *RPCFunc, params map[string]interface{}) ([]reflec // Same as above, but with the first param the websocket connection func jsonParamsToArgsWS(rpcFunc *RPCFunc, params map[string]interface{}, wsCtx types.WSRPCContext) ([]reflect.Value, error) { - values, err := jsonParamsToArgs(rpcFunc, params) + values, err := jsonParamsToArgs(rpcFunc, params, 1) if err != nil { return nil, err } @@ -463,7 +468,7 @@ func (wsc *wsConnection) readRoutine() { wsCtx := types.WSRPCContext{Request: request, WSRPCConnection: wsc} args, err = jsonParamsToArgsWS(rpcFunc, request.Params, wsCtx) } else { - args, err = jsonParamsToArgs(rpcFunc, request.Params) + args, err = jsonParamsToArgs(rpcFunc, request.Params, 0) } if err != nil { wsc.WriteRPCResponse(types.NewRPCResponse(request.ID, nil, err.Error())) From db69845ded7b5e61d0ea49f58430b7f27e084ed6 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Thu, 9 Mar 2017 19:00:05 +0400 Subject: [PATCH 103/309] introduce errors pkg --- client/http_client.go | 7 ++++--- client/ws_client.go | 4 ++-- server/handlers.go | 5 +++-- server/http_params.go | 15 ++++++++------- server/http_server.go | 5 +++-- 5 files changed, 20 insertions(+), 16 deletions(-) diff --git a/client/http_client.go b/client/http_client.go index 960869b75..7df09f249 100644 --- a/client/http_client.go +++ b/client/http_client.go @@ -11,6 +11,7 @@ import ( "reflect" "strings" + "github.com/pkg/errors" types "github.com/tendermint/go-rpc/types" wire "github.com/tendermint/go-wire" ) @@ -143,16 +144,16 @@ func unmarshalResponseBytes(responseBytes []byte, result interface{}) (interface response := &types.RPCResponse{} err = json.Unmarshal(responseBytes, response) if err != nil { - return nil, fmt.Errorf("Error unmarshalling rpc response: %v", err) + return nil, errors.Errorf("Error unmarshalling rpc response: %v", err) } errorStr := response.Error if errorStr != "" { - return nil, fmt.Errorf("Response error: %v", errorStr) + return nil, errors.Errorf("Response error: %v", errorStr) } // unmarshal the RawMessage into the result result = wire.ReadJSONPtr(result, *response.Result, &err) if err != nil { - return nil, fmt.Errorf("Error unmarshalling rpc response result: %v", err) + return nil, errors.Errorf("Error unmarshalling rpc response result: %v", err) } return result, nil } diff --git a/client/ws_client.go b/client/ws_client.go index d27e499dd..b56547dd6 100644 --- a/client/ws_client.go +++ b/client/ws_client.go @@ -2,12 +2,12 @@ package rpcclient import ( "encoding/json" - "fmt" "net" "net/http" "time" "github.com/gorilla/websocket" + "github.com/pkg/errors" cmn "github.com/tendermint/go-common" types "github.com/tendermint/go-rpc/types" ) @@ -104,7 +104,7 @@ func (wsc *WSClient) receiveEventsRoutine() { continue } if response.Error != "" { - wsc.ErrorsCh <- fmt.Errorf(response.Error) + wsc.ErrorsCh <- errors.Errorf(response.Error) continue } wsc.ResultsCh <- *response.Result diff --git a/server/handlers.go b/server/handlers.go index e590a45fd..ca42b2e67 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -13,6 +13,7 @@ import ( "time" "github.com/gorilla/websocket" + "github.com/pkg/errors" cmn "github.com/tendermint/go-common" events "github.com/tendermint/go-events" types "github.com/tendermint/go-rpc/types" @@ -272,7 +273,7 @@ func nonJsonToArg(ty reflect.Type, arg string) (reflect.Value, error, bool) { if isHexString { if !expectingString && !expectingByteSlice { - err := fmt.Errorf("Got a hex string arg, but expected '%s'", + err := errors.Errorf("Got a hex string arg, but expected '%s'", ty.Kind().String()) return reflect.ValueOf(nil), err, false } @@ -567,7 +568,7 @@ func (wm *WebsocketManager) WebsocketHandler(w http.ResponseWriter, r *http.Requ func unreflectResult(returns []reflect.Value) (interface{}, error) { errV := returns[1] if errV.Interface() != nil { - return nil, fmt.Errorf("%v", errV.Interface()) + return nil, errors.Errorf("%v", errV.Interface()) } rv := returns[0] // the result is a registered interface, diff --git a/server/http_params.go b/server/http_params.go index acf5b4c8c..565060678 100644 --- a/server/http_params.go +++ b/server/http_params.go @@ -2,10 +2,11 @@ package rpcserver import ( "encoding/hex" - "fmt" "net/http" "regexp" "strconv" + + "github.com/pkg/errors" ) var ( @@ -39,7 +40,7 @@ func GetParamInt64(r *http.Request, param string) (int64, error) { s := GetParam(r, param) i, err := strconv.ParseInt(s, 10, 64) if err != nil { - return 0, fmt.Errorf(param, err.Error()) + return 0, errors.Errorf(param, err.Error()) } return i, nil } @@ -48,7 +49,7 @@ func GetParamInt32(r *http.Request, param string) (int32, error) { s := GetParam(r, param) i, err := strconv.ParseInt(s, 10, 32) if err != nil { - return 0, fmt.Errorf(param, err.Error()) + return 0, errors.Errorf(param, err.Error()) } return int32(i), nil } @@ -57,7 +58,7 @@ func GetParamUint64(r *http.Request, param string) (uint64, error) { s := GetParam(r, param) i, err := strconv.ParseUint(s, 10, 64) if err != nil { - return 0, fmt.Errorf(param, err.Error()) + return 0, errors.Errorf(param, err.Error()) } return i, nil } @@ -66,7 +67,7 @@ func GetParamUint(r *http.Request, param string) (uint, error) { s := GetParam(r, param) i, err := strconv.ParseUint(s, 10, 64) if err != nil { - return 0, fmt.Errorf(param, err.Error()) + return 0, errors.Errorf(param, err.Error()) } return uint(i), nil } @@ -74,7 +75,7 @@ func GetParamUint(r *http.Request, param string) (uint, error) { func GetParamRegexp(r *http.Request, param string, re *regexp.Regexp) (string, error) { s := GetParam(r, param) if !re.MatchString(s) { - return "", fmt.Errorf(param, "Did not match regular expression %v", re.String()) + return "", errors.Errorf(param, "Did not match regular expression %v", re.String()) } return s, nil } @@ -83,7 +84,7 @@ func GetParamFloat64(r *http.Request, param string) (float64, error) { s := GetParam(r, param) f, err := strconv.ParseFloat(s, 64) if err != nil { - return 0, fmt.Errorf(param, err.Error()) + return 0, errors.Errorf(param, err.Error()) } return f, nil } diff --git a/server/http_server.go b/server/http_server.go index 24b9f18af..5375c574f 100644 --- a/server/http_server.go +++ b/server/http_server.go @@ -11,6 +11,7 @@ import ( "strings" "time" + "github.com/pkg/errors" types "github.com/tendermint/go-rpc/types" ) @@ -24,7 +25,7 @@ func StartHTTPServer(listenAddr string, handler http.Handler) (listener net.List // TODO: Deprecate proto = types.SocketType(listenAddr) addr = listenAddr - // return nil, fmt.Errorf("Invalid listener address %s", lisenAddr) + // return nil, errors.Errorf("Invalid listener address %s", lisenAddr) } else { proto, addr = parts[0], parts[1] } @@ -32,7 +33,7 @@ func StartHTTPServer(listenAddr string, handler http.Handler) (listener net.List log.Notice(fmt.Sprintf("Starting RPC HTTP server on %s socket %v", proto, addr)) listener, err = net.Listen(proto, addr) if err != nil { - return nil, fmt.Errorf("Failed to listen to %v: %v", listenAddr, err) + return nil, errors.Errorf("Failed to listen to %v: %v", listenAddr, err) } go func() { From 715f78e26a2d64ab52569867e0fd8b3bc7a4256f Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Thu, 9 Mar 2017 21:00:25 +0100 Subject: [PATCH 104/309] Properly encode json.RawMessage --- client/http_client.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/client/http_client.go b/client/http_client.go index 7df09f249..5030323b5 100644 --- a/client/http_client.go +++ b/client/http_client.go @@ -72,7 +72,9 @@ func (c *ClientJSONRPC) Call(method string, params map[string]interface{}, resul // (handlers.go:176) on the server side encodedParams := make(map[string]interface{}) for k, v := range params { - encodedParams[k] = json.RawMessage(wire.JSONBytes(v)) + // log.Printf("%s: %v (%s)\n", k, v, string(wire.JSONBytes(v))) + bytes := json.RawMessage(wire.JSONBytes(v)) + encodedParams[k] = &bytes } request := types.RPCRequest{ JSONRPC: "2.0", @@ -84,6 +86,7 @@ func (c *ClientJSONRPC) Call(method string, params map[string]interface{}, resul if err != nil { return nil, err } + // log.Info(string(requestBytes)) requestBuf := bytes.NewBuffer(requestBytes) // log.Info(Fmt("RPC request to %v (%v): %v", c.remote, method, string(requestBytes))) httpResponse, err := c.client.Post(c.address, "text/json", requestBuf) From e6c083f589d93d5cada7c5e9fff1c3c05873a167 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Wed, 8 Mar 2017 01:22:35 +0400 Subject: [PATCH 105/309] rename ClientURI -> URIClient, ClientJSONRPC -> JSONRPCClient (Refs #4) --- README.md | 1 + client/http_client.go | 18 +++++++++--------- rpc_test.go | 18 +++++++++--------- 3 files changed, 19 insertions(+), 18 deletions(-) diff --git a/README.md b/README.md index 149ecdf51..06a679032 100644 --- a/README.md +++ b/README.md @@ -118,6 +118,7 @@ BREAKING CHANGES: - removed `Client` empty interface - `ClientJSONRPC#Call` `params` argument became a map +- rename `ClientURI` -> `URIClient`, `ClientJSONRPC` -> `JSONRPCClient` IMPROVEMENTS: diff --git a/client/http_client.go b/client/http_client.go index 5030323b5..96bae9d9b 100644 --- a/client/http_client.go +++ b/client/http_client.go @@ -16,7 +16,7 @@ import ( wire "github.com/tendermint/go-wire" ) -// HTTPClient is a common interface for ClientJSONRPC and ClientURI. +// HTTPClient is a common interface for JSONRPCClient and URIClient. type HTTPClient interface { Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) } @@ -54,20 +54,20 @@ func makeHTTPClient(remoteAddr string) (string, *http.Client) { //------------------------------------------------------------------------------------ // JSON rpc takes params as a slice -type ClientJSONRPC struct { +type JSONRPCClient struct { address string client *http.Client } -func NewClientJSONRPC(remote string) *ClientJSONRPC { +func NewJSONRPCClient(remote string) *JSONRPCClient { address, client := makeHTTPClient(remote) - return &ClientJSONRPC{ + return &JSONRPCClient{ address: address, client: client, } } -func (c *ClientJSONRPC) Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) { +func (c *JSONRPCClient) Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) { // we need this step because we attempt to decode values using `go-wire` // (handlers.go:176) on the server side encodedParams := make(map[string]interface{}) @@ -105,20 +105,20 @@ func (c *ClientJSONRPC) Call(method string, params map[string]interface{}, resul //------------------------------------------------------------- // URI takes params as a map -type ClientURI struct { +type URIClient struct { address string client *http.Client } -func NewClientURI(remote string) *ClientURI { +func NewURIClient(remote string) *URIClient { address, client := makeHTTPClient(remote) - return &ClientURI{ + return &URIClient{ address: address, client: client, } } -func (c *ClientURI) Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) { +func (c *URIClient) Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) { values, err := argsToURLValues(params) if err != nil { return nil, err diff --git a/rpc_test.go b/rpc_test.go index 334909f1f..b1ae2566d 100644 --- a/rpc_test.go +++ b/rpc_test.go @@ -98,7 +98,7 @@ func init() { } -func testURI(t *testing.T, cl *client.ClientURI) { +func testURI(t *testing.T, cl *client.URIClient) { val := "acbd" params := map[string]interface{}{ "arg": val, @@ -114,7 +114,7 @@ func testURI(t *testing.T, cl *client.ClientURI) { } } -func testJSONRPC(t *testing.T, cl *client.ClientJSONRPC) { +func testJSONRPC(t *testing.T, cl *client.JSONRPCClient) { val := "acbd" params := map[string]interface{}{ "arg": val, @@ -164,22 +164,22 @@ func testWS(t *testing.T, cl *client.WSClient) { //------------- func TestURI_TCP(t *testing.T) { - cl := client.NewClientURI(tcpAddr) + cl := client.NewURIClient(tcpAddr) testURI(t, cl) } func TestURI_UNIX(t *testing.T) { - cl := client.NewClientURI(unixAddr) + cl := client.NewURIClient(unixAddr) testURI(t, cl) } func TestJSONRPC_TCP(t *testing.T) { - cl := client.NewClientJSONRPC(tcpAddr) + cl := client.NewJSONRPCClient(tcpAddr) testJSONRPC(t, cl) } func TestJSONRPC_UNIX(t *testing.T) { - cl := client.NewClientJSONRPC(unixAddr) + cl := client.NewJSONRPCClient(unixAddr) testJSONRPC(t, cl) } @@ -202,7 +202,7 @@ func TestWS_UNIX(t *testing.T) { } func TestHexStringArg(t *testing.T) { - cl := client.NewClientURI(tcpAddr) + cl := client.NewURIClient(tcpAddr) // should NOT be handled as hex val := "0xabc" params := map[string]interface{}{ @@ -220,7 +220,7 @@ func TestHexStringArg(t *testing.T) { } func TestQuotedStringArg(t *testing.T) { - cl := client.NewClientURI(tcpAddr) + cl := client.NewURIClient(tcpAddr) // should NOT be unquoted val := "\"abc\"" params := map[string]interface{}{ @@ -248,7 +248,7 @@ func randBytes(t *testing.T) []byte { } func TestByteSliceViaJSONRPC(t *testing.T) { - cl := client.NewClientJSONRPC(unixAddr) + cl := client.NewJSONRPCClient(unixAddr) val := randBytes(t) params := map[string]interface{}{ From d66ebbd90407d22b52a74711d21073409a91c571 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Fri, 10 Mar 2017 12:03:16 +0400 Subject: [PATCH 106/309] use testify package --- Makefile | 3 ++ rpc_test.go | 82 ++++++++++++++--------------------------------------- 2 files changed, 25 insertions(+), 60 deletions(-) diff --git a/Makefile b/Makefile index a2e3bea7f..0937558a8 100644 --- a/Makefile +++ b/Makefile @@ -11,5 +11,8 @@ test: get_deps: @echo "--> Running go get" @go get -v -d $(PACKAGES) + @go list -f '{{join .TestImports "\n"}}' ./... | \ + grep -v /vendor/ | sort | uniq | \ + xargs go get -v -d .PHONY: all test get_deps diff --git a/rpc_test.go b/rpc_test.go index b1ae2566d..b52794ada 100644 --- a/rpc_test.go +++ b/rpc_test.go @@ -9,6 +9,8 @@ import ( "testing" "time" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" client "github.com/tendermint/go-rpc/client" server "github.com/tendermint/go-rpc/server" types "github.com/tendermint/go-rpc/types" @@ -105,13 +107,9 @@ func testURI(t *testing.T, cl *client.URIClient) { } var result Result _, err := cl.Call("status", params, &result) - if err != nil { - t.Fatal(err) - } + require.Nil(t, err) got := result.(*ResultStatus).Value - if got != val { - t.Fatalf("Got: %v .... Expected: %v \n", got, val) - } + assert.Equal(t, got, val) } func testJSONRPC(t *testing.T, cl *client.JSONRPCClient) { @@ -121,13 +119,9 @@ func testJSONRPC(t *testing.T, cl *client.JSONRPCClient) { } var result Result _, err := cl.Call("status", params, &result) - if err != nil { - t.Fatal(err) - } + require.Nil(t, err) got := result.(*ResultStatus).Value - if got != val { - t.Fatalf("Got: %v .... Expected: %v \n", got, val) - } + assert.Equal(t, got, val) } func testWS(t *testing.T, cl *client.WSClient) { @@ -141,21 +135,15 @@ func testWS(t *testing.T, cl *client.WSClient) { Method: "status", Params: params, }) - if err != nil { - t.Fatal(err) - } + require.Nil(t, err) select { case msg := <-cl.ResultsCh: result := new(Result) wire.ReadJSONPtr(result, msg, &err) - if err != nil { - t.Fatal(err) - } + require.Nil(t, err) got := (*result).(*ResultStatus).Value - if got != val { - t.Fatalf("Got: %v .... Expected: %v \n", got, val) - } + assert.Equal(t, got, val) case err := <-cl.ErrorsCh: t.Fatal(err) } @@ -186,18 +174,14 @@ func TestJSONRPC_UNIX(t *testing.T) { func TestWS_TCP(t *testing.T) { cl := client.NewWSClient(tcpAddr, websocketEndpoint) _, err := cl.Start() - if err != nil { - t.Fatal(err) - } + require.Nil(t, err) testWS(t, cl) } func TestWS_UNIX(t *testing.T) { cl := client.NewWSClient(unixAddr, websocketEndpoint) _, err := cl.Start() - if err != nil { - t.Fatal(err) - } + require.Nil(t, err) testWS(t, cl) } @@ -210,13 +194,9 @@ func TestHexStringArg(t *testing.T) { } var result Result _, err := cl.Call("status", params, &result) - if err != nil { - t.Fatal(err) - } + require.Nil(t, err) got := result.(*ResultStatus).Value - if got != val { - t.Fatalf("Got: %v .... Expected: %v \n", got, val) - } + assert.Equal(t, got, val) } func TestQuotedStringArg(t *testing.T) { @@ -228,22 +208,16 @@ func TestQuotedStringArg(t *testing.T) { } var result Result _, err := cl.Call("status", params, &result) - if err != nil { - t.Fatal(err) - } + require.Nil(t, err) got := result.(*ResultStatus).Value - if got != val { - t.Fatalf("Got: %v .... Expected: %v \n", got, val) - } + assert.Equal(t, got, val) } func randBytes(t *testing.T) []byte { n := rand.Intn(10) + 2 buf := make([]byte, n) _, err := crand.Read(buf) - if err != nil { - t.Fatal(err) - } + require.Nil(t, err) return bytes.Replace(buf, []byte("="), []byte{100}, -1) } @@ -256,21 +230,15 @@ func TestByteSliceViaJSONRPC(t *testing.T) { } var result Result _, err := cl.Call("bytes", params, &result) - if err != nil { - t.Fatal(err) - } + require.Nil(t, err) got := result.(*ResultBytes).Value - if bytes.Compare(got, val) != 0 { - t.Fatalf("Got: %v .... Expected: %v \n", got, val) - } + assert.Equal(t, got, val) } func TestWSNewWSRPCFunc(t *testing.T) { cl := client.NewWSClient(unixAddr, websocketEndpoint) _, err := cl.Start() - if err != nil { - t.Fatal(err) - } + require.Nil(t, err) defer cl.Stop() val := "acbd" @@ -283,21 +251,15 @@ func TestWSNewWSRPCFunc(t *testing.T) { Method: "status_ws", Params: params, }) - if err != nil { - t.Fatal(err) - } + require.Nil(t, err) select { case msg := <-cl.ResultsCh: result := new(Result) wire.ReadJSONPtr(result, msg, &err) - if err != nil { - t.Fatal(err) - } + require.Nil(t, err) got := (*result).(*ResultStatus).Value - if got != val { - t.Fatalf("Got: %v .... Expected: %v \n", got, val) - } + assert.Equal(t, got, val) case err := <-cl.ErrorsCh: t.Fatal(err) } From 0874c72819f0b78ded043e05a4cdce3b973230e0 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Fri, 10 Mar 2017 12:52:40 +0400 Subject: [PATCH 107/309] refactor tests --- rpc_test.go | 87 ++++++++++++++++++----------------------------------- 1 file changed, 29 insertions(+), 58 deletions(-) diff --git a/rpc_test.go b/rpc_test.go index b52794ada..acbf440d0 100644 --- a/rpc_test.go +++ b/rpc_test.go @@ -3,6 +3,7 @@ package rpc import ( "bytes" crand "crypto/rand" + "fmt" "math/rand" "net/http" "os/exec" @@ -100,31 +101,25 @@ func init() { } -func testURI(t *testing.T, cl *client.URIClient) { - val := "acbd" +func status(cl client.HTTPClient, val string) (string, error) { params := map[string]interface{}{ "arg": val, } var result Result - _, err := cl.Call("status", params, &result) - require.Nil(t, err) - got := result.(*ResultStatus).Value - assert.Equal(t, got, val) -} - -func testJSONRPC(t *testing.T, cl *client.JSONRPCClient) { - val := "acbd" - params := map[string]interface{}{ - "arg": val, + if _, err := cl.Call("status", params, &result); err != nil { + return "", err } - var result Result - _, err := cl.Call("status", params, &result) + return result.(*ResultStatus).Value, nil +} + +func testWithHTTPClient(t *testing.T, cl client.HTTPClient) { + val := "acbd" + got, err := status(cl, val) require.Nil(t, err) - got := result.(*ResultStatus).Value assert.Equal(t, got, val) } -func testWS(t *testing.T, cl *client.WSClient) { +func testWithWSClient(t *testing.T, cl *client.WSClient) { val := "acbd" params := map[string]interface{}{ "arg": val, @@ -151,51 +146,32 @@ func testWS(t *testing.T, cl *client.WSClient) { //------------- -func TestURI_TCP(t *testing.T) { - cl := client.NewURIClient(tcpAddr) - testURI(t, cl) -} +func TestServersAndClientsBasic(t *testing.T) { + serverAddrs := [...]string{tcpAddr, unixAddr} + for _, addr := range serverAddrs { + cl1 := client.NewURIClient(addr) + fmt.Printf("=== testing server on %s using %v client", addr, cl1) + testWithHTTPClient(t, cl1) -func TestURI_UNIX(t *testing.T) { - cl := client.NewURIClient(unixAddr) - testURI(t, cl) -} + cl2 := client.NewJSONRPCClient(tcpAddr) + fmt.Printf("=== testing server on %s using %v client", addr, cl2) + testWithHTTPClient(t, cl2) -func TestJSONRPC_TCP(t *testing.T) { - cl := client.NewJSONRPCClient(tcpAddr) - testJSONRPC(t, cl) -} - -func TestJSONRPC_UNIX(t *testing.T) { - cl := client.NewJSONRPCClient(unixAddr) - testJSONRPC(t, cl) -} - -func TestWS_TCP(t *testing.T) { - cl := client.NewWSClient(tcpAddr, websocketEndpoint) - _, err := cl.Start() - require.Nil(t, err) - testWS(t, cl) -} - -func TestWS_UNIX(t *testing.T) { - cl := client.NewWSClient(unixAddr, websocketEndpoint) - _, err := cl.Start() - require.Nil(t, err) - testWS(t, cl) + cl3 := client.NewWSClient(tcpAddr, websocketEndpoint) + _, err := cl3.Start() + require.Nil(t, err) + fmt.Printf("=== testing server on %s using %v client", addr, cl3) + testWithWSClient(t, cl3) + cl3.Stop() + } } func TestHexStringArg(t *testing.T) { cl := client.NewURIClient(tcpAddr) // should NOT be handled as hex val := "0xabc" - params := map[string]interface{}{ - "arg": val, - } - var result Result - _, err := cl.Call("status", params, &result) + got, err := status(cl, val) require.Nil(t, err) - got := result.(*ResultStatus).Value assert.Equal(t, got, val) } @@ -203,13 +179,8 @@ func TestQuotedStringArg(t *testing.T) { cl := client.NewURIClient(tcpAddr) // should NOT be unquoted val := "\"abc\"" - params := map[string]interface{}{ - "arg": val, - } - var result Result - _, err := cl.Call("status", params, &result) + got, err := status(cl, val) require.Nil(t, err) - got := result.(*ResultStatus).Value assert.Equal(t, got, val) } From c88257b0384f6ceeb1219c527cb0ce06402acb1d Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Fri, 10 Mar 2017 12:57:14 +0400 Subject: [PATCH 108/309] rename rpc function status to echo echo means we're returning the input, which is exactly what this function does. --- rpc_test.go | 51 +++++++++++++++++++++++++-------------------------- 1 file changed, 25 insertions(+), 26 deletions(-) diff --git a/rpc_test.go b/rpc_test.go index acbf440d0..7b043953c 100644 --- a/rpc_test.go +++ b/rpc_test.go @@ -31,38 +31,37 @@ const ( // Define a type for results and register concrete versions type Result interface{} -type ResultStatus struct { +type ResultEcho struct { Value string } -type ResultBytes struct { +type ResultEchoBytes struct { Value []byte } var _ = wire.RegisterInterface( struct{ Result }{}, - wire.ConcreteType{&ResultStatus{}, 0x1}, - wire.ConcreteType{&ResultBytes{}, 0x2}, + wire.ConcreteType{&ResultEcho{}, 0x1}, + wire.ConcreteType{&ResultEchoBytes{}, 0x2}, ) // Define some routes var Routes = map[string]*server.RPCFunc{ - "status": server.NewRPCFunc(StatusResult, "arg"), - "status_ws": server.NewWSRPCFunc(StatusWSResult, "arg"), - "bytes": server.NewRPCFunc(BytesResult, "arg"), + "echo": server.NewRPCFunc(EchoResult, "arg"), + "echo_ws": server.NewWSRPCFunc(EchoWSResult, "arg"), + "echo_bytes": server.NewRPCFunc(EchoBytesResult, "arg"), } -// an rpc function -func StatusResult(v string) (Result, error) { - return &ResultStatus{v}, nil +func EchoResult(v string) (Result, error) { + return &ResultEcho{v}, nil } -func StatusWSResult(wsCtx types.WSRPCContext, v string) (Result, error) { - return &ResultStatus{v}, nil +func EchoWSResult(wsCtx types.WSRPCContext, v string) (Result, error) { + return &ResultEcho{v}, nil } -func BytesResult(v []byte) (Result, error) { - return &ResultBytes{v}, nil +func EchoBytesResult(v []byte) (Result, error) { + return &ResultEchoBytes{v}, nil } // launch unix and tcp servers @@ -101,20 +100,20 @@ func init() { } -func status(cl client.HTTPClient, val string) (string, error) { +func echo(cl client.HTTPClient, val string) (string, error) { params := map[string]interface{}{ "arg": val, } var result Result - if _, err := cl.Call("status", params, &result); err != nil { + if _, err := cl.Call("echo", params, &result); err != nil { return "", err } - return result.(*ResultStatus).Value, nil + return result.(*ResultEcho).Value, nil } func testWithHTTPClient(t *testing.T, cl client.HTTPClient) { val := "acbd" - got, err := status(cl, val) + got, err := echo(cl, val) require.Nil(t, err) assert.Equal(t, got, val) } @@ -127,7 +126,7 @@ func testWithWSClient(t *testing.T, cl *client.WSClient) { err := cl.WriteJSON(types.RPCRequest{ JSONRPC: "2.0", ID: "", - Method: "status", + Method: "echo", Params: params, }) require.Nil(t, err) @@ -137,7 +136,7 @@ func testWithWSClient(t *testing.T, cl *client.WSClient) { result := new(Result) wire.ReadJSONPtr(result, msg, &err) require.Nil(t, err) - got := (*result).(*ResultStatus).Value + got := (*result).(*ResultEcho).Value assert.Equal(t, got, val) case err := <-cl.ErrorsCh: t.Fatal(err) @@ -170,7 +169,7 @@ func TestHexStringArg(t *testing.T) { cl := client.NewURIClient(tcpAddr) // should NOT be handled as hex val := "0xabc" - got, err := status(cl, val) + got, err := echo(cl, val) require.Nil(t, err) assert.Equal(t, got, val) } @@ -179,7 +178,7 @@ func TestQuotedStringArg(t *testing.T) { cl := client.NewURIClient(tcpAddr) // should NOT be unquoted val := "\"abc\"" - got, err := status(cl, val) + got, err := echo(cl, val) require.Nil(t, err) assert.Equal(t, got, val) } @@ -200,9 +199,9 @@ func TestByteSliceViaJSONRPC(t *testing.T) { "arg": val, } var result Result - _, err := cl.Call("bytes", params, &result) + _, err := cl.Call("echo_bytes", params, &result) require.Nil(t, err) - got := result.(*ResultBytes).Value + got := result.(*ResultEchoBytes).Value assert.Equal(t, got, val) } @@ -219,7 +218,7 @@ func TestWSNewWSRPCFunc(t *testing.T) { err = cl.WriteJSON(types.RPCRequest{ JSONRPC: "2.0", ID: "", - Method: "status_ws", + Method: "echo_ws", Params: params, }) require.Nil(t, err) @@ -229,7 +228,7 @@ func TestWSNewWSRPCFunc(t *testing.T) { result := new(Result) wire.ReadJSONPtr(result, msg, &err) require.Nil(t, err) - got := (*result).(*ResultStatus).Value + got := (*result).(*ResultEcho).Value assert.Equal(t, got, val) case err := <-cl.ErrorsCh: t.Fatal(err) From 3233c9c003b8ed81ce2e9d18d39fdb5164d2d62a Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Fri, 10 Mar 2017 14:56:04 +0400 Subject: [PATCH 109/309] WSClient failed to "echo_bytes" Error: ``` Expected nil, but got: encoding/hex: invalid byte: U+0078 'x' ``` --- rpc_test.go | 118 +++++++++++++++++++++++++++++++++++----------------- 1 file changed, 80 insertions(+), 38 deletions(-) diff --git a/rpc_test.go b/rpc_test.go index 7b043953c..41952fca4 100644 --- a/rpc_test.go +++ b/rpc_test.go @@ -97,10 +97,9 @@ func init() { // wait for servers to start time.Sleep(time.Second * 2) - } -func echo(cl client.HTTPClient, val string) (string, error) { +func echoViaHTTP(cl client.HTTPClient, val string) (string, error) { params := map[string]interface{}{ "arg": val, } @@ -111,15 +110,30 @@ func echo(cl client.HTTPClient, val string) (string, error) { return result.(*ResultEcho).Value, nil } -func testWithHTTPClient(t *testing.T, cl client.HTTPClient) { - val := "acbd" - got, err := echo(cl, val) - require.Nil(t, err) - assert.Equal(t, got, val) +func echoBytesViaHTTP(cl client.HTTPClient, bytes []byte) ([]byte, error) { + params := map[string]interface{}{ + "arg": bytes, + } + var result Result + if _, err := cl.Call("echo_bytes", params, &result); err != nil { + return []byte{}, err + } + return result.(*ResultEchoBytes).Value, nil } -func testWithWSClient(t *testing.T, cl *client.WSClient) { +func testWithHTTPClient(t *testing.T, cl client.HTTPClient) { val := "acbd" + got, err := echoViaHTTP(cl, val) + require.Nil(t, err) + assert.Equal(t, got, val) + + val2 := randBytes(t) + got2, err := echoBytesViaHTTP(cl, val2) + require.Nil(t, err) + assert.Equal(t, got2, val2) +} + +func echoViaWS(cl *client.WSClient, val string) (string, error) { params := map[string]interface{}{ "arg": val, } @@ -129,20 +143,62 @@ func testWithWSClient(t *testing.T, cl *client.WSClient) { Method: "echo", Params: params, }) - require.Nil(t, err) + if err != nil { + return "", err + } select { case msg := <-cl.ResultsCh: result := new(Result) wire.ReadJSONPtr(result, msg, &err) - require.Nil(t, err) - got := (*result).(*ResultEcho).Value - assert.Equal(t, got, val) + if err != nil { + return "", nil + } + return (*result).(*ResultEcho).Value, nil case err := <-cl.ErrorsCh: - t.Fatal(err) + return "", err } } +func echoBytesViaWS(cl *client.WSClient, bytes []byte) ([]byte, error) { + params := map[string]interface{}{ + "arg": bytes, + } + err := cl.WriteJSON(types.RPCRequest{ + JSONRPC: "2.0", + ID: "", + Method: "echo_bytes", + Params: params, + }) + if err != nil { + return []byte{}, err + } + + select { + case msg := <-cl.ResultsCh: + result := new(Result) + wire.ReadJSONPtr(result, msg, &err) + if err != nil { + return []byte{}, nil + } + return (*result).(*ResultEchoBytes).Value, nil + case err := <-cl.ErrorsCh: + return []byte{}, err + } +} + +func testWithWSClient(t *testing.T, cl *client.WSClient) { + val := "acbd" + got, err := echoViaWS(cl, val) + require.Nil(t, err) + assert.Equal(t, got, val) + + val2 := randBytes(t) + got2, err := echoBytesViaWS(cl, val2) + require.Nil(t, err) + assert.Equal(t, got2, val2) +} + //------------- func TestServersAndClientsBasic(t *testing.T) { @@ -169,7 +225,7 @@ func TestHexStringArg(t *testing.T) { cl := client.NewURIClient(tcpAddr) // should NOT be handled as hex val := "0xabc" - got, err := echo(cl, val) + got, err := echoViaHTTP(cl, val) require.Nil(t, err) assert.Equal(t, got, val) } @@ -178,35 +234,13 @@ func TestQuotedStringArg(t *testing.T) { cl := client.NewURIClient(tcpAddr) // should NOT be unquoted val := "\"abc\"" - got, err := echo(cl, val) + got, err := echoViaHTTP(cl, val) require.Nil(t, err) assert.Equal(t, got, val) } -func randBytes(t *testing.T) []byte { - n := rand.Intn(10) + 2 - buf := make([]byte, n) - _, err := crand.Read(buf) - require.Nil(t, err) - return bytes.Replace(buf, []byte("="), []byte{100}, -1) -} - -func TestByteSliceViaJSONRPC(t *testing.T) { - cl := client.NewJSONRPCClient(unixAddr) - - val := randBytes(t) - params := map[string]interface{}{ - "arg": val, - } - var result Result - _, err := cl.Call("echo_bytes", params, &result) - require.Nil(t, err) - got := result.(*ResultEchoBytes).Value - assert.Equal(t, got, val) -} - func TestWSNewWSRPCFunc(t *testing.T) { - cl := client.NewWSClient(unixAddr, websocketEndpoint) + cl := client.NewWSClient(tcpAddr, websocketEndpoint) _, err := cl.Start() require.Nil(t, err) defer cl.Stop() @@ -234,3 +268,11 @@ func TestWSNewWSRPCFunc(t *testing.T) { t.Fatal(err) } } + +func randBytes(t *testing.T) []byte { + n := rand.Intn(10) + 2 + buf := make([]byte, n) + _, err := crand.Read(buf) + require.Nil(t, err) + return bytes.Replace(buf, []byte("="), []byte{100}, -1) +} From 5d19a008ce4ea633b2002404df1e6b6be298f886 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Fri, 10 Mar 2017 15:23:43 +0400 Subject: [PATCH 110/309] add Call method to WSClient, which does proper encoding of params --- README.md | 1 + client/http_client.go | 1 - client/ws_client.go | 26 ++++++++++++++++++++++++-- rpc_test.go | 14 ++------------ 4 files changed, 27 insertions(+), 15 deletions(-) diff --git a/README.md b/README.md index 06a679032..5928e6fe0 100644 --- a/README.md +++ b/README.md @@ -125,3 +125,4 @@ IMPROVEMENTS: - added `HTTPClient` interface, which can be used for both `ClientURI` and `ClientJSONRPC` - all params are now optional (Golang's default will be used if some param is missing) +- added `Call` method to `WSClient` (see method's doc for details) diff --git a/client/http_client.go b/client/http_client.go index 96bae9d9b..f4a2a6d7e 100644 --- a/client/http_client.go +++ b/client/http_client.go @@ -72,7 +72,6 @@ func (c *JSONRPCClient) Call(method string, params map[string]interface{}, resul // (handlers.go:176) on the server side encodedParams := make(map[string]interface{}) for k, v := range params { - // log.Printf("%s: %v (%s)\n", k, v, string(wire.JSONBytes(v))) bytes := json.RawMessage(wire.JSONBytes(v)) encodedParams[k] = &bytes } diff --git a/client/ws_client.go b/client/ws_client.go index b56547dd6..ecf641221 100644 --- a/client/ws_client.go +++ b/client/ws_client.go @@ -10,6 +10,7 @@ import ( "github.com/pkg/errors" cmn "github.com/tendermint/go-common" types "github.com/tendermint/go-rpc/types" + wire "github.com/tendermint/go-wire" ) const ( @@ -116,7 +117,8 @@ func (wsc *WSClient) receiveEventsRoutine() { close(wsc.ErrorsCh) } -// subscribe to an event +// Subscribe to an event. Note the server must have a "subscribe" route +// defined. func (wsc *WSClient) Subscribe(eventid string) error { err := wsc.WriteJSON(types.RPCRequest{ JSONRPC: "2.0", @@ -127,7 +129,8 @@ func (wsc *WSClient) Subscribe(eventid string) error { return err } -// unsubscribe from an event +// Unsubscribe from an event. Note the server must have a "unsubscribe" route +// defined. func (wsc *WSClient) Unsubscribe(eventid string) error { err := wsc.WriteJSON(types.RPCRequest{ JSONRPC: "2.0", @@ -137,3 +140,22 @@ func (wsc *WSClient) Unsubscribe(eventid string) error { }) return err } + +// Call asynchronously calls a given method by sending an RPCRequest to the +// server. Results will be available on ResultsCh, errors, if any, on ErrorsCh. +func (wsc *WSClient) Call(method string, params map[string]interface{}) error { + // we need this step because we attempt to decode values using `go-wire` + // (handlers.go:470) on the server side + encodedParams := make(map[string]interface{}) + for k, v := range params { + bytes := json.RawMessage(wire.JSONBytes(v)) + encodedParams[k] = &bytes + } + err := wsc.WriteJSON(types.RPCRequest{ + JSONRPC: "2.0", + Method: method, + Params: encodedParams, + ID: "", + }) + return err +} diff --git a/rpc_test.go b/rpc_test.go index 41952fca4..8a05d7295 100644 --- a/rpc_test.go +++ b/rpc_test.go @@ -137,12 +137,7 @@ func echoViaWS(cl *client.WSClient, val string) (string, error) { params := map[string]interface{}{ "arg": val, } - err := cl.WriteJSON(types.RPCRequest{ - JSONRPC: "2.0", - ID: "", - Method: "echo", - Params: params, - }) + err := cl.Call("echo", params) if err != nil { return "", err } @@ -164,12 +159,7 @@ func echoBytesViaWS(cl *client.WSClient, bytes []byte) ([]byte, error) { params := map[string]interface{}{ "arg": bytes, } - err := cl.WriteJSON(types.RPCRequest{ - JSONRPC: "2.0", - ID: "", - Method: "echo_bytes", - Params: params, - }) + err := cl.Call("echo_bytes", params) if err != nil { return []byte{}, err } From b54b9b4ecc2c444f7b11077f24e5abafdcc98676 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Mon, 13 Mar 2017 14:25:57 +0400 Subject: [PATCH 111/309] update url to network monitor [ci skip] [circleci skip] --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 06a679032..cb869d517 100644 --- a/README.md +++ b/README.md @@ -108,7 +108,7 @@ Each route is available as a GET request, as a JSONRPCv2 POST request, and via J # Examples * [Tendermint](https://github.com/tendermint/tendermint/blob/master/rpc/core/routes.go) -* [Network Monitor](https://github.com/tendermint/netmon/blob/master/handlers/routes.go) +* [tm-monitor](https://github.com/tendermint/tools/blob/master/tm-monitor/rpc.go) ## CHANGELOG From afc39febed0c51e01ba2474980533a5c5a899258 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Tue, 21 Mar 2017 20:47:12 +0400 Subject: [PATCH 112/309] close ws connection on Stop --- client/ws_client.go | 2 ++ server/handlers.go | 4 +++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/client/ws_client.go b/client/ws_client.go index b56547dd6..9ed2be8c5 100644 --- a/client/ws_client.go +++ b/client/ws_client.go @@ -85,6 +85,8 @@ func (wsc *WSClient) dial() error { func (wsc *WSClient) OnStop() { wsc.BaseService.OnStop() + wsc.Conn.Close() + wsc.Conn = nil // ResultsCh/ErrorsCh is closed in receiveEventsRoutine. } diff --git a/server/handlers.go b/server/handlers.go index ca42b2e67..5b6008504 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -373,7 +373,9 @@ func (wsc *wsConnection) OnStart() error { func (wsc *wsConnection) OnStop() { wsc.BaseService.OnStop() - wsc.evsw.RemoveListener(wsc.remoteAddr) + if wsc.evsw != nil { + wsc.evsw.RemoveListener(wsc.remoteAddr) + } wsc.readTimeout.Stop() wsc.pingTicker.Stop() // The write loop closes the websocket connection From d6587be7bcacf7cdc5a547f8a2f3862b3d7bd8df Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Tue, 21 Mar 2017 22:05:53 +0400 Subject: [PATCH 113/309] [WSClient] allow for multiple restarts needed for https://github.com/tendermint/tools/pull/13/commits/3044f66ba90694927fb22ea5267de2a90bb3281b See https://github.com/tendermint/tools/issues/6 --- client/ws_client.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/client/ws_client.go b/client/ws_client.go index b56547dd6..99737ca8f 100644 --- a/client/ws_client.go +++ b/client/ws_client.go @@ -53,6 +53,9 @@ func (wsc *WSClient) OnStart() error { if err != nil { return err } + + wsc.ResultsCh = make(chan json.RawMessage, wsResultsChannelCapacity) + wsc.ErrorsCh = make(chan error, wsErrorsChannelCapacity) go wsc.receiveEventsRoutine() return nil } From b0d2032488a16ce1497edd47e7c2e0dda246723f Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Tue, 28 Mar 2017 14:01:22 +0400 Subject: [PATCH 114/309] use BaseService.OnReset method to recreate channels --- client/ws_client.go | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/client/ws_client.go b/client/ws_client.go index 99737ca8f..fb359bdaf 100644 --- a/client/ws_client.go +++ b/client/ws_client.go @@ -47,16 +47,21 @@ func (wsc *WSClient) String() string { return wsc.Address + ", " + wsc.Endpoint } +// OnStart implements cmn.BaseService interface func (wsc *WSClient) OnStart() error { wsc.BaseService.OnStart() err := wsc.dial() if err != nil { return err } + go wsc.receiveEventsRoutine() + return nil +} +// OnReset implements cmn.BaseService interface +func (wsc *WSClient) OnReset() error { wsc.ResultsCh = make(chan json.RawMessage, wsResultsChannelCapacity) wsc.ErrorsCh = make(chan error, wsErrorsChannelCapacity) - go wsc.receiveEventsRoutine() return nil } @@ -86,6 +91,7 @@ func (wsc *WSClient) dial() error { return nil } +// OnStop implements cmn.BaseService interface func (wsc *WSClient) OnStop() { wsc.BaseService.OnStop() // ResultsCh/ErrorsCh is closed in receiveEventsRoutine. From ba5382b70e65f89cd771157fc900cfc6adb22819 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Tue, 28 Mar 2017 14:17:40 +0400 Subject: [PATCH 115/309] open result&error channels on start --- client/ws_client.go | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/client/ws_client.go b/client/ws_client.go index fb359bdaf..8fa6189d1 100644 --- a/client/ws_client.go +++ b/client/ws_client.go @@ -32,12 +32,10 @@ type WSClient struct { func NewWSClient(remoteAddr, endpoint string) *WSClient { addr, dialer := makeHTTPDialer(remoteAddr) wsClient := &WSClient{ - Address: addr, - Dialer: dialer, - Endpoint: endpoint, - Conn: nil, - ResultsCh: make(chan json.RawMessage, wsResultsChannelCapacity), - ErrorsCh: make(chan error, wsErrorsChannelCapacity), + Address: addr, + Dialer: dialer, + Endpoint: endpoint, + Conn: nil, } wsClient.BaseService = *cmn.NewBaseService(log, "WSClient", wsClient) return wsClient @@ -54,14 +52,14 @@ func (wsc *WSClient) OnStart() error { if err != nil { return err } + wsc.ResultsCh = make(chan json.RawMessage, wsResultsChannelCapacity) + wsc.ErrorsCh = make(chan error, wsErrorsChannelCapacity) go wsc.receiveEventsRoutine() return nil } // OnReset implements cmn.BaseService interface func (wsc *WSClient) OnReset() error { - wsc.ResultsCh = make(chan json.RawMessage, wsResultsChannelCapacity) - wsc.ErrorsCh = make(chan error, wsErrorsChannelCapacity) return nil } From 868017cf1ae44ab01f6cff654bb65e0573c743d4 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Tue, 4 Apr 2017 19:28:28 +0400 Subject: [PATCH 116/309] import go-common as cmn --- connection.go | 38 +++++++++++++++++++------------------- 1 file changed, 19 insertions(+), 19 deletions(-) diff --git a/connection.go b/connection.go index 4428e0da7..02cfb45d4 100644 --- a/connection.go +++ b/connection.go @@ -10,10 +10,10 @@ import ( "sync/atomic" "time" - . "github.com/tendermint/go-common" + cmn "github.com/tendermint/go-common" cfg "github.com/tendermint/go-config" flow "github.com/tendermint/go-flowrate/flowrate" - "github.com/tendermint/go-wire" //"github.com/tendermint/log15" + wire "github.com/tendermint/go-wire" ) const ( @@ -60,7 +60,7 @@ queue is full. Inbound message bytes are handled with an onReceive callback function. */ type MConnection struct { - BaseService + cmn.BaseService conn net.Conn bufReader *bufio.Reader @@ -78,9 +78,9 @@ type MConnection struct { errored uint32 quit chan struct{} - flushTimer *ThrottleTimer // flush writes as necessary but throttled. - pingTimer *RepeatTimer // send pings periodically - chStatsTimer *RepeatTimer // update channel stats periodically + flushTimer *cmn.ThrottleTimer // flush writes as necessary but throttled. + pingTimer *cmn.RepeatTimer // send pings periodically + chStatsTimer *cmn.RepeatTimer // update channel stats periodically LocalAddress *NetAddress RemoteAddress *NetAddress @@ -123,7 +123,7 @@ func NewMConnection(config cfg.Config, conn net.Conn, chDescs []*ChannelDescript mconn.channels = channels mconn.channelsIdx = channelsIdx - mconn.BaseService = *NewBaseService(log, "MConnection", mconn) + mconn.BaseService = *cmn.NewBaseService(log, "MConnection", mconn) return mconn } @@ -131,9 +131,9 @@ func NewMConnection(config cfg.Config, conn net.Conn, chDescs []*ChannelDescript func (c *MConnection) OnStart() error { c.BaseService.OnStart() c.quit = make(chan struct{}) - c.flushTimer = NewThrottleTimer("flush", flushThrottleMS*time.Millisecond) - c.pingTimer = NewRepeatTimer("ping", pingTimeoutSeconds*time.Second) - c.chStatsTimer = NewRepeatTimer("chStats", updateStatsSeconds*time.Second) + c.flushTimer = cmn.NewThrottleTimer("flush", flushThrottleMS*time.Millisecond) + c.pingTimer = cmn.NewRepeatTimer("ping", pingTimeoutSeconds*time.Second) + c.chStatsTimer = cmn.NewRepeatTimer("chStats", updateStatsSeconds*time.Second) go c.sendRoutine() go c.recvRoutine() return nil @@ -171,7 +171,7 @@ func (c *MConnection) flush() { func (c *MConnection) _recover() { if r := recover(); r != nil { stack := debug.Stack() - err := StackError{r, stack} + err := cmn.StackError{r, stack} c.stopForError(err) } } @@ -196,7 +196,7 @@ func (c *MConnection) Send(chID byte, msg interface{}) bool { // Send message to channel. channel, ok := c.channelsIdx[chID] if !ok { - log.Error(Fmt("Cannot send bytes, unknown channel %X", chID)) + log.Error(cmn.Fmt("Cannot send bytes, unknown channel %X", chID)) return false } @@ -225,7 +225,7 @@ func (c *MConnection) TrySend(chID byte, msg interface{}) bool { // Send message to channel. channel, ok := c.channelsIdx[chID] if !ok { - log.Error(Fmt("Cannot send bytes, unknown channel %X", chID)) + log.Error(cmn.Fmt("Cannot send bytes, unknown channel %X", chID)) return false } @@ -248,7 +248,7 @@ func (c *MConnection) CanSend(chID byte) bool { channel, ok := c.channelsIdx[chID] if !ok { - log.Error(Fmt("Unknown channel %X", chID)) + log.Error(cmn.Fmt("Unknown channel %X", chID)) return false } return channel.canSend() @@ -424,7 +424,7 @@ FOR_LOOP: } channel, ok := c.channelsIdx[pkt.ChannelID] if !ok || channel == nil { - PanicQ(Fmt("Unknown channel %X", pkt.ChannelID)) + cmn.PanicQ(cmn.Fmt("Unknown channel %X", pkt.ChannelID)) } msgBytes, err := channel.recvMsgPacket(pkt) if err != nil { @@ -439,7 +439,7 @@ FOR_LOOP: c.onReceive(pkt.ChannelID, msgBytes) } default: - PanicSanity(Fmt("Unknown message type %X", pktType)) + cmn.PanicSanity(cmn.Fmt("Unknown message type %X", pktType)) } // TODO: shouldn't this go in the sendRoutine? @@ -524,7 +524,7 @@ type Channel struct { func newChannel(conn *MConnection, desc *ChannelDescriptor) *Channel { desc.FillDefaults() if desc.Priority <= 0 { - PanicSanity("Channel default priority must be a postive integer") + cmn.PanicSanity("Channel default priority must be a postive integer") } return &Channel{ conn: conn, @@ -593,14 +593,14 @@ func (ch *Channel) isSendPending() bool { func (ch *Channel) nextMsgPacket() msgPacket { packet := msgPacket{} packet.ChannelID = byte(ch.id) - packet.Bytes = ch.sending[:MinInt(maxMsgPacketPayloadSize, len(ch.sending))] + packet.Bytes = ch.sending[:cmn.MinInt(maxMsgPacketPayloadSize, len(ch.sending))] if len(ch.sending) <= maxMsgPacketPayloadSize { packet.EOF = byte(0x01) ch.sending = nil atomic.AddInt32(&ch.sendQueueSize, -1) // decrement sendQueueSize } else { packet.EOF = byte(0x00) - ch.sending = ch.sending[MinInt(maxMsgPacketPayloadSize, len(ch.sending)):] + ch.sending = ch.sending[cmn.MinInt(maxMsgPacketPayloadSize, len(ch.sending)):] } return packet } From 549d3bd09a5476aa0ea1660c4689178ec05fec26 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Tue, 4 Apr 2017 23:13:09 +0400 Subject: [PATCH 117/309] tests for MConnection --- connection_test.go | 105 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 105 insertions(+) create mode 100644 connection_test.go diff --git a/connection_test.go b/connection_test.go new file mode 100644 index 000000000..9d489f655 --- /dev/null +++ b/connection_test.go @@ -0,0 +1,105 @@ +package p2p_test + +import ( + "net" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + cfg "github.com/tendermint/go-config" + p2p "github.com/tendermint/go-p2p" +) + +func createMConnection(conn net.Conn) *p2p.MConnection { + onReceive := func(chID byte, msgBytes []byte) { + } + onError := func(r interface{}) { + } + return createMConnectionWithCallbacks(conn, onReceive, onError) +} + +func createMConnectionWithCallbacks(conn net.Conn, onReceive func(chID byte, msgBytes []byte), onError func(r interface{})) *p2p.MConnection { + config := cfg.NewMapConfig(map[string]interface{}{"send_rate": 512000, "recv_rate": 512000}) + chDescs := []*p2p.ChannelDescriptor{&p2p.ChannelDescriptor{ID: 0x01, Priority: 1}} + + return p2p.NewMConnection(config, conn, chDescs, onReceive, onError) +} + +func TestMConnectionSend(t *testing.T) { + assert, require := assert.New(t), require.New(t) + + server, client := net.Pipe() + defer server.Close() + defer client.Close() + + mconn := createMConnection(client) + _, err := mconn.Start() + require.Nil(err) + defer mconn.Stop() + + msg := "Ant-Man" + assert.True(mconn.Send(0x01, msg)) + assert.False(mconn.CanSend(0x01)) + server.Read(make([]byte, len(msg))) + assert.True(mconn.CanSend(0x01)) + + msg = "Spider-Man" + assert.True(mconn.TrySend(0x01, msg)) + server.Read(make([]byte, len(msg))) +} + +func TestMConnectionReceive(t *testing.T) { + assert, require := assert.New(t), require.New(t) + + server, client := net.Pipe() + defer server.Close() + defer client.Close() + + receivedCh := make(chan []byte) + errorsCh := make(chan interface{}) + onReceive := func(chID byte, msgBytes []byte) { + receivedCh <- msgBytes + } + onError := func(r interface{}) { + errorsCh <- r + } + mconn1 := createMConnectionWithCallbacks(client, onReceive, onError) + _, err := mconn1.Start() + require.Nil(err) + defer mconn1.Stop() + + mconn2 := createMConnection(server) + _, err = mconn2.Start() + require.Nil(err) + defer mconn2.Stop() + + msg := "Cyclops" + assert.True(mconn2.Send(0x01, msg)) + + select { + case receivedBytes := <-receivedCh: + assert.Equal([]byte(msg), receivedBytes[2:]) // first 3 bytes are internal + case err := <-errorsCh: + t.Fatalf("Expected %s, got %+v", msg, err) + case <-time.After(500 * time.Millisecond): + t.Fatalf("Did not receive %s message in 500ms", msg) + } +} + +func TestMConnectionStatus(t *testing.T) { + assert, require := assert.New(t), require.New(t) + + server, client := net.Pipe() + defer server.Close() + defer client.Close() + + mconn := createMConnection(client) + _, err := mconn.Start() + require.Nil(err) + defer mconn.Stop() + + status := mconn.Status() + assert.NotNil(status) + assert.Zero(status.Channels[0].SendQueueSize) +} From 5be72672fea7184eb82a1fb29d35e37d7cd6b6ab Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Wed, 5 Apr 2017 00:14:24 +0400 Subject: [PATCH 118/309] use golang time datatype instead of time units in name --- connection.go | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/connection.go b/connection.go index 02cfb45d4..ddb096a11 100644 --- a/connection.go +++ b/connection.go @@ -21,14 +21,14 @@ const ( minReadBufferSize = 1024 minWriteBufferSize = 65536 idleTimeoutMinutes = 5 - updateStatsSeconds = 2 - pingTimeoutSeconds = 40 - flushThrottleMS = 100 + updateState = 2 * time.Second + pingTimeout = 40 * time.Second + flushThrottle = 100 * time.Millisecond defaultSendQueueCapacity = 1 defaultRecvBufferCapacity = 4096 defaultRecvMessageCapacity = 22020096 // 21MB - defaultSendTimeoutSeconds = 10 + defaultSendTimeout = 10 * time.Second ) type receiveCbFunc func(chID byte, msgBytes []byte) @@ -131,9 +131,9 @@ func NewMConnection(config cfg.Config, conn net.Conn, chDescs []*ChannelDescript func (c *MConnection) OnStart() error { c.BaseService.OnStart() c.quit = make(chan struct{}) - c.flushTimer = cmn.NewThrottleTimer("flush", flushThrottleMS*time.Millisecond) - c.pingTimer = cmn.NewRepeatTimer("ping", pingTimeoutSeconds*time.Second) - c.chStatsTimer = cmn.NewRepeatTimer("chStats", updateStatsSeconds*time.Second) + c.flushTimer = cmn.NewThrottleTimer("flush", flushThrottle) + c.pingTimer = cmn.NewRepeatTimer("ping", pingTimeout) + c.chStatsTimer = cmn.NewRepeatTimer("chStats", updateState) go c.sendRoutine() go c.recvRoutine() return nil @@ -538,9 +538,9 @@ func newChannel(conn *MConnection, desc *ChannelDescriptor) *Channel { // Queues message to send to this channel. // Goroutine-safe -// Times out (and returns false) after defaultSendTimeoutSeconds +// Times out (and returns false) after defaultSendTimeout func (ch *Channel) sendBytes(bytes []byte) bool { - timeout := time.NewTimer(defaultSendTimeoutSeconds * time.Second) + timeout := time.NewTimer(defaultSendTimeout) select { case <-timeout.C: // timeout From 2b02843453aa9499cb62e4afa1390fd14897e08f Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Wed, 5 Apr 2017 00:17:58 +0400 Subject: [PATCH 119/309] remove unused const --- connection.go | 1 - 1 file changed, 1 deletion(-) diff --git a/connection.go b/connection.go index ddb096a11..8afb3f9e9 100644 --- a/connection.go +++ b/connection.go @@ -20,7 +20,6 @@ const ( numBatchMsgPackets = 10 minReadBufferSize = 1024 minWriteBufferSize = 65536 - idleTimeoutMinutes = 5 updateState = 2 * time.Second pingTimeout = 40 * time.Second flushThrottle = 100 * time.Millisecond From b8a939a894b25aa6ff40391b1fd0af5dacad2655 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Wed, 5 Apr 2017 01:49:01 +0400 Subject: [PATCH 120/309] test non persistent mconnection --- connection_test.go | 33 +++++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/connection_test.go b/connection_test.go index 9d489f655..79a7227a2 100644 --- a/connection_test.go +++ b/connection_test.go @@ -103,3 +103,36 @@ func TestMConnectionStatus(t *testing.T) { assert.NotNil(status) assert.Zero(status.Channels[0].SendQueueSize) } + +func TestMConnectionNonPersistent(t *testing.T) { + assert, require := assert.New(t), require.New(t) + + server, client := net.Pipe() + defer server.Close() + defer client.Close() + + receivedCh := make(chan []byte) + errorsCh := make(chan interface{}) + onReceive := func(chID byte, msgBytes []byte) { + receivedCh <- msgBytes + } + onError := func(r interface{}) { + errorsCh <- r + } + mconn := createMConnectionWithCallbacks(client, onReceive, onError) + _, err := mconn.Start() + require.Nil(err) + defer mconn.Stop() + + client.Close() + + select { + case receivedBytes := <-receivedCh: + t.Fatalf("Expected error, got %v", receivedBytes) + case err := <-errorsCh: + assert.NotNil(err) + assert.False(mconn.IsRunning()) + case <-time.After(500 * time.Millisecond): + t.Fatal("Did not receive error in 500ms") + } +} From 5b0489cdb4121b3d4486a530e428f1665d100b3e Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Thu, 6 Apr 2017 16:43:45 +0400 Subject: [PATCH 121/309] use plain struct instead of go-config --- connection.go | 43 ++++++++++++++++++++++++++++--------------- connection_test.go | 7 ++----- peer.go | 6 +++++- switch.go | 2 +- 4 files changed, 36 insertions(+), 22 deletions(-) diff --git a/connection.go b/connection.go index 8afb3f9e9..e61608896 100644 --- a/connection.go +++ b/connection.go @@ -11,7 +11,6 @@ import ( "time" cmn "github.com/tendermint/go-common" - cfg "github.com/tendermint/go-config" flow "github.com/tendermint/go-flowrate/flowrate" wire "github.com/tendermint/go-wire" ) @@ -25,8 +24,10 @@ const ( flushThrottle = 100 * time.Millisecond defaultSendQueueCapacity = 1 + defaultSendRate = int64(512000) // 500KB/s defaultRecvBufferCapacity = 4096 - defaultRecvMessageCapacity = 22020096 // 21MB + defaultRecvMessageCapacity = 22020096 // 21MB + defaultRecvRate = int64(512000) // 500KB/s defaultSendTimeout = 10 * time.Second ) @@ -66,8 +67,6 @@ type MConnection struct { bufWriter *bufio.Writer sendMonitor *flow.Monitor recvMonitor *flow.Monitor - sendRate int64 - recvRate int64 send chan struct{} pong chan struct{} channels []*Channel @@ -75,6 +74,7 @@ type MConnection struct { onReceive receiveCbFunc onError errorCbFunc errored uint32 + config *MConnectionConfig quit chan struct{} flushTimer *cmn.ThrottleTimer // flush writes as necessary but throttled. @@ -85,25 +85,38 @@ type MConnection struct { RemoteAddress *NetAddress } -func NewMConnection(config cfg.Config, conn net.Conn, chDescs []*ChannelDescriptor, onReceive receiveCbFunc, onError errorCbFunc) *MConnection { +// MConnectionConfig is a MConnection configuration +type MConnectionConfig struct { + SendRate int64 + RecvRate int64 +} + +// NewMConnection wraps net.Conn and creates multiplex connection +func NewMConnection(conn net.Conn, chDescs []*ChannelDescriptor, onReceive receiveCbFunc, onError errorCbFunc) *MConnection { + return NewMConnectionWithConfig( + conn, + chDescs, + onReceive, + onError, + &MConnectionConfig{ + SendRate: defaultSendRate, + RecvRate: defaultRecvRate, + }) +} + +// NewMConnectionWithConfig wraps net.Conn and creates multiplex connection with a config +func NewMConnectionWithConfig(conn net.Conn, chDescs []*ChannelDescriptor, onReceive receiveCbFunc, onError errorCbFunc, config *MConnectionConfig) *MConnection { mconn := &MConnection{ conn: conn, bufReader: bufio.NewReaderSize(conn, minReadBufferSize), bufWriter: bufio.NewWriterSize(conn, minWriteBufferSize), sendMonitor: flow.New(0, 0), recvMonitor: flow.New(0, 0), - sendRate: int64(config.GetInt(configKeySendRate)), - recvRate: int64(config.GetInt(configKeyRecvRate)), send: make(chan struct{}, 1), pong: make(chan struct{}), onReceive: onReceive, onError: onError, - - // Initialized in Start() - quit: nil, - flushTimer: nil, - pingTimer: nil, - chStatsTimer: nil, + config: config, LocalAddress: NewNetAddress(conn.LocalAddr()), RemoteAddress: NewNetAddress(conn.RemoteAddr()), @@ -313,7 +326,7 @@ func (c *MConnection) sendSomeMsgPackets() bool { // Block until .sendMonitor says we can write. // Once we're ready we send more than we asked for, // but amortized it should even out. - c.sendMonitor.Limit(maxMsgPacketTotalSize, atomic.LoadInt64(&c.sendRate), true) + c.sendMonitor.Limit(maxMsgPacketTotalSize, atomic.LoadInt64(&c.config.SendRate), true) // Now send some msgPackets. for i := 0; i < numBatchMsgPackets; i++ { @@ -371,7 +384,7 @@ func (c *MConnection) recvRoutine() { FOR_LOOP: for { // Block until .recvMonitor says we can read. - c.recvMonitor.Limit(maxMsgPacketTotalSize, atomic.LoadInt64(&c.recvRate), true) + c.recvMonitor.Limit(maxMsgPacketTotalSize, atomic.LoadInt64(&c.config.RecvRate), true) /* // Peek into bufReader for debugging diff --git a/connection_test.go b/connection_test.go index 79a7227a2..cd6bb4a8f 100644 --- a/connection_test.go +++ b/connection_test.go @@ -7,7 +7,6 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - cfg "github.com/tendermint/go-config" p2p "github.com/tendermint/go-p2p" ) @@ -20,10 +19,8 @@ func createMConnection(conn net.Conn) *p2p.MConnection { } func createMConnectionWithCallbacks(conn net.Conn, onReceive func(chID byte, msgBytes []byte), onError func(r interface{})) *p2p.MConnection { - config := cfg.NewMapConfig(map[string]interface{}{"send_rate": 512000, "recv_rate": 512000}) chDescs := []*p2p.ChannelDescriptor{&p2p.ChannelDescriptor{ID: 0x01, Priority: 1}} - - return p2p.NewMConnection(config, conn, chDescs, onReceive, onError) + return p2p.NewMConnection(conn, chDescs, onReceive, onError) } func TestMConnectionSend(t *testing.T) { @@ -104,7 +101,7 @@ func TestMConnectionStatus(t *testing.T) { assert.Zero(status.Channels[0].SendQueueSize) } -func TestMConnectionNonPersistent(t *testing.T) { +func TestMConnectionStopsAndReturnsError(t *testing.T) { assert, require := assert.New(t), require.New(t) server, client := net.Pipe() diff --git a/peer.go b/peer.go index 7a2d647f8..6b1b47a1f 100644 --- a/peer.go +++ b/peer.go @@ -61,7 +61,11 @@ func newPeer(config cfg.Config, conn net.Conn, peerNodeInfo *NodeInfo, outbound p.Stop() onPeerError(p, r) } - mconn := NewMConnection(config, conn, chDescs, onReceive, onError) + mconnConfig := &MConnectionConfig{ + SendRate: int64(config.GetInt(configKeySendRate)), + RecvRate: int64(config.GetInt(configKeyRecvRate)), + } + mconn := NewMConnectionWithConfig(conn, chDescs, onReceive, onError, mconnConfig) p = &Peer{ outbound: outbound, mconn: mconn, diff --git a/switch.go b/switch.go index eed8ceea5..78a3020ed 100644 --- a/switch.go +++ b/switch.go @@ -193,7 +193,7 @@ func (sw *Switch) OnStop() { } // NOTE: This performs a blocking handshake before the peer is added. -// CONTRACT: Iff error is returned, peer is nil, and conn is immediately closed. +// CONTRACT: If error is returned, peer is nil, and conn is immediately closed. func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool) (*Peer, error) { // Filter by addr (ie. ip:port) From f88d56b2f832020bc4ce7bc7e732bb5a985cba4b Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Mon, 10 Apr 2017 15:17:49 +0400 Subject: [PATCH 122/309] add glide --- .gitignore | 5 +--- glide.lock | 71 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ glide.yaml | 23 ++++++++++++++++++ 3 files changed, 95 insertions(+), 4 deletions(-) create mode 100644 glide.lock create mode 100644 glide.yaml diff --git a/.gitignore b/.gitignore index c765108df..62f28681c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,2 @@ -*.swp -*.swo -*.bak -.DS_Store vendor +.glide diff --git a/glide.lock b/glide.lock new file mode 100644 index 000000000..797c86031 --- /dev/null +++ b/glide.lock @@ -0,0 +1,71 @@ +hash: 92a49cbcf88a339e4d29559fe291c30e61eacda1020fd04dfcd97de834e18b3e +updated: 2017-04-10T11:17:14.66226896Z +imports: +- name: github.com/btcsuite/btcd + version: 4b348c1d33373d672edd83fc576892d0e46686d2 + subpackages: + - btcec +- name: github.com/BurntSushi/toml + version: b26d9c308763d68093482582cea63d69be07a0f0 +- name: github.com/go-stack/stack + version: 100eb0c0a9c5b306ca2fb4f165df21d80ada4b82 +- name: github.com/mattn/go-colorable + version: ded68f7a9561c023e790de24279db7ebf473ea80 +- name: github.com/mattn/go-isatty + version: fc9e8d8ef48496124e79ae0df75490096eccf6fe +- name: github.com/pkg/errors + version: ff09b135c25aae272398c51a07235b90a75aa4f0 +- name: github.com/tendermint/ed25519 + version: 1f52c6f8b8a5c7908aff4497c186af344b428925 + subpackages: + - edwards25519 + - extra25519 +- name: github.com/tendermint/go-common + version: dcb015dff6c7af21e65c8e2f3b450df19d38c777 +- name: github.com/tendermint/go-config + version: 620dcbbd7d587cf3599dedbf329b64311b0c307a +- name: github.com/tendermint/go-crypto + version: 3f47cfac5fcd9e0f1727c7db980b3559913b3e3a +- name: github.com/tendermint/go-data + version: c955b191240568440ea902e14dad2ce19727543a +- name: github.com/tendermint/go-flowrate + version: a20c98e61957faa93b4014fbd902f20ab9317a6a + subpackages: + - flowrate +- name: github.com/tendermint/go-logger + version: cefb3a45c0bf3c493a04e9bcd9b1540528be59f2 +- name: github.com/tendermint/go-wire + version: f530b7af7a8b06e612c2063bff6ace49060a085e +- name: github.com/tendermint/log15 + version: ae0f3d6450da9eac7074b439c8e1c3cabf0d5ce6 + subpackages: + - term +- name: golang.org/x/crypto + version: 9ef620b9ca2f82b55030ffd4f41327fa9e77a92c + subpackages: + - curve25519 + - nacl/box + - nacl/secretbox + - openpgp/armor + - openpgp/errors + - poly1305 + - ripemd160 + - salsa20/salsa +- name: golang.org/x/sys + version: f3918c30c5c2cb527c0b071a27c35120a6c0719a + subpackages: + - unix +testImports: +- name: github.com/davecgh/go-spew + version: 04cdfd42973bb9c8589fd6a731800cf222fde1a9 + subpackages: + - spew +- name: github.com/pmezard/go-difflib + version: d8ed2627bdf02c080bf22230dbb337003b7aba2d + subpackages: + - difflib +- name: github.com/stretchr/testify + version: 4d4bfba8f1d1027c4fdbe371823030df51419987 + subpackages: + - assert + - require diff --git a/glide.yaml b/glide.yaml new file mode 100644 index 000000000..cf71cc670 --- /dev/null +++ b/glide.yaml @@ -0,0 +1,23 @@ +package: github.com/tendermint/go-p2p +import: +- package: github.com/tendermint/go-common +- package: github.com/tendermint/go-config +- package: github.com/tendermint/go-crypto +- package: github.com/tendermint/go-data + version: c955b191240568440ea902e14dad2ce19727543a +- package: github.com/tendermint/go-flowrate + subpackages: + - flowrate +- package: github.com/tendermint/go-logger +- package: github.com/tendermint/go-wire +- package: github.com/tendermint/log15 +- package: golang.org/x/crypto + subpackages: + - nacl/box + - nacl/secretbox + - ripemd160 +testImport: +- package: github.com/stretchr/testify + subpackages: + - assert + - require From 8bb3a2e1d7b1152f5d6043a5ccca7c3fbdd9a993 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Fri, 7 Apr 2017 14:57:03 +0400 Subject: [PATCH 123/309] persistent peers (Refs #13) --- peer.go | 208 +++++++++++++++++++++++++++++++++++++++---------- pex_reactor.go | 4 +- switch.go | 175 +++++++++++++++++++++-------------------- switch_test.go | 131 ++++++++++++++++++++++++++++--- 4 files changed, 380 insertions(+), 138 deletions(-) diff --git a/peer.go b/peer.go index 6b1b47a1f..d94ce5838 100644 --- a/peer.go +++ b/peer.go @@ -4,105 +4,187 @@ import ( "fmt" "io" "net" + "time" - . "github.com/tendermint/go-common" + cmn "github.com/tendermint/go-common" cfg "github.com/tendermint/go-config" - "github.com/tendermint/go-wire" + crypto "github.com/tendermint/go-crypto" + wire "github.com/tendermint/go-wire" ) +// Peer could be marked as persistent, in which case you can use +// Redial function to reconnect. Note that inbound peers can't be +// made persistent. They should be made persistent on the other end. +// +// Before using a peer, you will need to perform a handshake on connection. type Peer struct { - BaseService + cmn.BaseService outbound bool - mconn *MConnection + + conn net.Conn // source connection + mconn *MConnection // multiplex connection + + authEnc bool // authenticated encryption + persistent bool + config cfg.Config *NodeInfo Key string - Data *CMap // User data. + Data *cmn.CMap // User data. } +func newPeer(addr *NetAddress, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), config cfg.Config, privKey crypto.PrivKeyEd25519) (*Peer, error) { + conn, err := dial(addr, config) + if err != nil { + return nil, err + } + + // outbound = true + return newPeerFromExistingConn(conn, true, reactorsByCh, chDescs, onPeerError, config, privKey) +} + +func newPeerFromExistingConn(conn net.Conn, outbound bool, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), config cfg.Config, privKey crypto.PrivKeyEd25519) (*Peer, error) { + // Encrypt connection + if config.GetBool(configKeyAuthEnc) { + var err error + conn, err = MakeSecretConnection(conn, privKey) + if err != nil { + return nil, err + } + } + + p := &Peer{ + outbound: outbound, + authEnc: config.GetBool(configKeyAuthEnc), + conn: conn, + config: config, + Data: cmn.NewCMap(), + } + + p.mconn = createMConnection(conn, p, reactorsByCh, chDescs, onPeerError, config) + + p.BaseService = *cmn.NewBaseService(log, "Peer", p) + + return p, nil +} + +// CloseConn should be used when the peer was created, but never started. +func (p *Peer) CloseConn() { + p.conn.Close() +} + +// MakePersistent marks the peer as persistent. +func (p *Peer) MakePersistent() { + if !p.outbound { + panic("inbound peers can't be made persistent") + } + + p.persistent = true +} + +// IsPersistent returns true if the peer is persitent, false otherwise. +func (p *Peer) IsPersistent() bool { + return p.persistent +} + +// HandshakeTimeout performs a handshake between a given node and the peer. // NOTE: blocking -// Before creating a peer with newPeer(), perform a handshake on connection. -func peerHandshake(conn net.Conn, ourNodeInfo *NodeInfo) (*NodeInfo, error) { +func (p *Peer) HandshakeTimeout(ourNodeInfo *NodeInfo, timeout time.Duration) error { + // Set deadline for handshake so we don't block forever on conn.ReadFull + p.conn.SetDeadline(time.Now().Add(timeout)) + var peerNodeInfo = new(NodeInfo) var err1 error var err2 error - Parallel( + cmn.Parallel( func() { var n int - wire.WriteBinary(ourNodeInfo, conn, &n, &err1) + wire.WriteBinary(ourNodeInfo, p.conn, &n, &err1) }, func() { var n int - wire.ReadBinary(peerNodeInfo, conn, maxNodeInfoSize, &n, &err2) + wire.ReadBinary(peerNodeInfo, p.conn, maxNodeInfoSize, &n, &err2) log.Notice("Peer handshake", "peerNodeInfo", peerNodeInfo) }) if err1 != nil { - return nil, err1 + return err1 } if err2 != nil { - return nil, err2 + return err2 } - peerNodeInfo.RemoteAddr = conn.RemoteAddr().String() - return peerNodeInfo, nil -} -// NOTE: call peerHandshake on conn before calling newPeer(). -func newPeer(config cfg.Config, conn net.Conn, peerNodeInfo *NodeInfo, outbound bool, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{})) *Peer { - var p *Peer - onReceive := func(chID byte, msgBytes []byte) { - reactor := reactorsByCh[chID] - if reactor == nil { - PanicSanity(Fmt("Unknown channel %X", chID)) + if p.authEnc { + // Check that the professed PubKey matches the sconn's. + if !peerNodeInfo.PubKey.Equals(p.PubKey()) { + return fmt.Errorf("Ignoring connection with unmatching pubkey: %v vs %v", + peerNodeInfo.PubKey, p.PubKey()) } - reactor.Receive(chID, p, msgBytes) } - onError := func(r interface{}) { - p.Stop() - onPeerError(p, r) - } - mconnConfig := &MConnectionConfig{ - SendRate: int64(config.GetInt(configKeySendRate)), - RecvRate: int64(config.GetInt(configKeyRecvRate)), - } - mconn := NewMConnectionWithConfig(conn, chDescs, onReceive, onError, mconnConfig) - p = &Peer{ - outbound: outbound, - mconn: mconn, - NodeInfo: peerNodeInfo, - Key: peerNodeInfo.PubKey.KeyString(), - Data: NewCMap(), - } - p.BaseService = *NewBaseService(log, "Peer", p) - return p + + // Remove deadline + p.conn.SetDeadline(time.Time{}) + + peerNodeInfo.RemoteAddr = p.RemoteAddr().String() + + p.NodeInfo = peerNodeInfo + p.Key = peerNodeInfo.PubKey.KeyString() + + return nil } +// RemoteAddr returns the remote network address. +func (p *Peer) RemoteAddr() net.Addr { + return p.conn.RemoteAddr() +} + +// PubKey returns the remote public key. +func (p *Peer) PubKey() crypto.PubKeyEd25519 { + if p.authEnc { + return p.conn.(*SecretConnection).RemotePubKey() + } + if p.NodeInfo == nil { + panic("Attempt to get peer's PubKey before calling Handshake") + } + return p.PubKey() +} + +// OnStart implements BaseService. func (p *Peer) OnStart() error { p.BaseService.OnStart() _, err := p.mconn.Start() return err } +// OnStop implements BaseService. func (p *Peer) OnStop() { p.BaseService.OnStop() p.mconn.Stop() } +// Connection returns underlying MConnection. func (p *Peer) Connection() *MConnection { return p.mconn } +// IsOutbound returns true if the connection is outbound, false otherwise. func (p *Peer) IsOutbound() bool { return p.outbound } +// Send msg to the channel identified by chID byte. Returns false if the send +// queue is full after timeout, specified by MConnection. func (p *Peer) Send(chID byte, msg interface{}) bool { if !p.IsRunning() { + // see Switch#Broadcast, where we fetch the list of peers and loop over + // them - while we're looping, one peer may be removed and stopped. return false } return p.mconn.Send(chID, msg) } +// TrySend msg to the channel identified by chID byte. Immediately returns +// false if the send queue is full. func (p *Peer) TrySend(chID byte, msg interface{}) bool { if !p.IsRunning() { return false @@ -110,6 +192,7 @@ func (p *Peer) TrySend(chID byte, msg interface{}) bool { return p.mconn.TrySend(chID, msg) } +// CanSend returns true if the send queue is not full, false otherwise. func (p *Peer) CanSend(chID byte) bool { if !p.IsRunning() { return false @@ -117,6 +200,7 @@ func (p *Peer) CanSend(chID byte) bool { return p.mconn.CanSend(chID) } +// WriteTo writes the peer's public key to w. func (p *Peer) WriteTo(w io.Writer) (n int64, err error) { var n_ int wire.WriteString(p.Key, w, &n_, &err) @@ -124,18 +208,56 @@ func (p *Peer) WriteTo(w io.Writer) (n int64, err error) { return } +// String representation. func (p *Peer) String() string { if p.outbound { return fmt.Sprintf("Peer{%v %v out}", p.mconn, p.Key[:12]) - } else { - return fmt.Sprintf("Peer{%v %v in}", p.mconn, p.Key[:12]) } + + return fmt.Sprintf("Peer{%v %v in}", p.mconn, p.Key[:12]) } +// Equals reports whenever 2 peers are actually represent the same node. func (p *Peer) Equals(other *Peer) bool { return p.Key == other.Key } +// Get the data for a given key. func (p *Peer) Get(key string) interface{} { return p.Data.Get(key) } + +func dial(addr *NetAddress, config cfg.Config) (net.Conn, error) { + log.Info("Dialing address", "address", addr) + conn, err := addr.DialTimeout(time.Duration( + config.GetInt(configKeyDialTimeoutSeconds)) * time.Second) + if err != nil { + log.Info("Failed dialing address", "address", addr, "error", err) + return nil, err + } + if config.GetBool(configFuzzEnable) { + conn = FuzzConn(config, conn) + } + return conn, nil +} + +func createMConnection(conn net.Conn, p *Peer, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), config cfg.Config) *MConnection { + onReceive := func(chID byte, msgBytes []byte) { + reactor := reactorsByCh[chID] + if reactor == nil { + cmn.PanicSanity(cmn.Fmt("Unknown channel %X", chID)) + } + reactor.Receive(chID, p, msgBytes) + } + + onError := func(r interface{}) { + onPeerError(p, r) + } + + mconnConfig := &MConnectionConfig{ + SendRate: int64(config.GetInt(configKeySendRate)), + RecvRate: int64(config.GetInt(configKeyRecvRate)), + } + + return NewMConnectionWithConfig(conn, chDescs, onReceive, onError, mconnConfig) +} diff --git a/pex_reactor.go b/pex_reactor.go index 45c4c96d8..4ac9306cf 100644 --- a/pex_reactor.go +++ b/pex_reactor.go @@ -9,7 +9,7 @@ import ( "time" . "github.com/tendermint/go-common" - "github.com/tendermint/go-wire" + wire "github.com/tendermint/go-wire" ) var pexErrInvalidMessage = errors.New("Invalid PEX message") @@ -201,7 +201,7 @@ func (pexR *PEXReactor) ensurePeers() { // Dial picked addresses for _, item := range toDial.Values() { go func(picked *NetAddress) { - _, err := pexR.Switch.DialPeerWithAddress(picked) + _, err := pexR.Switch.DialPeerWithAddress(picked, false) if err != nil { pexR.book.MarkAttempt(picked) } diff --git a/switch.go b/switch.go index 78a3020ed..b0551a4f8 100644 --- a/switch.go +++ b/switch.go @@ -9,10 +9,15 @@ import ( . "github.com/tendermint/go-common" cfg "github.com/tendermint/go-config" - "github.com/tendermint/go-crypto" + crypto "github.com/tendermint/go-crypto" "github.com/tendermint/log15" ) +const ( + reconnectAttempts = 30 + reconnectInterval = 3 * time.Second +) + type Reactor interface { Service // Start, Stop @@ -194,78 +199,43 @@ func (sw *Switch) OnStop() { // NOTE: This performs a blocking handshake before the peer is added. // CONTRACT: If error is returned, peer is nil, and conn is immediately closed. -func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool) (*Peer, error) { - - // Filter by addr (ie. ip:port) - if err := sw.FilterConnByAddr(conn.RemoteAddr()); err != nil { - conn.Close() - return nil, err +func (sw *Switch) AddPeer(peer *Peer) error { + if err := sw.FilterConnByAddr(peer.RemoteAddr()); err != nil { + return err } - // Set deadline for handshake so we don't block forever on conn.ReadFull - conn.SetDeadline(time.Now().Add( - time.Duration(sw.config.GetInt(configKeyHandshakeTimeoutSeconds)) * time.Second)) - - // First, encrypt the connection. - var sconn net.Conn = conn - if sw.config.GetBool(configKeyAuthEnc) { - var err error - sconn, err = MakeSecretConnection(conn, sw.nodePrivKey) - if err != nil { - conn.Close() - return nil, err - } + if err := sw.FilterConnByPubKey(peer.PubKey()); err != nil { + return err } - // Filter by p2p-key - if err := sw.FilterConnByPubKey(sconn.(*SecretConnection).RemotePubKey()); err != nil { - sconn.Close() - return nil, err + if err := peer.HandshakeTimeout(sw.nodeInfo, time.Duration(sw.config.GetInt(configKeyHandshakeTimeoutSeconds))*time.Second); err != nil { + return err } - // Then, perform node handshake - peerNodeInfo, err := peerHandshake(sconn, sw.nodeInfo) - if err != nil { - sconn.Close() - return nil, err - } - if sw.config.GetBool(configKeyAuthEnc) { - // Check that the professed PubKey matches the sconn's. - if !peerNodeInfo.PubKey.Equals(sconn.(*SecretConnection).RemotePubKey()) { - sconn.Close() - return nil, fmt.Errorf("Ignoring connection with unmatching pubkey: %v vs %v", - peerNodeInfo.PubKey, sconn.(*SecretConnection).RemotePubKey()) - } - } // Avoid self - if peerNodeInfo.PubKey.Equals(sw.nodeInfo.PubKey) { - sconn.Close() - return nil, fmt.Errorf("Ignoring connection from self") - } - // Check version, chain id - if err := sw.nodeInfo.CompatibleWith(peerNodeInfo); err != nil { - sconn.Close() - return nil, err + if sw.nodeInfo.PubKey.Equals(peer.PubKey()) { + return errors.New("Ignoring connection from self") } - peer := newPeer(sw.config, sconn, peerNodeInfo, outbound, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError) + // Check version, chain id + if err := sw.nodeInfo.CompatibleWith(peer.NodeInfo); err != nil { + return err + } // Add the peer to .peers // ignore if duplicate or if we already have too many for that IP range if err := sw.peers.Add(peer); err != nil { log.Notice("Ignoring peer", "error", err, "peer", peer) - peer.Stop() - return nil, err + return err } - // remove deadline and start peer - conn.SetDeadline(time.Time{}) + // Start peer if sw.IsRunning() { sw.startInitPeer(peer) } log.Notice("Added peer", "peer", peer) - return peer, nil + return nil } func (sw *Switch) FilterConnByAddr(addr net.Addr) error { @@ -292,8 +262,10 @@ func (sw *Switch) SetPubKeyFilter(f func(crypto.PubKeyEd25519) error) { } func (sw *Switch) startInitPeer(peer *Peer) { - peer.Start() // spawn send/recv routines - sw.addPeerToReactors(peer) // run AddPeer on each reactor + peer.Start() // spawn send/recv routines + for _, reactor := range sw.reactors { + reactor.AddPeer(peer) + } } // Dial a list of seeds asynchronously in random order @@ -331,7 +303,7 @@ func (sw *Switch) DialSeeds(addrBook *AddrBook, seeds []string) error { } func (sw *Switch) dialSeed(addr *NetAddress) { - peer, err := sw.DialPeerWithAddress(addr) + peer, err := sw.DialPeerWithAddress(addr, true) if err != nil { log.Error("Error dialing seed", "error", err) return @@ -340,22 +312,23 @@ func (sw *Switch) dialSeed(addr *NetAddress) { } } -func (sw *Switch) DialPeerWithAddress(addr *NetAddress) (*Peer, error) { - log.Info("Dialing address", "address", addr) +func (sw *Switch) DialPeerWithAddress(addr *NetAddress, persistent bool) (*Peer, error) { sw.dialing.Set(addr.IP.String(), addr) - conn, err := addr.DialTimeout(time.Duration( - sw.config.GetInt(configKeyDialTimeoutSeconds)) * time.Second) - sw.dialing.Delete(addr.IP.String()) + defer sw.dialing.Delete(addr.IP.String()) + + peer, err := newPeer(addr, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.config, sw.nodePrivKey) + if persistent { + peer.MakePersistent() + } if err != nil { - log.Info("Failed dialing address", "address", addr, "error", err) + log.Info("Failed dialing peer", "address", addr, "error", err) + peer.CloseConn() return nil, err } - if sw.config.GetBool(configFuzzEnable) { - conn = FuzzConn(sw.config, conn) - } - peer, err := sw.AddPeerWithConnection(conn, true) + err = sw.AddPeer(peer) if err != nil { - log.Info("Failed adding peer", "address", addr, "conn", conn, "error", err) + log.Info("Failed adding peer", "address", addr, "error", err) + peer.CloseConn() return nil, err } log.Notice("Dialed and added peer", "address", addr, "peer", peer) @@ -400,31 +373,49 @@ func (sw *Switch) Peers() IPeerSet { return sw.peers } -// Disconnect from a peer due to external error. +// Disconnect from a peer due to external error, retry if it is a persistent peer. // TODO: make record depending on reason. func (sw *Switch) StopPeerForError(peer *Peer, reason interface{}) { + addr := NewNetAddress(peer.RemoteAddr()) log.Notice("Stopping peer for error", "peer", peer, "error", reason) - sw.peers.Remove(peer) - peer.Stop() - sw.removePeerFromReactors(peer, reason) + sw.stopAndRemovePeer(peer, reason) + + if peer.IsPersistent() { + go func() { + log.Notice("Reconnecting to peer", "peer", peer) + for i := 1; i < reconnectAttempts; i++ { + if !sw.IsRunning() { + return + } + + peer, err := sw.DialPeerWithAddress(addr, true) + if err != nil { + if i == reconnectAttempts { + log.Notice("Error reconnecting to peer. Giving up", "tries", i, "error", err) + return + } + log.Notice("Error reconnecting to peer. Trying again", "tries", i, "error", err) + time.Sleep(reconnectInterval) + continue + } + + log.Notice("Reconnected to peer", "peer", peer) + return + } + }() + } } // Disconnect from a peer gracefully. // TODO: handle graceful disconnects. func (sw *Switch) StopPeerGracefully(peer *Peer) { log.Notice("Stopping peer gracefully") + sw.stopAndRemovePeer(peer, nil) +} + +func (sw *Switch) stopAndRemovePeer(peer *Peer, reason interface{}) { sw.peers.Remove(peer) peer.Stop() - sw.removePeerFromReactors(peer, nil) -} - -func (sw *Switch) addPeerToReactors(peer *Peer) { - for _, reactor := range sw.reactors { - reactor.AddPeer(peer) - } -} - -func (sw *Switch) removePeerFromReactors(peer *Peer, reason interface{}) { for _, reactor := range sw.reactors { reactor.RemovePeer(peer, reason) } @@ -449,9 +440,9 @@ func (sw *Switch) listenerRoutine(l Listener) { } // New inbound connection! - _, err := sw.AddPeerWithConnection(inConn, false) + err := sw.AddPeerWithConnection(inConn, false, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.config, sw.nodePrivKey) if err != nil { - log.Notice("Ignoring inbound connection: error on AddPeerWithConnection", "address", inConn.RemoteAddr().String(), "error", err) + log.Notice("Ignoring inbound connection: error while adding peer", "address", inConn.RemoteAddr().String(), "error", err) continue } @@ -511,14 +502,14 @@ func Connect2Switches(switches []*Switch, i, j int) { c1, c2 := net.Pipe() doneCh := make(chan struct{}) go func() { - _, err := switchI.AddPeerWithConnection(c1, false) // AddPeer is blocking, requires handshake. + err := switchI.AddPeerWithConnection(c1, false, switchI.reactorsByCh, switchI.chDescs, switchI.StopPeerForError, switchI.config, switchI.nodePrivKey) if PanicOnAddPeerErr && err != nil { panic(err) } doneCh <- struct{}{} }() go func() { - _, err := switchJ.AddPeerWithConnection(c2, true) + err := switchJ.AddPeerWithConnection(c2, false, switchJ.reactorsByCh, switchJ.chDescs, switchJ.StopPeerForError, switchJ.config, switchJ.nodePrivKey) if PanicOnAddPeerErr && err != nil { panic(err) } @@ -552,3 +543,19 @@ func makeSwitch(i int, network, version string, initSwitch func(int, *Switch) *S s.SetNodePrivKey(privKey) return s } + +// AddPeerWithConnection is a helper function for testing. +func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), config cfg.Config, privKey crypto.PrivKeyEd25519) error { + peer, err := newPeerFromExistingConn(conn, outbound, reactorsByCh, chDescs, onPeerError, config, privKey) + if err != nil { + peer.CloseConn() + return err + } + + if err = sw.AddPeer(peer); err != nil { + peer.CloseConn() + return err + } + + return nil +} diff --git a/switch_test.go b/switch_test.go index 1b2ccd743..727bd2a1f 100644 --- a/switch_test.go +++ b/switch_test.go @@ -3,15 +3,19 @@ package p2p import ( "bytes" "fmt" + golog "log" "net" "sync" "testing" "time" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" . "github.com/tendermint/go-common" + cmn "github.com/tendermint/go-common" cfg "github.com/tendermint/go-config" - "github.com/tendermint/go-crypto" - "github.com/tendermint/go-wire" + crypto "github.com/tendermint/go-crypto" + wire "github.com/tendermint/go-wire" ) var ( @@ -21,7 +25,6 @@ var ( func init() { config = cfg.NewMapConfig(nil) setConfigDefaults(config) - } type PeerMessage struct { @@ -174,8 +177,12 @@ func TestConnAddrFilter(t *testing.T) { }) // connect to good peer - go s1.AddPeerWithConnection(c1, false) // AddPeer is blocking, requires handshake. - go s2.AddPeerWithConnection(c2, true) + go func() { + s1.AddPeerWithConnection(c1, false, s1.reactorsByCh, s1.chDescs, s1.StopPeerForError, s1.config, s1.nodePrivKey) + }() + go func() { + s2.AddPeerWithConnection(c2, true, s2.reactorsByCh, s2.chDescs, s2.StopPeerForError, s2.config, s2.nodePrivKey) + }() // Wait for things to happen, peers to get added... time.Sleep(100 * time.Millisecond * time.Duration(4)) @@ -205,8 +212,12 @@ func TestConnPubKeyFilter(t *testing.T) { }) // connect to good peer - go s1.AddPeerWithConnection(c1, false) // AddPeer is blocking, requires handshake. - go s2.AddPeerWithConnection(c2, true) + go func() { + s1.AddPeerWithConnection(c1, false, s1.reactorsByCh, s1.chDescs, s1.StopPeerForError, s1.config, s1.nodePrivKey) + }() + go func() { + s2.AddPeerWithConnection(c2, true, s2.reactorsByCh, s2.chDescs, s2.StopPeerForError, s2.config, s2.nodePrivKey) + }() // Wait for things to happen, peers to get added... time.Sleep(100 * time.Millisecond * time.Duration(4)) @@ -221,6 +232,63 @@ func TestConnPubKeyFilter(t *testing.T) { } } +func TestSwitchStopsNonPersistentPeerOnError(t *testing.T) { + assert, require := assert.New(t), require.New(t) + + sw := makeSwitch(1, "testing", "123.123.123", initSwitchFunc) + sw.Start() + defer sw.Stop() + + sw2 := makeSwitch(2, "testing", "123.123.123", initSwitchFunc) + defer sw2.Stop() + l, serverAddr := listenTCP() + done := make(chan struct{}) + go accept(l, done, sw2) + defer close(done) + + peer, err := newPeer(NewNetAddress(serverAddr), sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.config, sw.nodePrivKey) + require.Nil(err) + err = sw.AddPeer(peer) + require.Nil(err) + + // simulate failure by closing connection + peer.CloseConn() + + time.Sleep(100 * time.Millisecond) + + assert.Zero(sw.Peers().Size()) + assert.False(peer.IsRunning()) +} + +func TestSwitchReconnectsToPeerIfItIsPersistent(t *testing.T) { + assert, require := assert.New(t), require.New(t) + + sw := makeSwitch(1, "testing", "123.123.123", initSwitchFunc) + sw.Start() + defer sw.Stop() + + sw2 := makeSwitch(2, "testing", "123.123.123", initSwitchFunc) + defer sw2.Stop() + l, serverAddr := listenTCP() + done := make(chan struct{}) + go accept(l, done, sw2) + defer close(done) + + peer, err := newPeer(NewNetAddress(serverAddr), sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.config, sw.nodePrivKey) + peer.MakePersistent() + require.Nil(err) + err = sw.AddPeer(peer) + require.Nil(err) + + // simulate failure by closing connection + peer.CloseConn() + + time.Sleep(100 * time.Millisecond) + + assert.NotZero(sw.Peers().Size()) + assert.False(peer.IsRunning()) +} + func BenchmarkSwitches(b *testing.B) { b.StopTimer() @@ -252,9 +320,9 @@ func BenchmarkSwitches(b *testing.B) { successChan := s1.Broadcast(chID, "test data") for s := range successChan { if s { - numSuccess += 1 + numSuccess++ } else { - numFailure += 1 + numFailure++ } } } @@ -266,3 +334,48 @@ func BenchmarkSwitches(b *testing.B) { time.Sleep(1000 * time.Millisecond) } + +func listenTCP() (net.Listener, net.Addr) { + l, e := net.Listen("tcp", "127.0.0.1:0") // any available address + if e != nil { + golog.Fatalf("net.Listen tcp :0: %+v", e) + } + return l, l.Addr() +} + +// simulate remote peer +func accept(l net.Listener, done <-chan struct{}, sw *Switch) { + for { + conn, err := l.Accept() + if err != nil { + golog.Fatalf("Failed to accept conn: %+v", err) + } + conn, err = MakeSecretConnection(conn, sw.nodePrivKey) + if err != nil { + golog.Fatalf("Failed to make secret conn: %+v", err) + } + var err1, err2 error + nodeInfo := new(NodeInfo) + cmn.Parallel( + func() { + var n int + wire.WriteBinary(sw.nodeInfo, conn, &n, &err1) + }, + func() { + var n int + wire.ReadBinary(nodeInfo, conn, maxNodeInfoSize, &n, &err2) + }) + if err1 != nil { + golog.Fatalf("Failed to do handshake: %+v", err1) + } + if err2 != nil { + golog.Fatalf("Failed to do handshake: %+v", err2) + } + select { + case <-done: + conn.Close() + return + default: + } + } +} From a9bb6734e7f739be52b76575c82ed9091363df08 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Mon, 10 Apr 2017 15:59:32 -0400 Subject: [PATCH 124/309] SetDeadline for authEnc. Stop peer if Add fails --- peer.go | 6 ++++++ switch.go | 3 ++- switch_test.go | 2 +- 3 files changed, 9 insertions(+), 2 deletions(-) diff --git a/peer.go b/peer.go index d94ce5838..657162de9 100644 --- a/peer.go +++ b/peer.go @@ -48,12 +48,18 @@ func newPeerFromExistingConn(conn net.Conn, outbound bool, reactorsByCh map[byte // Encrypt connection if config.GetBool(configKeyAuthEnc) { var err error + // Set deadline for handshake so we don't block forever on conn.ReadFull + timeout := time.Duration(config.GetInt(configKeyHandshakeTimeoutSeconds)) * time.Second + conn.SetDeadline(time.Now().Add(timeout)) conn, err = MakeSecretConnection(conn, privKey) if err != nil { return nil, err } + // remove deadline + conn.SetDeadline(time.Time{}) } + // Key and NodeInfo are set after Handshake p := &Peer{ outbound: outbound, authEnc: config.GetBool(configKeyAuthEnc), diff --git a/switch.go b/switch.go index b0551a4f8..655c24f97 100644 --- a/switch.go +++ b/switch.go @@ -226,6 +226,7 @@ func (sw *Switch) AddPeer(peer *Peer) error { // ignore if duplicate or if we already have too many for that IP range if err := sw.peers.Add(peer); err != nil { log.Notice("Ignoring peer", "error", err, "peer", peer) + peer.Stop() return err } @@ -544,7 +545,7 @@ func makeSwitch(i int, network, version string, initSwitch func(int, *Switch) *S return s } -// AddPeerWithConnection is a helper function for testing. +// AddPeerWithConnection creates a newPeer from the connection, performs the handshake, and adds it to the switch. func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), config cfg.Config, privKey crypto.PrivKeyEd25519) error { peer, err := newPeerFromExistingConn(conn, outbound, reactorsByCh, chDescs, onPeerError, config, privKey) if err != nil { diff --git a/switch_test.go b/switch_test.go index 727bd2a1f..e3fa6876f 100644 --- a/switch_test.go +++ b/switch_test.go @@ -260,7 +260,7 @@ func TestSwitchStopsNonPersistentPeerOnError(t *testing.T) { assert.False(peer.IsRunning()) } -func TestSwitchReconnectsToPeerIfItIsPersistent(t *testing.T) { +func TestSwitchReconnectsToPersistentPeer(t *testing.T) { assert, require := assert.New(t), require.New(t) sw := makeSwitch(1, "testing", "123.123.123", initSwitchFunc) From b6f744c732d55c34b7f25cfbd0b409805fd89150 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Mon, 10 Apr 2017 16:03:14 -0400 Subject: [PATCH 125/309] fix AddPeerWithConnection --- switch.go | 10 +++++----- switch_test.go | 8 ++++---- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/switch.go b/switch.go index 655c24f97..dff9256f3 100644 --- a/switch.go +++ b/switch.go @@ -441,7 +441,7 @@ func (sw *Switch) listenerRoutine(l Listener) { } // New inbound connection! - err := sw.AddPeerWithConnection(inConn, false, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.config, sw.nodePrivKey) + err := sw.AddPeerWithConnection(inConn, false) if err != nil { log.Notice("Ignoring inbound connection: error while adding peer", "address", inConn.RemoteAddr().String(), "error", err) continue @@ -503,14 +503,14 @@ func Connect2Switches(switches []*Switch, i, j int) { c1, c2 := net.Pipe() doneCh := make(chan struct{}) go func() { - err := switchI.AddPeerWithConnection(c1, false, switchI.reactorsByCh, switchI.chDescs, switchI.StopPeerForError, switchI.config, switchI.nodePrivKey) + err := switchI.AddPeerWithConnection(c1, false) if PanicOnAddPeerErr && err != nil { panic(err) } doneCh <- struct{}{} }() go func() { - err := switchJ.AddPeerWithConnection(c2, false, switchJ.reactorsByCh, switchJ.chDescs, switchJ.StopPeerForError, switchJ.config, switchJ.nodePrivKey) + err := switchJ.AddPeerWithConnection(c2, false) if PanicOnAddPeerErr && err != nil { panic(err) } @@ -546,8 +546,8 @@ func makeSwitch(i int, network, version string, initSwitch func(int, *Switch) *S } // AddPeerWithConnection creates a newPeer from the connection, performs the handshake, and adds it to the switch. -func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), config cfg.Config, privKey crypto.PrivKeyEd25519) error { - peer, err := newPeerFromExistingConn(conn, outbound, reactorsByCh, chDescs, onPeerError, config, privKey) +func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool) error { + peer, err := newPeerFromExistingConn(conn, outbound, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.config, sw.nodePrivKey) if err != nil { peer.CloseConn() return err diff --git a/switch_test.go b/switch_test.go index e3fa6876f..8cfcb8c6e 100644 --- a/switch_test.go +++ b/switch_test.go @@ -178,10 +178,10 @@ func TestConnAddrFilter(t *testing.T) { // connect to good peer go func() { - s1.AddPeerWithConnection(c1, false, s1.reactorsByCh, s1.chDescs, s1.StopPeerForError, s1.config, s1.nodePrivKey) + s1.AddPeerWithConnection(c1, false) }() go func() { - s2.AddPeerWithConnection(c2, true, s2.reactorsByCh, s2.chDescs, s2.StopPeerForError, s2.config, s2.nodePrivKey) + s2.AddPeerWithConnection(c2, true) }() // Wait for things to happen, peers to get added... @@ -213,10 +213,10 @@ func TestConnPubKeyFilter(t *testing.T) { // connect to good peer go func() { - s1.AddPeerWithConnection(c1, false, s1.reactorsByCh, s1.chDescs, s1.StopPeerForError, s1.config, s1.nodePrivKey) + s1.AddPeerWithConnection(c1, false) }() go func() { - s2.AddPeerWithConnection(c2, true, s2.reactorsByCh, s2.chDescs, s2.StopPeerForError, s2.config, s2.nodePrivKey) + s2.AddPeerWithConnection(c2, true) }() // Wait for things to happen, peers to get added... From 9a1a6c56b402e44a8ef51283112fa1886e0c5aa5 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Mon, 10 Apr 2017 16:04:55 -0400 Subject: [PATCH 126/309] dont expose makePersistent --- peer.go | 4 ++-- switch.go | 2 +- switch_test.go | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/peer.go b/peer.go index 657162de9..92d4973d8 100644 --- a/peer.go +++ b/peer.go @@ -80,8 +80,8 @@ func (p *Peer) CloseConn() { p.conn.Close() } -// MakePersistent marks the peer as persistent. -func (p *Peer) MakePersistent() { +// makePersistent marks the peer as persistent. +func (p *Peer) makePersistent() { if !p.outbound { panic("inbound peers can't be made persistent") } diff --git a/switch.go b/switch.go index dff9256f3..fcde27449 100644 --- a/switch.go +++ b/switch.go @@ -319,7 +319,7 @@ func (sw *Switch) DialPeerWithAddress(addr *NetAddress, persistent bool) (*Peer, peer, err := newPeer(addr, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.config, sw.nodePrivKey) if persistent { - peer.MakePersistent() + peer.makePersistent() } if err != nil { log.Info("Failed dialing peer", "address", addr, "error", err) diff --git a/switch_test.go b/switch_test.go index 8cfcb8c6e..a9abfa0a5 100644 --- a/switch_test.go +++ b/switch_test.go @@ -275,7 +275,7 @@ func TestSwitchReconnectsToPersistentPeer(t *testing.T) { defer close(done) peer, err := newPeer(NewNetAddress(serverAddr), sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.config, sw.nodePrivKey) - peer.MakePersistent() + peer.makePersistent() require.Nil(err) err = sw.AddPeer(peer) require.Nil(err) From 9d18cbe74e66f875afa36d2fa3be280e4a2dc9e6 Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Tue, 11 Apr 2017 13:29:49 +0200 Subject: [PATCH 127/309] Remove race condition between read go-routine and stop --- client/ws_client.go | 4 +++- server/handlers.go | 7 +++++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/client/ws_client.go b/client/ws_client.go index 9ed2be8c5..9933ab073 100644 --- a/client/ws_client.go +++ b/client/ws_client.go @@ -86,7 +86,6 @@ func (wsc *WSClient) dial() error { func (wsc *WSClient) OnStop() { wsc.BaseService.OnStop() wsc.Conn.Close() - wsc.Conn = nil // ResultsCh/ErrorsCh is closed in receiveEventsRoutine. } @@ -112,6 +111,9 @@ func (wsc *WSClient) receiveEventsRoutine() { wsc.ResultsCh <- *response.Result } } + // this must be modified in the same go-routine that reads from the + // connection to avoid race conditions + wsc.Conn = nil // Cleanup close(wsc.ResultsCh) diff --git a/server/handlers.go b/server/handlers.go index 5b6008504..573696fb6 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -347,12 +347,15 @@ func NewWSConnection(baseConn *websocket.Conn, funcMap map[string]*RPCFunc, evsw func (wsc *wsConnection) OnStart() error { wsc.BaseService.OnStart() + // these must be set before the readRoutine is created, as it may + // call wsc.Stop(), which accesses these timers + wsc.readTimeout = time.NewTimer(time.Second * wsReadTimeoutSeconds) + wsc.pingTicker = time.NewTicker(time.Second * wsPingTickerSeconds) + // Read subscriptions/unsubscriptions to events go wsc.readRoutine() // Custom Ping handler to touch readTimeout - wsc.readTimeout = time.NewTimer(time.Second * wsReadTimeoutSeconds) - wsc.pingTicker = time.NewTicker(time.Second * wsPingTickerSeconds) wsc.baseConn.SetPingHandler(func(m string) error { // NOTE: https://github.com/gorilla/websocket/issues/97 go wsc.baseConn.WriteControl(websocket.PongMessage, []byte(m), time.Now().Add(time.Second*wsWriteTimeoutSeconds)) From 8067cdb5f240ebb288394ef03c65414ba9e4a08c Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Tue, 11 Apr 2017 12:42:11 -0400 Subject: [PATCH 128/309] fix closing conn --- peer.go | 7 ++++++- switch.go | 9 ++++----- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/peer.go b/peer.go index 92d4973d8..1be50aff1 100644 --- a/peer.go +++ b/peer.go @@ -41,7 +41,12 @@ func newPeer(addr *NetAddress, reactorsByCh map[byte]Reactor, chDescs []*Channel } // outbound = true - return newPeerFromExistingConn(conn, true, reactorsByCh, chDescs, onPeerError, config, privKey) + peer, err := newPeerFromExistingConn(conn, true, reactorsByCh, chDescs, onPeerError, config, privKey) + if err != nil { + conn.Close() + return nil, err + } + return peer, nil } func newPeerFromExistingConn(conn net.Conn, outbound bool, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), config cfg.Config, privKey crypto.PrivKeyEd25519) (*Peer, error) { diff --git a/switch.go b/switch.go index fcde27449..f38d4feb1 100644 --- a/switch.go +++ b/switch.go @@ -318,14 +318,13 @@ func (sw *Switch) DialPeerWithAddress(addr *NetAddress, persistent bool) (*Peer, defer sw.dialing.Delete(addr.IP.String()) peer, err := newPeer(addr, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.config, sw.nodePrivKey) - if persistent { - peer.makePersistent() - } if err != nil { log.Info("Failed dialing peer", "address", addr, "error", err) - peer.CloseConn() return nil, err } + if persistent { + peer.makePersistent() + } err = sw.AddPeer(peer) if err != nil { log.Info("Failed adding peer", "address", addr, "error", err) @@ -549,7 +548,7 @@ func makeSwitch(i int, network, version string, initSwitch func(int, *Switch) *S func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool) error { peer, err := newPeerFromExistingConn(conn, outbound, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.config, sw.nodePrivKey) if err != nil { - peer.CloseConn() + conn.Close() return err } From 7dcc3dbcd14a284e8150df8ac1bae96d774499cc Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Tue, 11 Apr 2017 19:47:05 +0400 Subject: [PATCH 129/309] test peer --- config.go | 2 - connection.go | 20 ++++--- fuzz.go | 145 +++++++++++++++++++++++++++++++++---------------- peer.go | 85 +++++++++++++++++++---------- peer_test.go | 120 ++++++++++++++++++++++++++++++++++++++++ switch.go | 45 ++++++++++++--- switch_test.go | 71 ++++-------------------- 7 files changed, 332 insertions(+), 156 deletions(-) create mode 100644 peer_test.go diff --git a/config.go b/config.go index 60b69e367..a8b7e343b 100644 --- a/config.go +++ b/config.go @@ -17,7 +17,6 @@ const ( // Fuzz params configFuzzEnable = "fuzz_enable" // use the fuzz wrapped conn - configFuzzActive = "fuzz_active" // toggle fuzzing configFuzzMode = "fuzz_mode" // eg. drop, delay configFuzzMaxDelayMilliseconds = "fuzz_max_delay_milliseconds" configFuzzProbDropRW = "fuzz_prob_drop_rw" @@ -38,7 +37,6 @@ func setConfigDefaults(config cfg.Config) { // Fuzz defaults config.SetDefault(configFuzzEnable, false) - config.SetDefault(configFuzzActive, false) config.SetDefault(configFuzzMode, FuzzModeDrop) config.SetDefault(configFuzzMaxDelayMilliseconds, 3000) config.SetDefault(configFuzzProbDropRW, 0.2) diff --git a/connection.go b/connection.go index e61608896..3448ae085 100644 --- a/connection.go +++ b/connection.go @@ -74,7 +74,7 @@ type MConnection struct { onReceive receiveCbFunc onError errorCbFunc errored uint32 - config *MConnectionConfig + config *MConnConfig quit chan struct{} flushTimer *cmn.ThrottleTimer // flush writes as necessary but throttled. @@ -85,12 +85,19 @@ type MConnection struct { RemoteAddress *NetAddress } -// MConnectionConfig is a MConnection configuration -type MConnectionConfig struct { +// MConnConfig is a MConnection configuration +type MConnConfig struct { SendRate int64 RecvRate int64 } +func defaultMConnectionConfig() *MConnConfig { + return &MConnConfig{ + SendRate: defaultSendRate, + RecvRate: defaultRecvRate, + } +} + // NewMConnection wraps net.Conn and creates multiplex connection func NewMConnection(conn net.Conn, chDescs []*ChannelDescriptor, onReceive receiveCbFunc, onError errorCbFunc) *MConnection { return NewMConnectionWithConfig( @@ -98,14 +105,11 @@ func NewMConnection(conn net.Conn, chDescs []*ChannelDescriptor, onReceive recei chDescs, onReceive, onError, - &MConnectionConfig{ - SendRate: defaultSendRate, - RecvRate: defaultRecvRate, - }) + defaultMConnectionConfig()) } // NewMConnectionWithConfig wraps net.Conn and creates multiplex connection with a config -func NewMConnectionWithConfig(conn net.Conn, chDescs []*ChannelDescriptor, onReceive receiveCbFunc, onError errorCbFunc, config *MConnectionConfig) *MConnection { +func NewMConnectionWithConfig(conn net.Conn, chDescs []*ChannelDescriptor, onReceive receiveCbFunc, onError errorCbFunc, config *MConnConfig) *MConnection { mconn := &MConnection{ conn: conn, bufReader: bufio.NewReaderSize(conn, minReadBufferSize), diff --git a/fuzz.go b/fuzz.go index ee8f43ccf..822002b93 100644 --- a/fuzz.go +++ b/fuzz.go @@ -1,90 +1,139 @@ package p2p import ( + "fmt" "math/rand" "net" "sync" "time" - - cfg "github.com/tendermint/go-config" ) -//-------------------------------------------------------- -// delay reads/writes -// randomly drop reads/writes -// randomly drop connections - const ( - FuzzModeDrop = "drop" - FuzzModeDelay = "delay" + // FuzzModeDrop is a mode in which we randomly drop reads/writes, connections or sleep + FuzzModeDrop = iota + // FuzzModeDelay is a mode in which we randomly sleep + FuzzModeDelay ) -func FuzzConn(config cfg.Config, conn net.Conn) net.Conn { - return &FuzzedConnection{ - conn: conn, - start: time.After(time.Second * 10), // so we have time to do peer handshakes and get set up - params: config, +type FuzzConnConfig struct { + Mode int + MaxDelay time.Duration + ProbDropRW float64 + ProbDropConn float64 + ProbSleep float64 +} + +func defaultFuzzConnConfig() *FuzzConnConfig { + return &FuzzConnConfig{ + Mode: FuzzModeDrop, + MaxDelay: 3 * time.Second, + ProbDropRW: 0.2, + ProbDropConn: 0.00, + ProbSleep: 0.00, } } +func FuzzConn(conn net.Conn) net.Conn { + return FuzzConnFromConfig(conn, defaultFuzzConnConfig()) +} + +func FuzzConnFromConfig(conn net.Conn, config *FuzzConnConfig) net.Conn { + return &FuzzedConnection{ + conn: conn, + start: make(<-chan time.Time), + active: true, + mode: config.Mode, + maxDelay: config.MaxDelay, + probDropRW: config.ProbDropRW, + probDropConn: config.ProbDropConn, + probSleep: config.ProbSleep, + } +} + +func FuzzConnAfter(conn net.Conn, d time.Duration) net.Conn { + return FuzzConnAfterFromConfig(conn, d, defaultFuzzConnConfig()) +} + +func FuzzConnAfterFromConfig(conn net.Conn, d time.Duration, config *FuzzConnConfig) net.Conn { + return &FuzzedConnection{ + conn: conn, + start: time.After(d), + active: false, + mode: config.Mode, + maxDelay: config.MaxDelay, + probDropRW: config.ProbDropRW, + probDropConn: config.ProbDropConn, + probSleep: config.ProbSleep, + } +} + +// FuzzedConnection wraps any net.Conn and depending on the mode either delays +// reads/writes or randomly drops reads/writes/connections. type FuzzedConnection struct { conn net.Conn - mtx sync.Mutex - fuzz bool // we don't start fuzzing right away - start <-chan time.Time + mtx sync.Mutex + start <-chan time.Time + active bool - // fuzz params - params cfg.Config + mode int + maxDelay time.Duration + probDropRW float64 + probDropConn float64 + probSleep float64 } func (fc *FuzzedConnection) randomDuration() time.Duration { - return time.Millisecond * time.Duration(rand.Int()%fc.MaxDelayMilliseconds()) + maxDelayMillis := int(fc.maxDelay.Nanoseconds() / 1000) + return time.Millisecond * time.Duration(rand.Int()%maxDelayMillis) } -func (fc *FuzzedConnection) Active() bool { - return fc.params.GetBool(configFuzzActive) +func (fc *FuzzedConnection) SetMode(mode int) { + switch mode { + case FuzzModeDrop: + fc.mode = FuzzModeDrop + case FuzzModeDelay: + fc.mode = FuzzModeDelay + default: + panic(fmt.Sprintf("Unknown mode %d", mode)) + } } -func (fc *FuzzedConnection) Mode() string { - return fc.params.GetString(configFuzzMode) +func (fc *FuzzedConnection) SetProbDropRW(prob float64) { + fc.probDropRW = prob } -func (fc *FuzzedConnection) ProbDropRW() float64 { - return fc.params.GetFloat64(configFuzzProbDropRW) +func (fc *FuzzedConnection) SetProbDropConn(prob float64) { + fc.probDropConn = prob } -func (fc *FuzzedConnection) ProbDropConn() float64 { - return fc.params.GetFloat64(configFuzzProbDropConn) +func (fc *FuzzedConnection) SetProbSleep(prob float64) { + fc.probSleep = prob } -func (fc *FuzzedConnection) ProbSleep() float64 { - return fc.params.GetFloat64(configFuzzProbSleep) -} - -func (fc *FuzzedConnection) MaxDelayMilliseconds() int { - return fc.params.GetInt(configFuzzMaxDelayMilliseconds) +func (fc *FuzzedConnection) SetMaxDelay(d time.Duration) { + fc.maxDelay = d } // implements the fuzz (delay, kill conn) // and returns whether or not the read/write should be ignored -func (fc *FuzzedConnection) Fuzz() bool { +func (fc *FuzzedConnection) fuzz() bool { if !fc.shouldFuzz() { return false } - switch fc.Mode() { + switch fc.mode { case FuzzModeDrop: // randomly drop the r/w, drop the conn, or sleep r := rand.Float64() - if r <= fc.ProbDropRW() { + if r <= fc.probDropRW { return true - } else if r < fc.ProbDropRW()+fc.ProbDropConn() { + } else if r < fc.probDropRW+fc.probDropConn { // XXX: can't this fail because machine precision? // XXX: do we need an error? fc.Close() return true - } else if r < fc.ProbDropRW()+fc.ProbDropConn()+fc.ProbSleep() { + } else if r < fc.probDropRW+fc.probDropConn+fc.probSleep { time.Sleep(fc.randomDuration()) } case FuzzModeDelay: @@ -96,33 +145,33 @@ func (fc *FuzzedConnection) Fuzz() bool { // we don't fuzz until start chan fires func (fc *FuzzedConnection) shouldFuzz() bool { - if !fc.Active() { - return false + if fc.active { + return true } fc.mtx.Lock() defer fc.mtx.Unlock() - if fc.fuzz { - return true - } select { case <-fc.start: - fc.fuzz = true + fc.active = true + return true default: + return false } - return false } +// Read implements net.Conn func (fc *FuzzedConnection) Read(data []byte) (n int, err error) { - if fc.Fuzz() { + if fc.fuzz() { return 0, nil } return fc.conn.Read(data) } +// Write implements net.Conn func (fc *FuzzedConnection) Write(data []byte) (n int, err error) { - if fc.Fuzz() { + if fc.fuzz() { return 0, nil } return fc.conn.Write(data) diff --git a/peer.go b/peer.go index 1be50aff1..6ef317378 100644 --- a/peer.go +++ b/peer.go @@ -7,7 +7,6 @@ import ( "time" cmn "github.com/tendermint/go-common" - cfg "github.com/tendermint/go-config" crypto "github.com/tendermint/go-crypto" wire "github.com/tendermint/go-wire" ) @@ -25,23 +24,50 @@ type Peer struct { conn net.Conn // source connection mconn *MConnection // multiplex connection - authEnc bool // authenticated encryption persistent bool - config cfg.Config + config *PeerConfig *NodeInfo Key string Data *cmn.CMap // User data. } -func newPeer(addr *NetAddress, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), config cfg.Config, privKey crypto.PrivKeyEd25519) (*Peer, error) { +// PeerConfig is a Peer configuration +type PeerConfig struct { + AuthEnc bool // authenticated encryption + + HandshakeTimeout time.Duration + DialTimeout time.Duration + + MConfig *MConnConfig + + Fuzz bool // fuzz connection (for testing) + FuzzConfig *FuzzConnConfig +} + +func defaultPeerConfig() *PeerConfig { + return &PeerConfig{ + AuthEnc: true, + Fuzz: false, + HandshakeTimeout: 20 * time.Second, + DialTimeout: 3 * time.Second, + MConfig: defaultMConnectionConfig(), + FuzzConfig: defaultFuzzConnConfig(), + } +} + +func newPeer(addr *NetAddress, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), ourNodePrivKey crypto.PrivKeyEd25519) (*Peer, error) { + return newPeerWithConfig(addr, reactorsByCh, chDescs, onPeerError, ourNodePrivKey, defaultPeerConfig()) +} + +func newPeerWithConfig(addr *NetAddress, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), ourNodePrivKey crypto.PrivKeyEd25519, config *PeerConfig) (*Peer, error) { conn, err := dial(addr, config) if err != nil { return nil, err } // outbound = true - peer, err := newPeerFromExistingConn(conn, true, reactorsByCh, chDescs, onPeerError, config, privKey) + peer, err := newPeerFromExistingConnAndConfig(conn, true, reactorsByCh, chDescs, onPeerError, ourNodePrivKey, config) if err != nil { conn.Close() return nil, err @@ -49,31 +75,39 @@ func newPeer(addr *NetAddress, reactorsByCh map[byte]Reactor, chDescs []*Channel return peer, nil } -func newPeerFromExistingConn(conn net.Conn, outbound bool, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), config cfg.Config, privKey crypto.PrivKeyEd25519) (*Peer, error) { +func newPeerFromExistingConn(rawConn net.Conn, outbound bool, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), ourNodePrivKey crypto.PrivKeyEd25519) (*Peer, error) { + return newPeerFromExistingConnAndConfig(rawConn, outbound, reactorsByCh, chDescs, onPeerError, ourNodePrivKey, defaultPeerConfig()) +} + +func newPeerFromExistingConnAndConfig(rawConn net.Conn, outbound bool, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), ourNodePrivKey crypto.PrivKeyEd25519, config *PeerConfig) (*Peer, error) { + conn := rawConn + + // Fuzz connection + if config.Fuzz { + // so we have time to do peer handshakes and get set up + conn = FuzzConnAfterFromConfig(conn, 10*time.Second, config.FuzzConfig) + } + // Encrypt connection - if config.GetBool(configKeyAuthEnc) { + if config.AuthEnc { + conn.SetDeadline(time.Now().Add(config.HandshakeTimeout)) + var err error - // Set deadline for handshake so we don't block forever on conn.ReadFull - timeout := time.Duration(config.GetInt(configKeyHandshakeTimeoutSeconds)) * time.Second - conn.SetDeadline(time.Now().Add(timeout)) - conn, err = MakeSecretConnection(conn, privKey) + conn, err = MakeSecretConnection(conn, ourNodePrivKey) if err != nil { return nil, err } - // remove deadline - conn.SetDeadline(time.Time{}) } // Key and NodeInfo are set after Handshake p := &Peer{ outbound: outbound, - authEnc: config.GetBool(configKeyAuthEnc), conn: conn, config: config, Data: cmn.NewCMap(), } - p.mconn = createMConnection(conn, p, reactorsByCh, chDescs, onPeerError, config) + p.mconn = createMConnection(conn, p, reactorsByCh, chDescs, onPeerError, config.MConfig) p.BaseService = *cmn.NewBaseService(log, "Peer", p) @@ -125,7 +159,7 @@ func (p *Peer) HandshakeTimeout(ourNodeInfo *NodeInfo, timeout time.Duration) er return err2 } - if p.authEnc { + if p.config.AuthEnc { // Check that the professed PubKey matches the sconn's. if !peerNodeInfo.PubKey.Equals(p.PubKey()) { return fmt.Errorf("Ignoring connection with unmatching pubkey: %v vs %v", @@ -151,7 +185,7 @@ func (p *Peer) RemoteAddr() net.Addr { // PubKey returns the remote public key. func (p *Peer) PubKey() crypto.PubKeyEd25519 { - if p.authEnc { + if p.config.AuthEnc { return p.conn.(*SecretConnection).RemotePubKey() } if p.NodeInfo == nil { @@ -238,21 +272,17 @@ func (p *Peer) Get(key string) interface{} { return p.Data.Get(key) } -func dial(addr *NetAddress, config cfg.Config) (net.Conn, error) { +func dial(addr *NetAddress, config *PeerConfig) (net.Conn, error) { log.Info("Dialing address", "address", addr) - conn, err := addr.DialTimeout(time.Duration( - config.GetInt(configKeyDialTimeoutSeconds)) * time.Second) + conn, err := addr.DialTimeout(config.DialTimeout) if err != nil { log.Info("Failed dialing address", "address", addr, "error", err) return nil, err } - if config.GetBool(configFuzzEnable) { - conn = FuzzConn(config, conn) - } return conn, nil } -func createMConnection(conn net.Conn, p *Peer, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), config cfg.Config) *MConnection { +func createMConnection(conn net.Conn, p *Peer, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), config *MConnConfig) *MConnection { onReceive := func(chID byte, msgBytes []byte) { reactor := reactorsByCh[chID] if reactor == nil { @@ -265,10 +295,5 @@ func createMConnection(conn net.Conn, p *Peer, reactorsByCh map[byte]Reactor, ch onPeerError(p, r) } - mconnConfig := &MConnectionConfig{ - SendRate: int64(config.GetInt(configKeySendRate)), - RecvRate: int64(config.GetInt(configKeyRecvRate)), - } - - return NewMConnectionWithConfig(conn, chDescs, onReceive, onError, mconnConfig) + return NewMConnectionWithConfig(conn, chDescs, onReceive, onError, config) } diff --git a/peer_test.go b/peer_test.go new file mode 100644 index 000000000..56d4c1da5 --- /dev/null +++ b/peer_test.go @@ -0,0 +1,120 @@ +package p2p + +import ( + golog "log" + "net" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + cmn "github.com/tendermint/go-common" + crypto "github.com/tendermint/go-crypto" + wire "github.com/tendermint/go-wire" +) + +func TestPeerStartStop(t *testing.T) { + assert, require := assert.New(t), require.New(t) + + // simulate remote peer + rp := &remotePeer{PrivKey: crypto.GenPrivKeyEd25519()} + rp.Start() + defer rp.Stop() + + p, err := createPeerAndPerformHandshake(rp.RemoteAddr()) + require.Nil(err) + + p.Start() + defer p.Stop() + + assert.True(p.IsRunning()) +} + +func createPeerAndPerformHandshake(addr *NetAddress) (*Peer, error) { + chDescs := []*ChannelDescriptor{ + &ChannelDescriptor{ID: 0x01, Priority: 1}, + } + reactorsByCh := map[byte]Reactor{0x01: NewTestReactor(chDescs, true)} + pk := crypto.GenPrivKeyEd25519() + p, err := newPeer(addr, reactorsByCh, chDescs, func(p *Peer, r interface{}) {}, pk) + if err != nil { + return nil, err + } + err = p.HandshakeTimeout(&NodeInfo{ + PubKey: pk.PubKey().(crypto.PubKeyEd25519), + Moniker: "remote_peer", + Network: "testing", + Version: "123.123.123", + }, 1*time.Second) + if err != nil { + return nil, err + } + return p, nil +} + +type remotePeer struct { + PrivKey crypto.PrivKeyEd25519 + addr *NetAddress + quit chan struct{} +} + +func (p *remotePeer) RemoteAddr() *NetAddress { + return p.addr +} + +func (p *remotePeer) Start() { + l, e := net.Listen("tcp", "127.0.0.1:0") // any available address + if e != nil { + golog.Fatalf("net.Listen tcp :0: %+v", e) + } + p.addr = NewNetAddress(l.Addr()) + p.quit = make(chan struct{}) + go p.accept(l) +} + +func (p *remotePeer) Stop() { + close(p.quit) +} + +func (p *remotePeer) accept(l net.Listener) { + for { + conn, err := l.Accept() + if err != nil { + golog.Fatalf("Failed to accept conn: %+v", err) + } + conn, err = MakeSecretConnection(conn, p.PrivKey) + if err != nil { + golog.Fatalf("Failed to make secret conn: %+v", err) + } + var err1, err2 error + nodeInfo := new(NodeInfo) + cmn.Parallel( + func() { + var n int + ourNodeInfo := &NodeInfo{ + PubKey: p.PrivKey.PubKey().(crypto.PubKeyEd25519), + Moniker: "remote_peer", + Network: "testing", + Version: "123.123.123", + } + wire.WriteBinary(ourNodeInfo, conn, &n, &err1) + }, + func() { + var n int + wire.ReadBinary(nodeInfo, conn, maxNodeInfoSize, &n, &err2) + }) + if err1 != nil { + golog.Fatalf("Failed to do handshake: %+v", err1) + } + if err2 != nil { + golog.Fatalf("Failed to do handshake: %+v", err2) + } + select { + case <-p.quit: + conn.Close() + return + default: + } + } +} diff --git a/switch.go b/switch.go index f38d4feb1..b25384618 100644 --- a/switch.go +++ b/switch.go @@ -317,7 +317,7 @@ func (sw *Switch) DialPeerWithAddress(addr *NetAddress, persistent bool) (*Peer, sw.dialing.Set(addr.IP.String(), addr) defer sw.dialing.Delete(addr.IP.String()) - peer, err := newPeer(addr, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.config, sw.nodePrivKey) + peer, err := newPeerWithConfig(addr, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey, peerConfigFromGoConfig(sw.config)) if err != nil { log.Info("Failed dialing peer", "address", addr, "error", err) return nil, err @@ -435,12 +435,8 @@ func (sw *Switch) listenerRoutine(l Listener) { continue } - if sw.config.GetBool(configFuzzEnable) { - inConn = FuzzConn(sw.config, inConn) - } - // New inbound connection! - err := sw.AddPeerWithConnection(inConn, false) + err := sw.AddPeerWithConnectionAndConfig(inConn, false, peerConfigFromGoConfig(sw.config)) if err != nil { log.Notice("Ignoring inbound connection: error while adding peer", "address", inConn.RemoteAddr().String(), "error", err) continue @@ -546,7 +542,7 @@ func makeSwitch(i int, network, version string, initSwitch func(int, *Switch) *S // AddPeerWithConnection creates a newPeer from the connection, performs the handshake, and adds it to the switch. func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool) error { - peer, err := newPeerFromExistingConn(conn, outbound, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.config, sw.nodePrivKey) + peer, err := newPeerFromExistingConn(conn, outbound, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey) if err != nil { conn.Close() return err @@ -559,3 +555,38 @@ func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool) error { return nil } + +func (sw *Switch) AddPeerWithConnectionAndConfig(conn net.Conn, outbound bool, config *PeerConfig) error { + peer, err := newPeerFromExistingConnAndConfig(conn, outbound, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey, config) + if err != nil { + peer.CloseConn() + return err + } + + if err = sw.AddPeer(peer); err != nil { + peer.CloseConn() + return err + } + + return nil +} + +func peerConfigFromGoConfig(config cfg.Config) *PeerConfig { + return &PeerConfig{ + AuthEnc: config.GetBool(configKeyAuthEnc), + Fuzz: config.GetBool(configFuzzEnable), + HandshakeTimeout: time.Duration(config.GetInt(configKeyHandshakeTimeoutSeconds)) * time.Second, + DialTimeout: time.Duration(config.GetInt(configKeyDialTimeoutSeconds)) * time.Second, + MConfig: &MConnConfig{ + SendRate: int64(config.GetInt(configKeySendRate)), + RecvRate: int64(config.GetInt(configKeyRecvRate)), + }, + FuzzConfig: &FuzzConnConfig{ + Mode: config.GetInt(configFuzzMode), + MaxDelay: time.Duration(config.GetInt(configFuzzMaxDelayMilliseconds)) * time.Millisecond, + ProbDropRW: config.GetFloat64(configFuzzProbDropRW), + ProbDropConn: config.GetFloat64(configFuzzProbDropConn), + ProbSleep: config.GetFloat64(configFuzzProbSleep), + }, + } +} diff --git a/switch_test.go b/switch_test.go index a9abfa0a5..530a12b17 100644 --- a/switch_test.go +++ b/switch_test.go @@ -3,7 +3,6 @@ package p2p import ( "bytes" "fmt" - golog "log" "net" "sync" "testing" @@ -12,7 +11,6 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" . "github.com/tendermint/go-common" - cmn "github.com/tendermint/go-common" cfg "github.com/tendermint/go-config" crypto "github.com/tendermint/go-crypto" wire "github.com/tendermint/go-wire" @@ -239,14 +237,12 @@ func TestSwitchStopsNonPersistentPeerOnError(t *testing.T) { sw.Start() defer sw.Stop() - sw2 := makeSwitch(2, "testing", "123.123.123", initSwitchFunc) - defer sw2.Stop() - l, serverAddr := listenTCP() - done := make(chan struct{}) - go accept(l, done, sw2) - defer close(done) + // simulate remote peer + rp := &remotePeer{PrivKey: crypto.GenPrivKeyEd25519()} + rp.Start() + defer rp.Stop() - peer, err := newPeer(NewNetAddress(serverAddr), sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.config, sw.nodePrivKey) + peer, err := newPeer(rp.RemoteAddr(), sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey) require.Nil(err) err = sw.AddPeer(peer) require.Nil(err) @@ -267,14 +263,12 @@ func TestSwitchReconnectsToPersistentPeer(t *testing.T) { sw.Start() defer sw.Stop() - sw2 := makeSwitch(2, "testing", "123.123.123", initSwitchFunc) - defer sw2.Stop() - l, serverAddr := listenTCP() - done := make(chan struct{}) - go accept(l, done, sw2) - defer close(done) + // simulate remote peer + rp := &remotePeer{PrivKey: crypto.GenPrivKeyEd25519()} + rp.Start() + defer rp.Stop() - peer, err := newPeer(NewNetAddress(serverAddr), sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.config, sw.nodePrivKey) + peer, err := newPeer(rp.RemoteAddr(), sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey) peer.makePersistent() require.Nil(err) err = sw.AddPeer(peer) @@ -334,48 +328,3 @@ func BenchmarkSwitches(b *testing.B) { time.Sleep(1000 * time.Millisecond) } - -func listenTCP() (net.Listener, net.Addr) { - l, e := net.Listen("tcp", "127.0.0.1:0") // any available address - if e != nil { - golog.Fatalf("net.Listen tcp :0: %+v", e) - } - return l, l.Addr() -} - -// simulate remote peer -func accept(l net.Listener, done <-chan struct{}, sw *Switch) { - for { - conn, err := l.Accept() - if err != nil { - golog.Fatalf("Failed to accept conn: %+v", err) - } - conn, err = MakeSecretConnection(conn, sw.nodePrivKey) - if err != nil { - golog.Fatalf("Failed to make secret conn: %+v", err) - } - var err1, err2 error - nodeInfo := new(NodeInfo) - cmn.Parallel( - func() { - var n int - wire.WriteBinary(sw.nodeInfo, conn, &n, &err1) - }, - func() { - var n int - wire.ReadBinary(nodeInfo, conn, maxNodeInfoSize, &n, &err2) - }) - if err1 != nil { - golog.Fatalf("Failed to do handshake: %+v", err1) - } - if err2 != nil { - golog.Fatalf("Failed to do handshake: %+v", err2) - } - select { - case <-done: - conn.Close() - return - default: - } - } -} From c3295f4878019ff3fdfcac37a4c0e4bcf4bb02a7 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Wed, 12 Apr 2017 13:42:19 -0400 Subject: [PATCH 130/309] RPCRequest.Params can be map[string]interface{} or []interface{} --- server/handlers.go | 44 ++++++++++++++++++++++++++++++++------------ types/types.go | 8 ++++---- 2 files changed, 36 insertions(+), 16 deletions(-) diff --git a/server/handlers.go b/server/handlers.go index 573696fb6..051d67d00 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -140,36 +140,56 @@ func makeJSONRPCHandler(funcMap map[string]*RPCFunc) http.HandlerFunc { } } -// Convert a list of interfaces to properly typed values +// Convert a []interface{} OR a map[string]interface{} to properly typed values // // argsOffset is used in jsonParamsToArgsWS, where len(rpcFunc.args) != len(rpcFunc.argNames). // Example: // rpcFunc.args = [rpctypes.WSRPCContext string] // rpcFunc.argNames = ["arg"] -func jsonParamsToArgs(rpcFunc *RPCFunc, params map[string]interface{}, argsOffset int) ([]reflect.Value, error) { +func jsonParamsToArgs(rpcFunc *RPCFunc, paramsI interface{}, argsOffset int) ([]reflect.Value, error) { values := make([]reflect.Value, len(rpcFunc.argNames)) - for i, argName := range rpcFunc.argNames { - argType := rpcFunc.args[i+argsOffset] + switch params := paramsI.(type) { - // decode param if provided - if param, ok := params[argName]; ok && "" != param { - v, err := _jsonObjectToArg(argType, param) + case map[string]interface{}: + for i, argName := range rpcFunc.argNames { + argType := rpcFunc.args[i+argsOffset] + + // decode param if provided + if param, ok := params[argName]; ok && "" != param { + v, err := _jsonObjectToArg(argType, param) + if err != nil { + return nil, err + } + values[i] = v + } else { // use default for that type + values[i] = reflect.Zero(argType) + } + } + case []interface{}: + if len(rpcFunc.argNames) != len(params) { + return nil, errors.New(fmt.Sprintf("Expected %v parameters (%v), got %v (%v)", + len(rpcFunc.argNames), rpcFunc.argNames, len(params), params)) + } + values := make([]reflect.Value, len(params)) + for i, p := range params { + ty := rpcFunc.args[i] + v, err := _jsonObjectToArg(ty, p) if err != nil { return nil, err } values[i] = v - } else { // use default for that type - values[i] = reflect.Zero(argType) } + return values, nil + default: + return nil, fmt.Errorf("Unknown type for JSON params %v. Expected map[string]interface{} or []interface{}", reflect.TypeOf(paramsI)) } - return values, nil } // Same as above, but with the first param the websocket connection -func jsonParamsToArgsWS(rpcFunc *RPCFunc, params map[string]interface{}, wsCtx types.WSRPCContext) ([]reflect.Value, error) { - values, err := jsonParamsToArgs(rpcFunc, params, 1) +func jsonParamsToArgsWS(rpcFunc *RPCFunc, paramsI interface{}, wsCtx types.WSRPCContext) ([]reflect.Value, error) { + values, err := jsonParamsToArgs(rpcFunc, paramsI, 1) if err != nil { return nil, err } diff --git a/types/types.go b/types/types.go index cebd7564a..38c7f09db 100644 --- a/types/types.go +++ b/types/types.go @@ -9,10 +9,10 @@ import ( ) type RPCRequest struct { - JSONRPC string `json:"jsonrpc"` - ID string `json:"id"` - Method string `json:"method"` - Params map[string]interface{} `json:"params"` + JSONRPC string `json:"jsonrpc"` + ID string `json:"id"` + Method string `json:"method"` + Params interface{} `json:"params"` // must be map[string]interface{} or []interface{} } func NewRPCRequest(id string, method string, params map[string]interface{}) RPCRequest { From 8c385433576988ab4b0269a8220d095d82b96e6e Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Wed, 12 Apr 2017 18:15:51 -0400 Subject: [PATCH 131/309] fix error msg --- server/handlers.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/server/handlers.go b/server/handlers.go index 051d67d00..de2b8094f 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -133,7 +133,7 @@ func makeJSONRPCHandler(funcMap map[string]*RPCFunc) http.HandlerFunc { log.Info("HTTPJSONRPC", "method", request.Method, "args", args, "returns", returns) result, err := unreflectResult(returns) if err != nil { - WriteRPCResponseHTTP(w, types.NewRPCResponse(request.ID, result, fmt.Sprintf("Error unreflecting result: %v", err.Error()))) + WriteRPCResponseHTTP(w, types.NewRPCResponse(request.ID, result, err.Error())) return } WriteRPCResponseHTTP(w, types.NewRPCResponse(request.ID, result, "")) @@ -231,7 +231,7 @@ func makeHTTPHandler(rpcFunc *RPCFunc) func(http.ResponseWriter, *http.Request) log.Info("HTTPRestRPC", "method", r.URL.Path, "args", args, "returns", returns) result, err := unreflectResult(returns) if err != nil { - WriteRPCResponseHTTP(w, types.NewRPCResponse("", nil, fmt.Sprintf("Error unreflecting result: %v", err.Error()))) + WriteRPCResponseHTTP(w, types.NewRPCResponse("", nil, err.Error())) return } WriteRPCResponseHTTP(w, types.NewRPCResponse("", result, "")) From 4b30cb3083f8275a8d9c94527c290996a42c3707 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Wed, 12 Apr 2017 19:30:05 -0400 Subject: [PATCH 132/309] test: check err on cmd.Wait --- rpc_test.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/rpc_test.go b/rpc_test.go index 8a05d7295..56b8ade32 100644 --- a/rpc_test.go +++ b/rpc_test.go @@ -71,7 +71,9 @@ func init() { if err != nil { panic(err) } - err = cmd.Wait() + if err = cmd.Wait(); err != nil { + panic(err) + } mux := http.NewServeMux() server.RegisterRPCFuncs(mux, Routes) From 5965578c56678f6ac413fe02849f3ebaa116be2b Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Thu, 13 Apr 2017 11:55:14 +0400 Subject: [PATCH 133/309] [fuzz] only one way to set config variables --- fuzz.go | 203 ++++++++++++++++++++++++++------------------------------ peer.go | 2 +- 2 files changed, 94 insertions(+), 111 deletions(-) diff --git a/fuzz.go b/fuzz.go index 822002b93..aefac986a 100644 --- a/fuzz.go +++ b/fuzz.go @@ -1,7 +1,6 @@ package p2p import ( - "fmt" "math/rand" "net" "sync" @@ -15,58 +14,6 @@ const ( FuzzModeDelay ) -type FuzzConnConfig struct { - Mode int - MaxDelay time.Duration - ProbDropRW float64 - ProbDropConn float64 - ProbSleep float64 -} - -func defaultFuzzConnConfig() *FuzzConnConfig { - return &FuzzConnConfig{ - Mode: FuzzModeDrop, - MaxDelay: 3 * time.Second, - ProbDropRW: 0.2, - ProbDropConn: 0.00, - ProbSleep: 0.00, - } -} - -func FuzzConn(conn net.Conn) net.Conn { - return FuzzConnFromConfig(conn, defaultFuzzConnConfig()) -} - -func FuzzConnFromConfig(conn net.Conn, config *FuzzConnConfig) net.Conn { - return &FuzzedConnection{ - conn: conn, - start: make(<-chan time.Time), - active: true, - mode: config.Mode, - maxDelay: config.MaxDelay, - probDropRW: config.ProbDropRW, - probDropConn: config.ProbDropConn, - probSleep: config.ProbSleep, - } -} - -func FuzzConnAfter(conn net.Conn, d time.Duration) net.Conn { - return FuzzConnAfterFromConfig(conn, d, defaultFuzzConnConfig()) -} - -func FuzzConnAfterFromConfig(conn net.Conn, d time.Duration, config *FuzzConnConfig) net.Conn { - return &FuzzedConnection{ - conn: conn, - start: time.After(d), - active: false, - mode: config.Mode, - maxDelay: config.MaxDelay, - probDropRW: config.ProbDropRW, - probDropConn: config.ProbDropConn, - probSleep: config.ProbSleep, - } -} - // FuzzedConnection wraps any net.Conn and depending on the mode either delays // reads/writes or randomly drops reads/writes/connections. type FuzzedConnection struct { @@ -76,43 +23,108 @@ type FuzzedConnection struct { start <-chan time.Time active bool - mode int - maxDelay time.Duration - probDropRW float64 - probDropConn float64 - probSleep float64 + config *FuzzConnConfig } -func (fc *FuzzedConnection) randomDuration() time.Duration { - maxDelayMillis := int(fc.maxDelay.Nanoseconds() / 1000) - return time.Millisecond * time.Duration(rand.Int()%maxDelayMillis) +// FuzzConnConfig is a FuzzedConnection configuration. +type FuzzConnConfig struct { + Mode int + MaxDelay time.Duration + ProbDropRW float64 + ProbDropConn float64 + ProbSleep float64 } -func (fc *FuzzedConnection) SetMode(mode int) { - switch mode { - case FuzzModeDrop: - fc.mode = FuzzModeDrop - case FuzzModeDelay: - fc.mode = FuzzModeDelay - default: - panic(fmt.Sprintf("Unknown mode %d", mode)) +// DefaultFuzzConnConfig returns the default config. +func DefaultFuzzConnConfig() *FuzzConnConfig { + return &FuzzConnConfig{ + Mode: FuzzModeDrop, + MaxDelay: 3 * time.Second, + ProbDropRW: 0.2, + ProbDropConn: 0.00, + ProbSleep: 0.00, } } -func (fc *FuzzedConnection) SetProbDropRW(prob float64) { - fc.probDropRW = prob +// FuzzConn creates a new FuzzedConnection. Fuzzing starts immediately. +func FuzzConn(conn net.Conn) net.Conn { + return FuzzConnFromConfig(conn, DefaultFuzzConnConfig()) } -func (fc *FuzzedConnection) SetProbDropConn(prob float64) { - fc.probDropConn = prob +// FuzzConnFromConfig creates a new FuzzedConnection from a config. Fuzzing +// starts immediately. +func FuzzConnFromConfig(conn net.Conn, config *FuzzConnConfig) net.Conn { + return &FuzzedConnection{ + conn: conn, + start: make(<-chan time.Time), + active: true, + config: config, + } } -func (fc *FuzzedConnection) SetProbSleep(prob float64) { - fc.probSleep = prob +// FuzzConnAfter creates a new FuzzedConnection. Fuzzing starts when the +// duration elapses. +func FuzzConnAfter(conn net.Conn, d time.Duration) net.Conn { + return FuzzConnAfterFromConfig(conn, d, DefaultFuzzConnConfig()) } -func (fc *FuzzedConnection) SetMaxDelay(d time.Duration) { - fc.maxDelay = d +// FuzzConnAfterFromConfig creates a new FuzzedConnection from a config. +// Fuzzing starts when the duration elapses. +func FuzzConnAfterFromConfig(conn net.Conn, d time.Duration, config *FuzzConnConfig) net.Conn { + return &FuzzedConnection{ + conn: conn, + start: time.After(d), + active: false, + config: config, + } +} + +// Config returns the connection's config. +func (fc *FuzzedConnection) Config() *FuzzConnConfig { + return fc.config +} + +// Read implements net.Conn. +func (fc *FuzzedConnection) Read(data []byte) (n int, err error) { + if fc.fuzz() { + return 0, nil + } + return fc.conn.Read(data) +} + +// Write implements net.Conn. +func (fc *FuzzedConnection) Write(data []byte) (n int, err error) { + if fc.fuzz() { + return 0, nil + } + return fc.conn.Write(data) +} + +// Close implements net.Conn. +func (fc *FuzzedConnection) Close() error { return fc.conn.Close() } + +// LocalAddr implements net.Conn. +func (fc *FuzzedConnection) LocalAddr() net.Addr { return fc.conn.LocalAddr() } + +// RemoteAddr implements net.Conn. +func (fc *FuzzedConnection) RemoteAddr() net.Addr { return fc.conn.RemoteAddr() } + +// SetDeadline implements net.Conn. +func (fc *FuzzedConnection) SetDeadline(t time.Time) error { return fc.conn.SetDeadline(t) } + +// SetReadDeadline implements net.Conn. +func (fc *FuzzedConnection) SetReadDeadline(t time.Time) error { + return fc.conn.SetReadDeadline(t) +} + +// SetWriteDeadline implements net.Conn. +func (fc *FuzzedConnection) SetWriteDeadline(t time.Time) error { + return fc.conn.SetWriteDeadline(t) +} + +func (fc *FuzzedConnection) randomDuration() time.Duration { + maxDelayMillis := int(fc.config.MaxDelay.Nanoseconds() / 1000) + return time.Millisecond * time.Duration(rand.Int()%maxDelayMillis) } // implements the fuzz (delay, kill conn) @@ -122,18 +134,18 @@ func (fc *FuzzedConnection) fuzz() bool { return false } - switch fc.mode { + switch fc.config.Mode { case FuzzModeDrop: // randomly drop the r/w, drop the conn, or sleep r := rand.Float64() - if r <= fc.probDropRW { + if r <= fc.config.ProbDropRW { return true - } else if r < fc.probDropRW+fc.probDropConn { + } else if r < fc.config.ProbDropRW+fc.config.ProbDropConn { // XXX: can't this fail because machine precision? // XXX: do we need an error? fc.Close() return true - } else if r < fc.probDropRW+fc.probDropConn+fc.probSleep { + } else if r < fc.config.ProbDropRW+fc.config.ProbDropConn+fc.config.ProbSleep { time.Sleep(fc.randomDuration()) } case FuzzModeDelay: @@ -143,7 +155,6 @@ func (fc *FuzzedConnection) fuzz() bool { return false } -// we don't fuzz until start chan fires func (fc *FuzzedConnection) shouldFuzz() bool { if fc.active { return true @@ -160,31 +171,3 @@ func (fc *FuzzedConnection) shouldFuzz() bool { return false } } - -// Read implements net.Conn -func (fc *FuzzedConnection) Read(data []byte) (n int, err error) { - if fc.fuzz() { - return 0, nil - } - return fc.conn.Read(data) -} - -// Write implements net.Conn -func (fc *FuzzedConnection) Write(data []byte) (n int, err error) { - if fc.fuzz() { - return 0, nil - } - return fc.conn.Write(data) -} - -// Implements net.Conn -func (fc *FuzzedConnection) Close() error { return fc.conn.Close() } -func (fc *FuzzedConnection) LocalAddr() net.Addr { return fc.conn.LocalAddr() } -func (fc *FuzzedConnection) RemoteAddr() net.Addr { return fc.conn.RemoteAddr() } -func (fc *FuzzedConnection) SetDeadline(t time.Time) error { return fc.conn.SetDeadline(t) } -func (fc *FuzzedConnection) SetReadDeadline(t time.Time) error { - return fc.conn.SetReadDeadline(t) -} -func (fc *FuzzedConnection) SetWriteDeadline(t time.Time) error { - return fc.conn.SetWriteDeadline(t) -} diff --git a/peer.go b/peer.go index 6ef317378..3d2b4720d 100644 --- a/peer.go +++ b/peer.go @@ -52,7 +52,7 @@ func defaultPeerConfig() *PeerConfig { HandshakeTimeout: 20 * time.Second, DialTimeout: 3 * time.Second, MConfig: defaultMConnectionConfig(), - FuzzConfig: defaultFuzzConnConfig(), + FuzzConfig: DefaultFuzzConnConfig(), } } From a63e1bb2dc68735eab5bfe57b9a581e1959aabfe Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Thu, 13 Apr 2017 12:08:57 +0400 Subject: [PATCH 134/309] fix possible panic --- switch.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/switch.go b/switch.go index b25384618..f4889a5f5 100644 --- a/switch.go +++ b/switch.go @@ -549,7 +549,7 @@ func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool) error { } if err = sw.AddPeer(peer); err != nil { - peer.CloseConn() + conn.Close() return err } @@ -559,12 +559,12 @@ func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool) error { func (sw *Switch) AddPeerWithConnectionAndConfig(conn net.Conn, outbound bool, config *PeerConfig) error { peer, err := newPeerFromExistingConnAndConfig(conn, outbound, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey, config) if err != nil { - peer.CloseConn() + conn.Close() return err } if err = sw.AddPeer(peer); err != nil { - peer.CloseConn() + conn.Close() return err } From 715b8c629fb15fb741b86e7b3362acd6448c0ce9 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Thu, 13 Apr 2017 12:09:43 +0400 Subject: [PATCH 135/309] use the peer struct to simulate remote peer --- peer_test.go | 38 +++++++++++--------------------------- 1 file changed, 11 insertions(+), 27 deletions(-) diff --git a/peer_test.go b/peer_test.go index 56d4c1da5..d564022ad 100644 --- a/peer_test.go +++ b/peer_test.go @@ -9,9 +9,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - cmn "github.com/tendermint/go-common" crypto "github.com/tendermint/go-crypto" - wire "github.com/tendermint/go-wire" ) func TestPeerStartStop(t *testing.T) { @@ -43,7 +41,7 @@ func createPeerAndPerformHandshake(addr *NetAddress) (*Peer, error) { } err = p.HandshakeTimeout(&NodeInfo{ PubKey: pk.PubKey().(crypto.PubKeyEd25519), - Moniker: "remote_peer", + Moniker: "host_peer", Network: "testing", Version: "123.123.123", }, 1*time.Second) @@ -83,32 +81,18 @@ func (p *remotePeer) accept(l net.Listener) { if err != nil { golog.Fatalf("Failed to accept conn: %+v", err) } - conn, err = MakeSecretConnection(conn, p.PrivKey) + peer, err := newPeerFromExistingConn(conn, false, make(map[byte]Reactor), make([]*ChannelDescriptor, 0), func(p *Peer, r interface{}) {}, p.PrivKey) if err != nil { - golog.Fatalf("Failed to make secret conn: %+v", err) + golog.Fatalf("Failed to create a peer: %+v", err) } - var err1, err2 error - nodeInfo := new(NodeInfo) - cmn.Parallel( - func() { - var n int - ourNodeInfo := &NodeInfo{ - PubKey: p.PrivKey.PubKey().(crypto.PubKeyEd25519), - Moniker: "remote_peer", - Network: "testing", - Version: "123.123.123", - } - wire.WriteBinary(ourNodeInfo, conn, &n, &err1) - }, - func() { - var n int - wire.ReadBinary(nodeInfo, conn, maxNodeInfoSize, &n, &err2) - }) - if err1 != nil { - golog.Fatalf("Failed to do handshake: %+v", err1) - } - if err2 != nil { - golog.Fatalf("Failed to do handshake: %+v", err2) + err = peer.HandshakeTimeout(&NodeInfo{ + PubKey: p.PrivKey.PubKey().(crypto.PubKeyEd25519), + Moniker: "remote_peer", + Network: "testing", + Version: "123.123.123", + }, 1*time.Second) + if err != nil { + golog.Fatalf("Failed to perform handshake: %+v", err) } select { case <-p.quit: From 1d01f6af9873b706cefdb1acd949bc40a8275a0b Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Thu, 13 Apr 2017 12:36:16 +0400 Subject: [PATCH 136/309] 2 kinds of peers: outbound and inbound --- peer.go | 24 ++++++++++++++---------- peer_test.go | 4 ++-- switch.go | 17 ++++++++--------- switch_test.go | 12 ++++++------ 4 files changed, 30 insertions(+), 27 deletions(-) diff --git a/peer.go b/peer.go index 3d2b4720d..262569187 100644 --- a/peer.go +++ b/peer.go @@ -32,7 +32,7 @@ type Peer struct { Data *cmn.CMap // User data. } -// PeerConfig is a Peer configuration +// PeerConfig is a Peer configuration. type PeerConfig struct { AuthEnc bool // authenticated encryption @@ -45,7 +45,8 @@ type PeerConfig struct { FuzzConfig *FuzzConnConfig } -func defaultPeerConfig() *PeerConfig { +// DefaultPeerConfig returns the default config. +func DefaultPeerConfig() *PeerConfig { return &PeerConfig{ AuthEnc: true, Fuzz: false, @@ -56,18 +57,17 @@ func defaultPeerConfig() *PeerConfig { } } -func newPeer(addr *NetAddress, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), ourNodePrivKey crypto.PrivKeyEd25519) (*Peer, error) { - return newPeerWithConfig(addr, reactorsByCh, chDescs, onPeerError, ourNodePrivKey, defaultPeerConfig()) +func newOutboundPeer(addr *NetAddress, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), ourNodePrivKey crypto.PrivKeyEd25519) (*Peer, error) { + return newOutboundPeerWithConfig(addr, reactorsByCh, chDescs, onPeerError, ourNodePrivKey, DefaultPeerConfig()) } -func newPeerWithConfig(addr *NetAddress, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), ourNodePrivKey crypto.PrivKeyEd25519, config *PeerConfig) (*Peer, error) { +func newOutboundPeerWithConfig(addr *NetAddress, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), ourNodePrivKey crypto.PrivKeyEd25519, config *PeerConfig) (*Peer, error) { conn, err := dial(addr, config) if err != nil { return nil, err } - // outbound = true - peer, err := newPeerFromExistingConnAndConfig(conn, true, reactorsByCh, chDescs, onPeerError, ourNodePrivKey, config) + peer, err := newPeerFromConnAndConfig(conn, true, reactorsByCh, chDescs, onPeerError, ourNodePrivKey, config) if err != nil { conn.Close() return nil, err @@ -75,11 +75,15 @@ func newPeerWithConfig(addr *NetAddress, reactorsByCh map[byte]Reactor, chDescs return peer, nil } -func newPeerFromExistingConn(rawConn net.Conn, outbound bool, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), ourNodePrivKey crypto.PrivKeyEd25519) (*Peer, error) { - return newPeerFromExistingConnAndConfig(rawConn, outbound, reactorsByCh, chDescs, onPeerError, ourNodePrivKey, defaultPeerConfig()) +func newInboundPeer(conn net.Conn, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), ourNodePrivKey crypto.PrivKeyEd25519) (*Peer, error) { + return newInboundPeerWithConfig(conn, reactorsByCh, chDescs, onPeerError, ourNodePrivKey, DefaultPeerConfig()) } -func newPeerFromExistingConnAndConfig(rawConn net.Conn, outbound bool, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), ourNodePrivKey crypto.PrivKeyEd25519, config *PeerConfig) (*Peer, error) { +func newInboundPeerWithConfig(conn net.Conn, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), ourNodePrivKey crypto.PrivKeyEd25519, config *PeerConfig) (*Peer, error) { + return newPeerFromConnAndConfig(conn, false, reactorsByCh, chDescs, onPeerError, ourNodePrivKey, config) +} + +func newPeerFromConnAndConfig(rawConn net.Conn, outbound bool, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), ourNodePrivKey crypto.PrivKeyEd25519, config *PeerConfig) (*Peer, error) { conn := rawConn // Fuzz connection diff --git a/peer_test.go b/peer_test.go index d564022ad..199428af1 100644 --- a/peer_test.go +++ b/peer_test.go @@ -35,7 +35,7 @@ func createPeerAndPerformHandshake(addr *NetAddress) (*Peer, error) { } reactorsByCh := map[byte]Reactor{0x01: NewTestReactor(chDescs, true)} pk := crypto.GenPrivKeyEd25519() - p, err := newPeer(addr, reactorsByCh, chDescs, func(p *Peer, r interface{}) {}, pk) + p, err := newOutboundPeer(addr, reactorsByCh, chDescs, func(p *Peer, r interface{}) {}, pk) if err != nil { return nil, err } @@ -81,7 +81,7 @@ func (p *remotePeer) accept(l net.Listener) { if err != nil { golog.Fatalf("Failed to accept conn: %+v", err) } - peer, err := newPeerFromExistingConn(conn, false, make(map[byte]Reactor), make([]*ChannelDescriptor, 0), func(p *Peer, r interface{}) {}, p.PrivKey) + peer, err := newInboundPeer(conn, make(map[byte]Reactor), make([]*ChannelDescriptor, 0), func(p *Peer, r interface{}) {}, p.PrivKey) if err != nil { golog.Fatalf("Failed to create a peer: %+v", err) } diff --git a/switch.go b/switch.go index f4889a5f5..7505c0632 100644 --- a/switch.go +++ b/switch.go @@ -317,7 +317,7 @@ func (sw *Switch) DialPeerWithAddress(addr *NetAddress, persistent bool) (*Peer, sw.dialing.Set(addr.IP.String(), addr) defer sw.dialing.Delete(addr.IP.String()) - peer, err := newPeerWithConfig(addr, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey, peerConfigFromGoConfig(sw.config)) + peer, err := newOutboundPeerWithConfig(addr, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey, peerConfigFromGoConfig(sw.config)) if err != nil { log.Info("Failed dialing peer", "address", addr, "error", err) return nil, err @@ -436,7 +436,7 @@ func (sw *Switch) listenerRoutine(l Listener) { } // New inbound connection! - err := sw.AddPeerWithConnectionAndConfig(inConn, false, peerConfigFromGoConfig(sw.config)) + err := sw.addPeerWithConnectionAndConfig(inConn, peerConfigFromGoConfig(sw.config)) if err != nil { log.Notice("Ignoring inbound connection: error while adding peer", "address", inConn.RemoteAddr().String(), "error", err) continue @@ -498,14 +498,14 @@ func Connect2Switches(switches []*Switch, i, j int) { c1, c2 := net.Pipe() doneCh := make(chan struct{}) go func() { - err := switchI.AddPeerWithConnection(c1, false) + err := switchI.addPeerWithConnection(c1) if PanicOnAddPeerErr && err != nil { panic(err) } doneCh <- struct{}{} }() go func() { - err := switchJ.AddPeerWithConnection(c2, false) + err := switchJ.addPeerWithConnection(c2) if PanicOnAddPeerErr && err != nil { panic(err) } @@ -540,9 +540,8 @@ func makeSwitch(i int, network, version string, initSwitch func(int, *Switch) *S return s } -// AddPeerWithConnection creates a newPeer from the connection, performs the handshake, and adds it to the switch. -func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool) error { - peer, err := newPeerFromExistingConn(conn, outbound, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey) +func (sw *Switch) addPeerWithConnection(conn net.Conn) error { + peer, err := newInboundPeer(conn, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey) if err != nil { conn.Close() return err @@ -556,8 +555,8 @@ func (sw *Switch) AddPeerWithConnection(conn net.Conn, outbound bool) error { return nil } -func (sw *Switch) AddPeerWithConnectionAndConfig(conn net.Conn, outbound bool, config *PeerConfig) error { - peer, err := newPeerFromExistingConnAndConfig(conn, outbound, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey, config) +func (sw *Switch) addPeerWithConnectionAndConfig(conn net.Conn, config *PeerConfig) error { + peer, err := newInboundPeerWithConfig(conn, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey, config) if err != nil { conn.Close() return err diff --git a/switch_test.go b/switch_test.go index 530a12b17..6a9d6e858 100644 --- a/switch_test.go +++ b/switch_test.go @@ -176,10 +176,10 @@ func TestConnAddrFilter(t *testing.T) { // connect to good peer go func() { - s1.AddPeerWithConnection(c1, false) + s1.addPeerWithConnection(c1) }() go func() { - s2.AddPeerWithConnection(c2, true) + s2.addPeerWithConnection(c2) }() // Wait for things to happen, peers to get added... @@ -211,10 +211,10 @@ func TestConnPubKeyFilter(t *testing.T) { // connect to good peer go func() { - s1.AddPeerWithConnection(c1, false) + s1.addPeerWithConnection(c1) }() go func() { - s2.AddPeerWithConnection(c2, true) + s2.addPeerWithConnection(c2) }() // Wait for things to happen, peers to get added... @@ -242,7 +242,7 @@ func TestSwitchStopsNonPersistentPeerOnError(t *testing.T) { rp.Start() defer rp.Stop() - peer, err := newPeer(rp.RemoteAddr(), sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey) + peer, err := newOutboundPeer(rp.RemoteAddr(), sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey) require.Nil(err) err = sw.AddPeer(peer) require.Nil(err) @@ -268,7 +268,7 @@ func TestSwitchReconnectsToPersistentPeer(t *testing.T) { rp.Start() defer rp.Stop() - peer, err := newPeer(rp.RemoteAddr(), sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey) + peer, err := newOutboundPeer(rp.RemoteAddr(), sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey) peer.makePersistent() require.Nil(err) err = sw.AddPeer(peer) From 06d219db8eeb53a3d311eff0768f7d23df8ec12f Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Fri, 14 Apr 2017 12:43:28 +0400 Subject: [PATCH 137/309] test peer with no auth enc --- connection.go | 7 ++++--- glide.lock | 10 +++++----- glide.yaml | 4 +++- peer.go | 23 ++++++++++++----------- peer_test.go | 45 ++++++++++++++++++++++++++++++++++++++------- switch.go | 4 ++-- switch_test.go | 8 ++++---- 7 files changed, 68 insertions(+), 33 deletions(-) diff --git a/connection.go b/connection.go index 3448ae085..cf9bec4c5 100644 --- a/connection.go +++ b/connection.go @@ -85,13 +85,14 @@ type MConnection struct { RemoteAddress *NetAddress } -// MConnConfig is a MConnection configuration +// MConnConfig is a MConnection configuration. type MConnConfig struct { SendRate int64 RecvRate int64 } -func defaultMConnectionConfig() *MConnConfig { +// DefaultMConnConfig returns the default config. +func DefaultMConnConfig() *MConnConfig { return &MConnConfig{ SendRate: defaultSendRate, RecvRate: defaultRecvRate, @@ -105,7 +106,7 @@ func NewMConnection(conn net.Conn, chDescs []*ChannelDescriptor, onReceive recei chDescs, onReceive, onError, - defaultMConnectionConfig()) + DefaultMConnConfig()) } // NewMConnectionWithConfig wraps net.Conn and creates multiplex connection with a config diff --git a/glide.lock b/glide.lock index 797c86031..423f18a09 100644 --- a/glide.lock +++ b/glide.lock @@ -1,5 +1,5 @@ -hash: 92a49cbcf88a339e4d29559fe291c30e61eacda1020fd04dfcd97de834e18b3e -updated: 2017-04-10T11:17:14.66226896Z +hash: ef8ea7b02d9a133bfbfcf3f4615d43be0956ad2bc9eb0050e0721fca12d09308 +updated: 2017-04-14T08:28:07.579629532Z imports: - name: github.com/btcsuite/btcd version: 4b348c1d33373d672edd83fc576892d0e46686d2 @@ -25,9 +25,9 @@ imports: - name: github.com/tendermint/go-config version: 620dcbbd7d587cf3599dedbf329b64311b0c307a - name: github.com/tendermint/go-crypto - version: 3f47cfac5fcd9e0f1727c7db980b3559913b3e3a + version: 750b25c47a5782f5f2b773ed9e706cb82b3ccef4 - name: github.com/tendermint/go-data - version: c955b191240568440ea902e14dad2ce19727543a + version: e7fcc6d081ec8518912fcdc103188275f83a3ee5 - name: github.com/tendermint/go-flowrate version: a20c98e61957faa93b4014fbd902f20ab9317a6a subpackages: @@ -41,7 +41,7 @@ imports: subpackages: - term - name: golang.org/x/crypto - version: 9ef620b9ca2f82b55030ffd4f41327fa9e77a92c + version: cbc3d0884eac986df6e78a039b8792e869bff863 subpackages: - curve25519 - nacl/box diff --git a/glide.yaml b/glide.yaml index cf71cc670..2020b0424 100644 --- a/glide.yaml +++ b/glide.yaml @@ -3,8 +3,9 @@ import: - package: github.com/tendermint/go-common - package: github.com/tendermint/go-config - package: github.com/tendermint/go-crypto + version: develop - package: github.com/tendermint/go-data - version: c955b191240568440ea902e14dad2ce19727543a + version: develop - package: github.com/tendermint/go-flowrate subpackages: - flowrate @@ -16,6 +17,7 @@ import: - nacl/box - nacl/secretbox - ripemd160 +- package: github.com/pkg/errors testImport: - package: github.com/stretchr/testify subpackages: diff --git a/peer.go b/peer.go index 262569187..5461d7e8a 100644 --- a/peer.go +++ b/peer.go @@ -6,6 +6,7 @@ import ( "net" "time" + "github.com/pkg/errors" cmn "github.com/tendermint/go-common" crypto "github.com/tendermint/go-crypto" wire "github.com/tendermint/go-wire" @@ -49,10 +50,10 @@ type PeerConfig struct { func DefaultPeerConfig() *PeerConfig { return &PeerConfig{ AuthEnc: true, - Fuzz: false, - HandshakeTimeout: 20 * time.Second, + HandshakeTimeout: 2 * time.Second, DialTimeout: 3 * time.Second, - MConfig: defaultMConnectionConfig(), + MConfig: DefaultMConnConfig(), + Fuzz: false, FuzzConfig: DefaultFuzzConnConfig(), } } @@ -64,7 +65,7 @@ func newOutboundPeer(addr *NetAddress, reactorsByCh map[byte]Reactor, chDescs [] func newOutboundPeerWithConfig(addr *NetAddress, reactorsByCh map[byte]Reactor, chDescs []*ChannelDescriptor, onPeerError func(*Peer, interface{}), ourNodePrivKey crypto.PrivKeyEd25519, config *PeerConfig) (*Peer, error) { conn, err := dial(addr, config) if err != nil { - return nil, err + return nil, errors.Wrap(err, "Error creating peer") } peer, err := newPeerFromConnAndConfig(conn, true, reactorsByCh, chDescs, onPeerError, ourNodePrivKey, config) @@ -99,7 +100,7 @@ func newPeerFromConnAndConfig(rawConn net.Conn, outbound bool, reactorsByCh map[ var err error conn, err = MakeSecretConnection(conn, ourNodePrivKey) if err != nil { - return nil, err + return nil, errors.Wrap(err, "Error creating peer") } } @@ -157,10 +158,10 @@ func (p *Peer) HandshakeTimeout(ourNodeInfo *NodeInfo, timeout time.Duration) er log.Notice("Peer handshake", "peerNodeInfo", peerNodeInfo) }) if err1 != nil { - return err1 + return errors.Wrap(err1, "Error during handshake/write") } if err2 != nil { - return err2 + return errors.Wrap(err2, "Error during handshake/read") } if p.config.AuthEnc { @@ -174,7 +175,7 @@ func (p *Peer) HandshakeTimeout(ourNodeInfo *NodeInfo, timeout time.Duration) er // Remove deadline p.conn.SetDeadline(time.Time{}) - peerNodeInfo.RemoteAddr = p.RemoteAddr().String() + peerNodeInfo.RemoteAddr = p.Addr().String() p.NodeInfo = peerNodeInfo p.Key = peerNodeInfo.PubKey.KeyString() @@ -182,12 +183,12 @@ func (p *Peer) HandshakeTimeout(ourNodeInfo *NodeInfo, timeout time.Duration) er return nil } -// RemoteAddr returns the remote network address. -func (p *Peer) RemoteAddr() net.Addr { +// Addr returns peer's network address. +func (p *Peer) Addr() net.Addr { return p.conn.RemoteAddr() } -// PubKey returns the remote public key. +// PubKey returns peer's public key. func (p *Peer) PubKey() crypto.PubKeyEd25519 { if p.config.AuthEnc { return p.conn.(*SecretConnection).RemotePubKey() diff --git a/peer_test.go b/peer_test.go index 199428af1..5c23f3424 100644 --- a/peer_test.go +++ b/peer_test.go @@ -12,15 +12,41 @@ import ( crypto "github.com/tendermint/go-crypto" ) -func TestPeerStartStop(t *testing.T) { +func TestPeerBasic(t *testing.T) { assert, require := assert.New(t), require.New(t) // simulate remote peer - rp := &remotePeer{PrivKey: crypto.GenPrivKeyEd25519()} + rp := &remotePeer{PrivKey: crypto.GenPrivKeyEd25519(), Config: DefaultPeerConfig()} rp.Start() defer rp.Stop() - p, err := createPeerAndPerformHandshake(rp.RemoteAddr()) + p, err := createOutboundPeerAndPerformHandshake(rp.Addr(), DefaultPeerConfig()) + require.Nil(err) + + p.Start() + defer p.Stop() + + assert.True(p.IsRunning()) + assert.True(p.IsOutbound()) + assert.False(p.IsPersistent()) + p.makePersistent() + assert.True(p.IsPersistent()) + assert.Equal(rp.Addr().String(), p.Addr().String()) + assert.Equal(rp.PubKey(), p.PubKey()) +} + +func TestPeerWithoutAuthEnc(t *testing.T) { + assert, require := assert.New(t), require.New(t) + + config := DefaultPeerConfig() + config.AuthEnc = false + + // simulate remote peer + rp := &remotePeer{PrivKey: crypto.GenPrivKeyEd25519(), Config: config} + rp.Start() + defer rp.Stop() + + p, err := createOutboundPeerAndPerformHandshake(rp.Addr(), config) require.Nil(err) p.Start() @@ -29,13 +55,13 @@ func TestPeerStartStop(t *testing.T) { assert.True(p.IsRunning()) } -func createPeerAndPerformHandshake(addr *NetAddress) (*Peer, error) { +func createOutboundPeerAndPerformHandshake(addr *NetAddress, config *PeerConfig) (*Peer, error) { chDescs := []*ChannelDescriptor{ &ChannelDescriptor{ID: 0x01, Priority: 1}, } reactorsByCh := map[byte]Reactor{0x01: NewTestReactor(chDescs, true)} pk := crypto.GenPrivKeyEd25519() - p, err := newOutboundPeer(addr, reactorsByCh, chDescs, func(p *Peer, r interface{}) {}, pk) + p, err := newOutboundPeerWithConfig(addr, reactorsByCh, chDescs, func(p *Peer, r interface{}) {}, pk, config) if err != nil { return nil, err } @@ -53,14 +79,19 @@ func createPeerAndPerformHandshake(addr *NetAddress) (*Peer, error) { type remotePeer struct { PrivKey crypto.PrivKeyEd25519 + Config *PeerConfig addr *NetAddress quit chan struct{} } -func (p *remotePeer) RemoteAddr() *NetAddress { +func (p *remotePeer) Addr() *NetAddress { return p.addr } +func (p *remotePeer) PubKey() crypto.PubKeyEd25519 { + return p.PrivKey.PubKey().(crypto.PubKeyEd25519) +} + func (p *remotePeer) Start() { l, e := net.Listen("tcp", "127.0.0.1:0") // any available address if e != nil { @@ -81,7 +112,7 @@ func (p *remotePeer) accept(l net.Listener) { if err != nil { golog.Fatalf("Failed to accept conn: %+v", err) } - peer, err := newInboundPeer(conn, make(map[byte]Reactor), make([]*ChannelDescriptor, 0), func(p *Peer, r interface{}) {}, p.PrivKey) + peer, err := newInboundPeerWithConfig(conn, make(map[byte]Reactor), make([]*ChannelDescriptor, 0), func(p *Peer, r interface{}) {}, p.PrivKey, p.Config) if err != nil { golog.Fatalf("Failed to create a peer: %+v", err) } diff --git a/switch.go b/switch.go index 7505c0632..8ceb1ab70 100644 --- a/switch.go +++ b/switch.go @@ -200,7 +200,7 @@ func (sw *Switch) OnStop() { // NOTE: This performs a blocking handshake before the peer is added. // CONTRACT: If error is returned, peer is nil, and conn is immediately closed. func (sw *Switch) AddPeer(peer *Peer) error { - if err := sw.FilterConnByAddr(peer.RemoteAddr()); err != nil { + if err := sw.FilterConnByAddr(peer.Addr()); err != nil { return err } @@ -376,7 +376,7 @@ func (sw *Switch) Peers() IPeerSet { // Disconnect from a peer due to external error, retry if it is a persistent peer. // TODO: make record depending on reason. func (sw *Switch) StopPeerForError(peer *Peer, reason interface{}) { - addr := NewNetAddress(peer.RemoteAddr()) + addr := NewNetAddress(peer.Addr()) log.Notice("Stopping peer for error", "peer", peer, "error", reason) sw.stopAndRemovePeer(peer, reason) diff --git a/switch_test.go b/switch_test.go index 6a9d6e858..a81bb4ac0 100644 --- a/switch_test.go +++ b/switch_test.go @@ -238,11 +238,11 @@ func TestSwitchStopsNonPersistentPeerOnError(t *testing.T) { defer sw.Stop() // simulate remote peer - rp := &remotePeer{PrivKey: crypto.GenPrivKeyEd25519()} + rp := &remotePeer{PrivKey: crypto.GenPrivKeyEd25519(), Config: DefaultPeerConfig()} rp.Start() defer rp.Stop() - peer, err := newOutboundPeer(rp.RemoteAddr(), sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey) + peer, err := newOutboundPeer(rp.Addr(), sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey) require.Nil(err) err = sw.AddPeer(peer) require.Nil(err) @@ -264,11 +264,11 @@ func TestSwitchReconnectsToPersistentPeer(t *testing.T) { defer sw.Stop() // simulate remote peer - rp := &remotePeer{PrivKey: crypto.GenPrivKeyEd25519()} + rp := &remotePeer{PrivKey: crypto.GenPrivKeyEd25519(), Config: DefaultPeerConfig()} rp.Start() defer rp.Stop() - peer, err := newOutboundPeer(rp.RemoteAddr(), sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey) + peer, err := newOutboundPeer(rp.Addr(), sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey) peer.makePersistent() require.Nil(err) err = sw.AddPeer(peer) From ebe23f1379dc8610411e06ad797f16dc2a7f0635 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Fri, 14 Apr 2017 14:21:58 +0400 Subject: [PATCH 138/309] refactor MConnection#sendBytes --- connection.go | 6 ++---- connection_test.go | 9 +++++++-- peer_test.go | 21 +++++++++++++++++++++ 3 files changed, 30 insertions(+), 6 deletions(-) diff --git a/connection.go b/connection.go index cf9bec4c5..6658722ab 100644 --- a/connection.go +++ b/connection.go @@ -557,14 +557,12 @@ func newChannel(conn *MConnection, desc *ChannelDescriptor) *Channel { // Goroutine-safe // Times out (and returns false) after defaultSendTimeout func (ch *Channel) sendBytes(bytes []byte) bool { - timeout := time.NewTimer(defaultSendTimeout) select { - case <-timeout.C: - // timeout - return false case ch.sendQueue <- bytes: atomic.AddInt32(&ch.sendQueueSize, 1) return true + case <-time.After(defaultSendTimeout): + return false } } diff --git a/connection_test.go b/connection_test.go index cd6bb4a8f..a7d6ebcf9 100644 --- a/connection_test.go +++ b/connection_test.go @@ -19,7 +19,7 @@ func createMConnection(conn net.Conn) *p2p.MConnection { } func createMConnectionWithCallbacks(conn net.Conn, onReceive func(chID byte, msgBytes []byte), onError func(r interface{})) *p2p.MConnection { - chDescs := []*p2p.ChannelDescriptor{&p2p.ChannelDescriptor{ID: 0x01, Priority: 1}} + chDescs := []*p2p.ChannelDescriptor{&p2p.ChannelDescriptor{ID: 0x01, Priority: 1, SendQueueCapacity: 1}} return p2p.NewMConnection(conn, chDescs, onReceive, onError) } @@ -37,13 +37,18 @@ func TestMConnectionSend(t *testing.T) { msg := "Ant-Man" assert.True(mconn.Send(0x01, msg)) - assert.False(mconn.CanSend(0x01)) + assert.False(mconn.CanSend(0x01), "CanSend should return false because queue is full") + // assert.False(mconn.Send(0x01, msg), "Send should return false because queue is full") + // assert.False(mconn.TrySend(0x01, msg), "TrySend should return false because queue is full") server.Read(make([]byte, len(msg))) assert.True(mconn.CanSend(0x01)) msg = "Spider-Man" assert.True(mconn.TrySend(0x01, msg)) server.Read(make([]byte, len(msg))) + + assert.False(mconn.CanSend(0x05), "CanSend should return false because channel is unknown") + assert.False(mconn.Send(0x05, "Absorbing Man"), "Send should return false because channel is unknown") } func TestMConnectionReceive(t *testing.T) { diff --git a/peer_test.go b/peer_test.go index 5c23f3424..5f3ed0e23 100644 --- a/peer_test.go +++ b/peer_test.go @@ -55,6 +55,27 @@ func TestPeerWithoutAuthEnc(t *testing.T) { assert.True(p.IsRunning()) } +func TestPeerSend(t *testing.T) { + assert, require := assert.New(t), require.New(t) + + config := DefaultPeerConfig() + config.AuthEnc = false + + // simulate remote peer + rp := &remotePeer{PrivKey: crypto.GenPrivKeyEd25519(), Config: config} + rp.Start() + defer rp.Stop() + + p, err := createOutboundPeerAndPerformHandshake(rp.Addr(), config) + require.Nil(err) + + p.Start() + defer p.Stop() + + assert.True(p.CanSend(0x01)) + assert.True(p.Send(0x01, "Asylum")) +} + func createOutboundPeerAndPerformHandshake(addr *NetAddress, config *PeerConfig) (*Peer, error) { chDescs := []*ChannelDescriptor{ &ChannelDescriptor{ID: 0x01, Priority: 1}, From 6dc113aa808be0be85890b6a001011c29f1773e0 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Fri, 14 Apr 2017 14:56:02 +0400 Subject: [PATCH 139/309] [netaddress] panic only when normal run --- netaddress.go | 42 +++++++++++++++++++++++++++++++----------- 1 file changed, 31 insertions(+), 11 deletions(-) diff --git a/netaddress.go b/netaddress.go index 90fcf6a43..263ec9037 100644 --- a/netaddress.go +++ b/netaddress.go @@ -6,6 +6,7 @@ package p2p import ( "errors" + "flag" "net" "strconv" "time" @@ -13,28 +14,36 @@ import ( cmn "github.com/tendermint/go-common" ) +// NetAddress defines information about a peer on the network +// including its IP address, and port. type NetAddress struct { IP net.IP Port uint16 str string } +// NewNetAddress returns a new NetAddress using the provided TCP +// address. When testing, other net.Addr (except TCP) will result in +// using 0.0.0.0:0. When normal run, other net.Addr (except TCP) will +// panic. // TODO: socks proxies? func NewNetAddress(addr net.Addr) *NetAddress { tcpAddr, ok := addr.(*net.TCPAddr) if !ok { - log.Warn(`Only TCPAddrs are supported. If used for anything but testing, - may result in undefined behaviour!`, "addr", addr) - return NewNetAddressIPPort(net.IP("0.0.0.0"), 0) - // NOTE: it would be nice to only not panic if we're in testing ... - // PanicSanity(Fmt("Only TCPAddrs are supported. Got: %v", addr)) + if flag.Lookup("test.v") == nil { // normal run + cmn.PanicSanity(cmn.Fmt("Only TCPAddrs are supported. Got: %v", addr)) + } else { // in testing + return NewNetAddressIPPort(net.IP("0.0.0.0"), 0) + } } ip := tcpAddr.IP port := uint16(tcpAddr.Port) return NewNetAddressIPPort(ip, port) } -// Also resolves the host if host is not an IP. +// NewNetAddressString returns a new NetAddress using the provided +// address in the form of "IP:Port". Also resolves the host if host +// is not an IP. func NewNetAddressString(addr string) (*NetAddress, error) { host, portStr, err := net.SplitHostPort(addr) @@ -62,6 +71,8 @@ func NewNetAddressString(addr string) (*NetAddress, error) { return na, nil } +// NewNetAddressStrings returns an array of NetAddress'es build using +// the provided strings. func NewNetAddressStrings(addrs []string) ([]*NetAddress, error) { netAddrs := make([]*NetAddress, len(addrs)) for i, addr := range addrs { @@ -74,6 +85,8 @@ func NewNetAddressStrings(addrs []string) ([]*NetAddress, error) { return netAddrs, nil } +// NewNetAddressIPPort returns a new NetAddress using the provided IP +// and port number. func NewNetAddressIPPort(ip net.IP, port uint16) *NetAddress { na := &NetAddress{ IP: ip, @@ -86,23 +99,25 @@ func NewNetAddressIPPort(ip net.IP, port uint16) *NetAddress { return na } +// Equals reports whether na and other are the same addresses. func (na *NetAddress) Equals(other interface{}) bool { if o, ok := other.(*NetAddress); ok { return na.String() == o.String() - } else { - return false } + + return false } func (na *NetAddress) Less(other interface{}) bool { if o, ok := other.(*NetAddress); ok { return na.String() < o.String() - } else { - cmn.PanicSanity("Cannot compare unequal types") - return false } + + cmn.PanicSanity("Cannot compare unequal types") + return false } +// String representation. func (na *NetAddress) String() string { if na.str == "" { na.str = net.JoinHostPort( @@ -113,6 +128,7 @@ func (na *NetAddress) String() string { return na.str } +// Dial calls net.Dial on the address. func (na *NetAddress) Dial() (net.Conn, error) { conn, err := net.Dial("tcp", na.String()) if err != nil { @@ -121,6 +137,7 @@ func (na *NetAddress) Dial() (net.Conn, error) { return conn, nil } +// DialTimeout calls net.DialTimeout on the address. func (na *NetAddress) DialTimeout(timeout time.Duration) (net.Conn, error) { conn, err := net.DialTimeout("tcp", na.String(), timeout) if err != nil { @@ -129,6 +146,7 @@ func (na *NetAddress) DialTimeout(timeout time.Duration) (net.Conn, error) { return conn, nil } +// Routable returns true if the address is routable. func (na *NetAddress) Routable() bool { // TODO(oga) bitcoind doesn't include RFC3849 here, but should we? return na.Valid() && !(na.RFC1918() || na.RFC3927() || na.RFC4862() || @@ -142,10 +160,12 @@ func (na *NetAddress) Valid() bool { na.IP.Equal(net.IPv4bcast)) } +// Local returns true if it is a local address. func (na *NetAddress) Local() bool { return na.IP.IsLoopback() || zero4.Contains(na.IP) } +// ReachabilityTo checks whenever o can be reached from na. func (na *NetAddress) ReachabilityTo(o *NetAddress) int { const ( Unreachable = 0 From fbedb426ce2eb1cd82f474ceb6b38acffdf859ef Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Fri, 14 Apr 2017 16:37:07 +0400 Subject: [PATCH 140/309] tests for NetAddress --- netaddress_test.go | 113 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 113 insertions(+) create mode 100644 netaddress_test.go diff --git a/netaddress_test.go b/netaddress_test.go new file mode 100644 index 000000000..db871fdec --- /dev/null +++ b/netaddress_test.go @@ -0,0 +1,113 @@ +package p2p + +import ( + "net" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestNewNetAddress(t *testing.T) { + assert, require := assert.New(t), require.New(t) + + tcpAddr, err := net.ResolveTCPAddr("tcp", "127.0.0.1:8080") + require.Nil(err) + addr := NewNetAddress(tcpAddr) + + assert.Equal("127.0.0.1:8080", addr.String()) + + assert.NotPanics(func() { + NewNetAddress(&net.UDPAddr{IP: net.ParseIP("127.0.0.1"), Port: 8000}) + }, "Calling NewNetAddress with UDPAddr should not panic in testing") +} + +func TestNewNetAddressString(t *testing.T) { + assert, require := assert.New(t), require.New(t) + + tests := []struct { + addr string + correct bool + }{ + {"127.0.0.1:8080", true}, + {"127.0.0:8080", false}, + {"a", false}, + {"127.0.0.1:a", false}, + {"a:8080", false}, + {"8082", false}, + {"127.0.0:8080000", false}, + } + + for _, t := range tests { + addr, err := NewNetAddressString(t.addr) + if t.correct { + require.Nil(err) + assert.Equal(t.addr, addr.String()) + } else { + require.NotNil(err) + } + } +} + +func TestNewNetAddressStrings(t *testing.T) { + assert, require := assert.New(t), require.New(t) + addrs, err := NewNetAddressStrings([]string{"127.0.0.1:8080", "127.0.0.2:8080"}) + require.Nil(err) + + assert.Equal(2, len(addrs)) +} + +func TestNewNetAddressIPPort(t *testing.T) { + assert := assert.New(t) + addr := NewNetAddressIPPort(net.ParseIP("127.0.0.1"), 8080) + + assert.Equal("127.0.0.1:8080", addr.String()) +} + +func TestNetAddressProperties(t *testing.T) { + assert, require := assert.New(t), require.New(t) + + // TODO add more test cases + tests := []struct { + addr string + valid bool + local bool + routable bool + }{ + {"127.0.0.1:8080", true, true, false}, + {"ya.ru:80", true, false, true}, + } + + for _, t := range tests { + addr, err := NewNetAddressString(t.addr) + require.Nil(err) + + assert.Equal(t.valid, addr.Valid()) + assert.Equal(t.local, addr.Local()) + assert.Equal(t.routable, addr.Routable()) + } +} + +func TestNetAddressReachabilityTo(t *testing.T) { + assert, require := assert.New(t), require.New(t) + + // TODO add more test cases + tests := []struct { + addr string + other string + reachability int + }{ + {"127.0.0.1:8080", "127.0.0.1:8081", 0}, + {"ya.ru:80", "127.0.0.1:8080", 1}, + } + + for _, t := range tests { + addr, err := NewNetAddressString(t.addr) + require.Nil(err) + + other, err := NewNetAddressString(t.other) + require.Nil(err) + + assert.Equal(t.reachability, addr.ReachabilityTo(other)) + } +} From 2ac69176e1f80329f08221f79a15199ef3f6a810 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Tue, 18 Apr 2017 12:11:48 +0400 Subject: [PATCH 141/309] add a comment for MConnection#CanSend also add a note to TestMConnectionSend --- connection.go | 2 ++ connection_test.go | 4 ++-- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/connection.go b/connection.go index 6658722ab..a14fa5ee4 100644 --- a/connection.go +++ b/connection.go @@ -258,6 +258,8 @@ func (c *MConnection) TrySend(chID byte, msg interface{}) bool { return ok } +// CanSend returns true if you can send more data onto the chID, false +// otherwise. Use only as a heuristic. func (c *MConnection) CanSend(chID byte) bool { if !c.IsRunning() { return false diff --git a/connection_test.go b/connection_test.go index a7d6ebcf9..84e20eee3 100644 --- a/connection_test.go +++ b/connection_test.go @@ -37,9 +37,9 @@ func TestMConnectionSend(t *testing.T) { msg := "Ant-Man" assert.True(mconn.Send(0x01, msg)) + // Note: subsequent Send/TrySend calls could pass because we are reading from + // the send queue in a separate goroutine. assert.False(mconn.CanSend(0x01), "CanSend should return false because queue is full") - // assert.False(mconn.Send(0x01, msg), "Send should return false because queue is full") - // assert.False(mconn.TrySend(0x01, msg), "TrySend should return false because queue is full") server.Read(make([]byte, len(msg))) assert.True(mconn.CanSend(0x01)) From 7d5b62b61f11d54d57113743fcca49f52775eddc Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Tue, 18 Apr 2017 23:58:24 -0400 Subject: [PATCH 142/309] CHANGELOG and version bump --- CHANGELOG.md | 21 +++++++++++++++++++++ version.go | 2 +- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 81e30fcca..bba6dd77b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,26 @@ # Changelog +## 0.5.0 (April 18, 2017) + +BREAKING CHANGES: + +- Remove or unexport methods from FuzzedConnection: Active, Mode, ProbDropRW, ProbDropConn, ProbSleep, MaxDelayMilliseconds, Fuzz +- switch.AddPeerWithConnection is unexported and replaced by switch.AddPeer +- switch.DialPeerWithAddress takes a bool, setting the peer as persistent or not + +FEATURES: + +- Persistent peers: any peer considered a "seed" will be reconnected to when the connection is dropped + + +IMPROVEMENTS: + +- Many more tests and comments +- Refactor configurations for less dependence on go-config. Introduces new structs PeerConfig, MConnConfig, FuzzConnConfig +- New methods on peer: CloseConn, HandshakeTimeout, IsPersistent, Addr, PubKey +- NewNetAddress supports a testing mode where the address defaults to 0.0.0.0:0 + + ## 0.4.0 (March 6, 2017) BREAKING CHANGES: diff --git a/version.go b/version.go index c13ec447b..9a4c7bbaf 100644 --- a/version.go +++ b/version.go @@ -1,3 +1,3 @@ package p2p -const Version = "0.4.0" // DialSeeds returns an error +const Version = "0.5.0" From e05052b079fa407fe3aa74ebd0838c6a64b77835 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Wed, 19 Apr 2017 00:01:55 -0400 Subject: [PATCH 143/309] update glide --- glide.lock | 30 ++++++++++++++++-------------- glide.yaml | 4 ++++ 2 files changed, 20 insertions(+), 14 deletions(-) diff --git a/glide.lock b/glide.lock index 423f18a09..71505ea05 100644 --- a/glide.lock +++ b/glide.lock @@ -1,31 +1,33 @@ -hash: ef8ea7b02d9a133bfbfcf3f4615d43be0956ad2bc9eb0050e0721fca12d09308 -updated: 2017-04-14T08:28:07.579629532Z +hash: f3d76bef9548cc37ad6038cb55f0812bac7e64735a99995c9da85010eef27f50 +updated: 2017-04-19T00:00:50.949249104-04:00 imports: - name: github.com/btcsuite/btcd - version: 4b348c1d33373d672edd83fc576892d0e46686d2 + version: b8df516b4b267acf2de46be593a9d948d1d2c420 subpackages: - btcec +- name: github.com/btcsuite/fastsha256 + version: 637e656429416087660c84436a2a035d69d54e2e - name: github.com/BurntSushi/toml - version: b26d9c308763d68093482582cea63d69be07a0f0 + version: 99064174e013895bbd9b025c31100bd1d9b590ca - name: github.com/go-stack/stack version: 100eb0c0a9c5b306ca2fb4f165df21d80ada4b82 - name: github.com/mattn/go-colorable - version: ded68f7a9561c023e790de24279db7ebf473ea80 + version: 9fdad7c47650b7d2e1da50644c1f4ba7f172f252 - name: github.com/mattn/go-isatty - version: fc9e8d8ef48496124e79ae0df75490096eccf6fe + version: 56b76bdf51f7708750eac80fa38b952bb9f32639 - name: github.com/pkg/errors - version: ff09b135c25aae272398c51a07235b90a75aa4f0 + version: 645ef00459ed84a119197bfb8d8205042c6df63d - name: github.com/tendermint/ed25519 version: 1f52c6f8b8a5c7908aff4497c186af344b428925 subpackages: - edwards25519 - extra25519 - name: github.com/tendermint/go-common - version: dcb015dff6c7af21e65c8e2f3b450df19d38c777 + version: f9e3db037330c8a8d61d3966de8473eaf01154fa - name: github.com/tendermint/go-config version: 620dcbbd7d587cf3599dedbf329b64311b0c307a - name: github.com/tendermint/go-crypto - version: 750b25c47a5782f5f2b773ed9e706cb82b3ccef4 + version: 0ca2c6fdb0706001ca4c4b9b80c9f428e8cf39da - name: github.com/tendermint/go-data version: e7fcc6d081ec8518912fcdc103188275f83a3ee5 - name: github.com/tendermint/go-flowrate @@ -35,13 +37,13 @@ imports: - name: github.com/tendermint/go-logger version: cefb3a45c0bf3c493a04e9bcd9b1540528be59f2 - name: github.com/tendermint/go-wire - version: f530b7af7a8b06e612c2063bff6ace49060a085e + version: c1c9a57ab8038448ddea1714c0698f8051e5748c - name: github.com/tendermint/log15 version: ae0f3d6450da9eac7074b439c8e1c3cabf0d5ce6 subpackages: - term - name: golang.org/x/crypto - version: cbc3d0884eac986df6e78a039b8792e869bff863 + version: 1f22c0103821b9390939b6776727195525381532 subpackages: - curve25519 - nacl/box @@ -52,12 +54,12 @@ imports: - ripemd160 - salsa20/salsa - name: golang.org/x/sys - version: f3918c30c5c2cb527c0b071a27c35120a6c0719a + version: 50c6bc5e4292a1d4e65c6e9be5f53be28bcbe28e subpackages: - unix testImports: - name: github.com/davecgh/go-spew - version: 04cdfd42973bb9c8589fd6a731800cf222fde1a9 + version: 6d212800a42e8ab5c146b8ace3490ee17e5225f9 subpackages: - spew - name: github.com/pmezard/go-difflib @@ -65,7 +67,7 @@ testImports: subpackages: - difflib - name: github.com/stretchr/testify - version: 4d4bfba8f1d1027c4fdbe371823030df51419987 + version: 69483b4bd14f5845b5a1e55bca19e954e827f1d0 subpackages: - assert - require diff --git a/glide.yaml b/glide.yaml index 2020b0424..e7edc80ae 100644 --- a/glide.yaml +++ b/glide.yaml @@ -1,7 +1,9 @@ package: github.com/tendermint/go-p2p import: - package: github.com/tendermint/go-common + version: develop - package: github.com/tendermint/go-config + version: develop - package: github.com/tendermint/go-crypto version: develop - package: github.com/tendermint/go-data @@ -10,7 +12,9 @@ import: subpackages: - flowrate - package: github.com/tendermint/go-logger + version: develop - package: github.com/tendermint/go-wire + version: develop - package: github.com/tendermint/log15 - package: golang.org/x/crypto subpackages: From 1a42f946dc6bcd88f9f58c7f2fb86f785584d793 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Wed, 19 Apr 2017 00:05:18 -0400 Subject: [PATCH 144/309] version bump --- version.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/version.go b/version.go index 33eb7fe51..8828f260b 100644 --- a/version.go +++ b/version.go @@ -1,7 +1,7 @@ package rpc const Maj = "0" -const Min = "6" // 0x-prefixed string args handled as hex -const Fix = "0" // +const Min = "7" +const Fix = "0" const Version = Maj + "." + Min + "." + Fix From 057cfb30f12137cfe65851be71beb50ae8ed617f Mon Sep 17 00:00:00 2001 From: Anton Kalyaev Date: Wed, 11 Jan 2017 15:03:14 +0400 Subject: [PATCH 145/309] remove unused error --- pex_reactor.go | 3 --- 1 file changed, 3 deletions(-) diff --git a/pex_reactor.go b/pex_reactor.go index 4ac9306cf..2cffb529c 100644 --- a/pex_reactor.go +++ b/pex_reactor.go @@ -2,7 +2,6 @@ package p2p import ( "bytes" - "errors" "fmt" "math/rand" "reflect" @@ -12,8 +11,6 @@ import ( wire "github.com/tendermint/go-wire" ) -var pexErrInvalidMessage = errors.New("Invalid PEX message") - const ( PexChannel = byte(0x00) ensurePeersPeriodSeconds = 30 From 26f661a5dd0f60c140e6169d7ab90ecefaf51629 Mon Sep 17 00:00:00 2001 From: Anton Kalyaev Date: Wed, 11 Jan 2017 15:03:29 +0400 Subject: [PATCH 146/309] prefer short names --- pex_reactor.go | 112 ++++++++++++++++++++++++------------------------- 1 file changed, 54 insertions(+), 58 deletions(-) diff --git a/pex_reactor.go b/pex_reactor.go index 2cffb529c..01d0cbd18 100644 --- a/pex_reactor.go +++ b/pex_reactor.go @@ -18,10 +18,8 @@ const ( maxPexMessageSize = 1048576 // 1MB ) -/* -PEXReactor handles PEX (peer exchange) and ensures that an -adequate number of peers are connected to the switch. -*/ +// PEXReactor handles PEX (peer exchange) and ensures that an +// adequate number of peers are connected to the switch. type PEXReactor struct { BaseReactor @@ -29,28 +27,28 @@ type PEXReactor struct { book *AddrBook } -func NewPEXReactor(book *AddrBook) *PEXReactor { - pexR := &PEXReactor{ - book: book, +func NewPEXReactor(b *AddrBook) *PEXReactor { + r := &PEXReactor{ + book: b, } - pexR.BaseReactor = *NewBaseReactor(log, "PEXReactor", pexR) - return pexR + r.BaseReactor = *NewBaseReactor(log, "PEXReactor", r) + return r } -func (pexR *PEXReactor) OnStart() error { - pexR.BaseReactor.OnStart() - pexR.book.Start() - go pexR.ensurePeersRoutine() +func (r *PEXReactor) OnStart() error { + r.BaseReactor.OnStart() + r.book.Start() + go r.ensurePeersRoutine() return nil } -func (pexR *PEXReactor) OnStop() { - pexR.BaseReactor.OnStop() - pexR.book.Stop() +func (r *PEXReactor) OnStop() { + r.BaseReactor.OnStop() + r.book.Stop() } -// Implements Reactor -func (pexR *PEXReactor) GetChannels() []*ChannelDescriptor { +// GetChannels implements Reactor +func (r *PEXReactor) GetChannels() []*ChannelDescriptor { return []*ChannelDescriptor{ &ChannelDescriptor{ ID: PexChannel, @@ -60,49 +58,45 @@ func (pexR *PEXReactor) GetChannels() []*ChannelDescriptor { } } -// Implements Reactor -func (pexR *PEXReactor) AddPeer(peer *Peer) { - // Add the peer to the address book - netAddr, err := NewNetAddressString(peer.ListenAddr) +// AddPeer implements Reactor by adding peer to the address book (if inbound) +// or by requesting more addresses (if outbound). +func (r *PEXReactor) AddPeer(p *Peer) { + netAddr, err := NewNetAddressString(p.ListenAddr) if err != nil { // this should never happen - log.Error("Error in AddPeer: invalid peer address", "addr", peer.ListenAddr, "error", err) + log.Error("Error in AddPeer: invalid peer address", "addr", p.ListenAddr, "error", err) return } - if peer.IsOutbound() { - if pexR.book.NeedMoreAddrs() { - pexR.RequestPEX(peer) + if p.IsOutbound() { // For outbound peers, the address is already in the books + if r.book.NeedMoreAddrs() { + r.RequestPEX(p) } - } else { - // For inbound connections, the peer is its own source - // (For outbound peers, the address is already in the books) - pexR.book.AddAddress(netAddr, netAddr) + } else { // For inbound connections, the peer is its own source + r.book.AddAddress(netAddr, netAddr) } } -// Implements Reactor -func (pexR *PEXReactor) RemovePeer(peer *Peer, reason interface{}) { +// RemovePeer implements Reactor +func (r *PEXReactor) RemovePeer(p *Peer, reason interface{}) { // TODO } -// Implements Reactor -// Handles incoming PEX messages. -func (pexR *PEXReactor) Receive(chID byte, src *Peer, msgBytes []byte) { - - // decode message +// Receive implements Reactor by handling incoming PEX messages. +func (r *PEXReactor) Receive(chID byte, src *Peer, msgBytes []byte) { _, msg, err := DecodeMessage(msgBytes) if err != nil { log.Warn("Error decoding message", "error", err) return } + log.Notice("Received message", "msg", msg) switch msg := msg.(type) { case *pexRequestMessage: // src requested some peers. // TODO: prevent abuse. - pexR.SendAddrs(src, pexR.book.GetSelection()) + r.SendAddrs(src, r.book.GetSelection()) case *pexAddrsMessage: // We received some peer addresses from src. // TODO: prevent abuse. @@ -110,7 +104,7 @@ func (pexR *PEXReactor) Receive(chID byte, src *Peer, msgBytes []byte) { srcAddr := src.Connection().RemoteAddress for _, addr := range msg.Addrs { if addr != nil { - pexR.book.AddAddress(addr, srcAddr) + r.book.AddAddress(addr, srcAddr) } } default: @@ -118,30 +112,32 @@ func (pexR *PEXReactor) Receive(chID byte, src *Peer, msgBytes []byte) { } } -// Asks peer for more addresses. -func (pexR *PEXReactor) RequestPEX(peer *Peer) { - peer.Send(PexChannel, struct{ PexMessage }{&pexRequestMessage{}}) +// RequestPEX asks peer for more addresses. +func (r *PEXReactor) RequestPEX(p *Peer) { + p.Send(PexChannel, struct{ PexMessage }{&pexRequestMessage{}}) } -func (pexR *PEXReactor) SendAddrs(peer *Peer, addrs []*NetAddress) { - peer.Send(PexChannel, struct{ PexMessage }{&pexAddrsMessage{Addrs: addrs}}) +// SendAddrs sends addrs to the peer. +func (r *PEXReactor) SendAddrs(p *Peer, addrs []*NetAddress) { + p.Send(PexChannel, struct{ PexMessage }{&pexAddrsMessage{Addrs: addrs}}) } // Ensures that sufficient peers are connected. (continuous) -func (pexR *PEXReactor) ensurePeersRoutine() { +func (r *PEXReactor) ensurePeersRoutine() { // Randomize when routine starts time.Sleep(time.Duration(rand.Int63n(500*ensurePeersPeriodSeconds)) * time.Millisecond) // fire once immediately. - pexR.ensurePeers() + r.ensurePeers() + // fire periodically timer := NewRepeatTimer("pex", ensurePeersPeriodSeconds*time.Second) FOR_LOOP: for { select { case <-timer.Ch: - pexR.ensurePeers() - case <-pexR.Quit: + r.ensurePeers() + case <-r.Quit: break FOR_LOOP } } @@ -151,8 +147,8 @@ FOR_LOOP: } // Ensures that sufficient peers are connected. (once) -func (pexR *PEXReactor) ensurePeers() { - numOutPeers, _, numDialing := pexR.Switch.NumPeers() +func (r *PEXReactor) ensurePeers() { + numOutPeers, _, numDialing := r.Switch.NumPeers() numToDial := minNumOutboundPeers - (numOutPeers + numDialing) log.Info("Ensure peers", "numOutPeers", numOutPeers, "numDialing", numDialing, "numToDial", numToDial) if numToDial <= 0 { @@ -168,13 +164,13 @@ func (pexR *PEXReactor) ensurePeers() { // Try to fetch a new peer 3 times. // This caps the maximum number of tries to 3 * numToDial. for j := 0; j < 3; j++ { - try := pexR.book.PickAddress(newBias) + try := r.book.PickAddress(newBias) if try == nil { break } alreadySelected := toDial.Has(try.IP.String()) - alreadyDialing := pexR.Switch.IsDialing(try) - alreadyConnected := pexR.Switch.Peers().Has(try.IP.String()) + alreadyDialing := r.Switch.IsDialing(try) + alreadyConnected := r.Switch.Peers().Has(try.IP.String()) if alreadySelected || alreadyDialing || alreadyConnected { /* log.Info("Cannot dial address", "addr", try, @@ -198,20 +194,20 @@ func (pexR *PEXReactor) ensurePeers() { // Dial picked addresses for _, item := range toDial.Values() { go func(picked *NetAddress) { - _, err := pexR.Switch.DialPeerWithAddress(picked, false) + _, err := r.Switch.DialPeerWithAddress(picked, false) if err != nil { - pexR.book.MarkAttempt(picked) + r.book.MarkAttempt(picked) } }(item.(*NetAddress)) } // If we need more addresses, pick a random peer and ask for more. - if pexR.book.NeedMoreAddrs() { - if peers := pexR.Switch.Peers().List(); len(peers) > 0 { + if r.book.NeedMoreAddrs() { + if peers := r.Switch.Peers().List(); len(peers) > 0 { i := rand.Int() % len(peers) peer := peers[i] log.Info("No addresses to dial. Sending pexRequest to random peer", "peer", peer) - pexR.RequestPEX(peer) + r.RequestPEX(peer) } } } From 3af7c677576f07e5610686e5e6a4a38e54448d6c Mon Sep 17 00:00:00 2001 From: Anton Kalyaev Date: Wed, 11 Jan 2017 17:17:09 +0400 Subject: [PATCH 147/309] add Dockerfile --- Dockerfile | 13 +++++++++++++ 1 file changed, 13 insertions(+) create mode 100644 Dockerfile diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 000000000..3716185f2 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,13 @@ +FROM golang:latest + +RUN curl https://glide.sh/get | sh + +RUN mkdir -p /go/src/github.com/tendermint/go-p2p +WORKDIR /go/src/github.com/tendermint/go-p2p + +COPY glide.yaml /go/src/github.com/tendermint/go-p2p/ +COPY glide.lock /go/src/github.com/tendermint/go-p2p/ + +RUN glide install + +COPY . /go/src/github.com/tendermint/go-p2p From 37d5a2cf3ed9f1562bbab946e960bf54eb41198d Mon Sep 17 00:00:00 2001 From: Anton Kalyaev Date: Wed, 11 Jan 2017 19:23:31 +0400 Subject: [PATCH 148/309] implement RemovePeer for PEXReactor --- pex_reactor.go | 7 +++++-- pex_reactor_tests.go | 50 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 2 deletions(-) create mode 100644 pex_reactor_tests.go diff --git a/pex_reactor.go b/pex_reactor.go index 01d0cbd18..8d49de992 100644 --- a/pex_reactor.go +++ b/pex_reactor.go @@ -73,13 +73,16 @@ func (r *PEXReactor) AddPeer(p *Peer) { r.RequestPEX(p) } } else { // For inbound connections, the peer is its own source - r.book.AddAddress(netAddr, netAddr) + addr := NewNetAddressString(p.ListenAddr) + r.book.AddAddress(addr, addr) } } // RemovePeer implements Reactor func (r *PEXReactor) RemovePeer(p *Peer, reason interface{}) { - // TODO + addr := NewNetAddressString(p.ListenAddr) + // addr will be ejected from the book + r.book.MarkBad(addr) } // Receive implements Reactor by handling incoming PEX messages. diff --git a/pex_reactor_tests.go b/pex_reactor_tests.go new file mode 100644 index 000000000..5825495f7 --- /dev/null +++ b/pex_reactor_tests.go @@ -0,0 +1,50 @@ +package p2p + +import ( + "math/rand" + "testing" + + "github.com/stretchr/testify/assert" + . "github.com/tendermint/go-common" +) + +func TestBasic(t *testing.T) { + book := NewAddrBook(createTempFileName("addrbook"), true) + r := NewPEXReactor(book) + + assert.NotNil(t, r) + assert.NotEmpty(t, r.GetChannels()) +} + +func TestAddRemovePeer(t *testing.T) { + book := NewAddrBook(createTempFileName("addrbook"), true) + r := NewPEXReactor(book) + + size := book.Size() + peer := createRandomPeer(false) + + r.AddPeer(peer) + assert.Equal(t, size+1, book.Size()) + + r.RemovePeer(peer, "peer not available") + assert.Equal(t, size, book.Size()) + + outboundPeer := createRandomPeer(true) + + r.AddPeer(outboundPeer) + assert.Equal(t, size, book.Size(), "size must not change") + + r.RemovePeer(outboundPeer, "peer not available") + assert.Equal(t, size, book.Size(), "size must not change") +} + +func createRandomPeer(outbound bool) *Peer { + return &Peer{ + Key: RandStr(12), + NodeInfo: &NodeInfo{ + RemoteAddr: Fmt("%v.%v.%v.%v:46656", rand.Int()%256, rand.Int()%256, rand.Int()%256, rand.Int()%256), + ListenAddr: Fmt("%v.%v.%v.%v:46656", rand.Int()%256, rand.Int()%256, rand.Int()%256, rand.Int()%256), + }, + outbound: outbound, + } +} From 0109f1e5245c0fc0f9121fde1d6b4aa8ccd4b079 Mon Sep 17 00:00:00 2001 From: Anton Kalyaev Date: Thu, 12 Jan 2017 00:17:15 +0400 Subject: [PATCH 149/309] test ensurePeers goroutine --- pex_reactor.go | 22 ++++++---- pex_reactor_test.go | 97 ++++++++++++++++++++++++++++++++++++++++++++ pex_reactor_tests.go | 50 ----------------------- switch.go | 10 +++-- 4 files changed, 118 insertions(+), 61 deletions(-) create mode 100644 pex_reactor_test.go delete mode 100644 pex_reactor_tests.go diff --git a/pex_reactor.go b/pex_reactor.go index 8d49de992..56a1e3233 100644 --- a/pex_reactor.go +++ b/pex_reactor.go @@ -13,7 +13,7 @@ import ( const ( PexChannel = byte(0x00) - ensurePeersPeriodSeconds = 30 + defaultEnsurePeersPeriod = 30 * time.Second minNumOutboundPeers = 10 maxPexMessageSize = 1048576 // 1MB ) @@ -23,13 +23,15 @@ const ( type PEXReactor struct { BaseReactor - sw *Switch - book *AddrBook + sw *Switch + book *AddrBook + ensurePeersPeriod time.Duration } func NewPEXReactor(b *AddrBook) *PEXReactor { r := &PEXReactor{ - book: b, + book: b, + ensurePeersPeriod: defaultEnsurePeersPeriod, } r.BaseReactor = *NewBaseReactor(log, "PEXReactor", r) return r @@ -125,16 +127,22 @@ func (r *PEXReactor) SendAddrs(p *Peer, addrs []*NetAddress) { p.Send(PexChannel, struct{ PexMessage }{&pexAddrsMessage{Addrs: addrs}}) } +// SetEnsurePeersPeriod sets period to ensure peers connected. +func (r *PEXReactor) SetEnsurePeersPeriod(d time.Duration) { + r.ensurePeersPeriod = d +} + // Ensures that sufficient peers are connected. (continuous) func (r *PEXReactor) ensurePeersRoutine() { // Randomize when routine starts - time.Sleep(time.Duration(rand.Int63n(500*ensurePeersPeriodSeconds)) * time.Millisecond) + ensurePeersPeriodMs := r.ensurePeersPeriod.Nanoseconds() / 1e6 + time.Sleep(time.Duration(rand.Int63n(ensurePeersPeriodMs)) * time.Millisecond) // fire once immediately. r.ensurePeers() // fire periodically - timer := NewRepeatTimer("pex", ensurePeersPeriodSeconds*time.Second) + timer := NewRepeatTimer("pex", r.ensurePeersPeriod) FOR_LOOP: for { select { @@ -149,7 +157,7 @@ FOR_LOOP: timer.Stop() } -// Ensures that sufficient peers are connected. (once) +// ensurePeers ensures that sufficient peers are connected. (once) func (r *PEXReactor) ensurePeers() { numOutPeers, _, numDialing := r.Switch.NumPeers() numToDial := minNumOutboundPeers - (numOutPeers + numDialing) diff --git a/pex_reactor_test.go b/pex_reactor_test.go new file mode 100644 index 000000000..3674d3f31 --- /dev/null +++ b/pex_reactor_test.go @@ -0,0 +1,97 @@ +package p2p + +import ( + "math/rand" + "testing" + "time" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + . "github.com/tendermint/go-common" +) + +func TestPEXReactorBasic(t *testing.T) { + book := NewAddrBook(createTempFileName("addrbook"), true) + r := NewPEXReactor(book) + + assert.NotNil(t, r) + assert.NotEmpty(t, r.GetChannels()) +} + +func TestPEXReactorAddRemovePeer(t *testing.T) { + book := NewAddrBook(createTempFileName("addrbook"), true) + r := NewPEXReactor(book) + + size := book.Size() + peer := createRandomPeer(false) + + r.AddPeer(peer) + assert.Equal(t, size+1, book.Size()) + + r.RemovePeer(peer, "peer not available") + assert.Equal(t, size, book.Size()) + + outboundPeer := createRandomPeer(true) + + r.AddPeer(outboundPeer) + assert.Equal(t, size, book.Size(), "size must not change") + + r.RemovePeer(outboundPeer, "peer not available") + assert.Equal(t, size, book.Size(), "size must not change") +} + +func TestPEXReactorRunning(t *testing.T) { + N := 3 + switches := make([]*Switch, N) + + book := NewAddrBook(createTempFileName("addrbook"), false) + + // create switches + for i := 0; i < N; i++ { + switches[i] = makeSwitch(i, "172.17.0.2", "123.123.123", func(i int, sw *Switch) *Switch { + r := NewPEXReactor(book) + r.SetEnsurePeersPeriod(250 * time.Millisecond) + sw.AddReactor("pex", r) + return sw + }) + } + + // fill the address book and add listeners + for _, s := range switches { + addr := NewNetAddressString(s.NodeInfo().ListenAddr) + book.AddAddress(addr, addr) + s.AddListener(NewDefaultListener("tcp", s.NodeInfo().ListenAddr, true)) + } + + // start switches + for _, s := range switches { + _, err := s.Start() // start switch and reactors + require.Nil(t, err) + } + + time.Sleep(1 * time.Second) + + // check peers are connected after some time + for _, s := range switches { + outbound, inbound, _ := s.NumPeers() + if outbound+inbound == 0 { + t.Errorf("%v expected to be connected to at least one peer", s.NodeInfo().ListenAddr) + } + } + + // stop them + for _, s := range switches { + s.Stop() + } +} + +func createRandomPeer(outbound bool) *Peer { + return &Peer{ + Key: RandStr(12), + NodeInfo: &NodeInfo{ + RemoteAddr: Fmt("%v.%v.%v.%v:46656", rand.Int()%256, rand.Int()%256, rand.Int()%256, rand.Int()%256), + ListenAddr: Fmt("%v.%v.%v.%v:46656", rand.Int()%256, rand.Int()%256, rand.Int()%256, rand.Int()%256), + }, + outbound: outbound, + } +} diff --git a/pex_reactor_tests.go b/pex_reactor_tests.go deleted file mode 100644 index 5825495f7..000000000 --- a/pex_reactor_tests.go +++ /dev/null @@ -1,50 +0,0 @@ -package p2p - -import ( - "math/rand" - "testing" - - "github.com/stretchr/testify/assert" - . "github.com/tendermint/go-common" -) - -func TestBasic(t *testing.T) { - book := NewAddrBook(createTempFileName("addrbook"), true) - r := NewPEXReactor(book) - - assert.NotNil(t, r) - assert.NotEmpty(t, r.GetChannels()) -} - -func TestAddRemovePeer(t *testing.T) { - book := NewAddrBook(createTempFileName("addrbook"), true) - r := NewPEXReactor(book) - - size := book.Size() - peer := createRandomPeer(false) - - r.AddPeer(peer) - assert.Equal(t, size+1, book.Size()) - - r.RemovePeer(peer, "peer not available") - assert.Equal(t, size, book.Size()) - - outboundPeer := createRandomPeer(true) - - r.AddPeer(outboundPeer) - assert.Equal(t, size, book.Size(), "size must not change") - - r.RemovePeer(outboundPeer, "peer not available") - assert.Equal(t, size, book.Size(), "size must not change") -} - -func createRandomPeer(outbound bool) *Peer { - return &Peer{ - Key: RandStr(12), - NodeInfo: &NodeInfo{ - RemoteAddr: Fmt("%v.%v.%v.%v:46656", rand.Int()%256, rand.Int()%256, rand.Int()%256, rand.Int()%256), - ListenAddr: Fmt("%v.%v.%v.%v:46656", rand.Int()%256, rand.Int()%256, rand.Int()%256, rand.Int()%256), - }, - outbound: outbound, - } -} diff --git a/switch.go b/switch.go index 8ceb1ab70..6835e0a4b 100644 --- a/switch.go +++ b/switch.go @@ -531,10 +531,12 @@ func makeSwitch(i int, network, version string, initSwitch func(int, *Switch) *S // TODO: let the config be passed in? s := initSwitch(i, NewSwitch(cfg.NewMapConfig(nil))) s.SetNodeInfo(&NodeInfo{ - PubKey: privKey.PubKey().(crypto.PubKeyEd25519), - Moniker: Fmt("switch%d", i), - Network: network, - Version: version, + PubKey: privKey.PubKey().(crypto.PubKeyEd25519), + Moniker: Fmt("switch%d", i), + Network: network, + Version: version, + RemoteAddr: Fmt("%v:%v", network, rand.Intn(64512)+1023), + ListenAddr: Fmt("%v:%v", network, rand.Intn(64512)+1023), }) s.SetNodePrivKey(privKey) return s From 1a59b6a3b4e318fe059cfcafa1b7b5f6a029e090 Mon Sep 17 00:00:00 2001 From: Anton Kalyaev Date: Thu, 12 Jan 2017 13:26:29 +0400 Subject: [PATCH 150/309] replace repeate timer with simple ticker no need for repeate timer here (no need for goroutine safety) --- pex_reactor.go | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/pex_reactor.go b/pex_reactor.go index 56a1e3233..5cea1cb3c 100644 --- a/pex_reactor.go +++ b/pex_reactor.go @@ -142,19 +142,18 @@ func (r *PEXReactor) ensurePeersRoutine() { r.ensurePeers() // fire periodically - timer := NewRepeatTimer("pex", r.ensurePeersPeriod) + ticker := time.NewTicker(r.ensurePeersPeriod) FOR_LOOP: for { select { - case <-timer.Ch: + case <-ticker.C: r.ensurePeers() case <-r.Quit: break FOR_LOOP } } - // Cleanup - timer.Stop() + ticker.Stop() } // ensurePeers ensures that sufficient peers are connected. (once) From 47df1fb7d4646a5a69399839317d08d2bf18f086 Mon Sep 17 00:00:00 2001 From: Anton Kalyaev Date: Thu, 12 Jan 2017 15:16:51 +0400 Subject: [PATCH 151/309] test PEXReactor#Receive --- pex_reactor_test.go | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/pex_reactor_test.go b/pex_reactor_test.go index 3674d3f31..762d96810 100644 --- a/pex_reactor_test.go +++ b/pex_reactor_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" . "github.com/tendermint/go-common" + wire "github.com/tendermint/go-wire" ) func TestPEXReactorBasic(t *testing.T) { @@ -85,13 +86,30 @@ func TestPEXReactorRunning(t *testing.T) { } } +func TestPEXReactorReceive(t *testing.T) { + book := NewAddrBook(createTempFileName("addrbook"), true) + r := NewPEXReactor(book) + + peer := createRandomPeer(false) + + size := book.Size() + addrs := []*NetAddress{NewNetAddressString(peer.ListenAddr)} + msg := wire.BinaryBytes(struct{ PexMessage }{&pexAddrsMessage{Addrs: addrs}}) + r.Receive(PexChannel, peer, msg) + assert.Equal(t, size+1, book.Size()) + + msg = wire.BinaryBytes(struct{ PexMessage }{&pexRequestMessage{}}) + r.Receive(PexChannel, peer, msg) +} + func createRandomPeer(outbound bool) *Peer { + addr := Fmt("%v.%v.%v.%v:46656", rand.Int()%256, rand.Int()%256, rand.Int()%256, rand.Int()%256) return &Peer{ Key: RandStr(12), NodeInfo: &NodeInfo{ - RemoteAddr: Fmt("%v.%v.%v.%v:46656", rand.Int()%256, rand.Int()%256, rand.Int()%256, rand.Int()%256), - ListenAddr: Fmt("%v.%v.%v.%v:46656", rand.Int()%256, rand.Int()%256, rand.Int()%256, rand.Int()%256), + ListenAddr: addr, }, outbound: outbound, + mconn: &MConnection{RemoteAddress: NewNetAddressString(addr)}, } } From 873d34157d51d09116b0c0a99557367aafbd1897 Mon Sep 17 00:00:00 2001 From: Anton Kalyaev Date: Thu, 12 Jan 2017 17:56:40 +0400 Subject: [PATCH 152/309] prevent abuse from peers --- pex_reactor.go | 59 ++++++++++++++++++++++++++++++++++++++------- pex_reactor_test.go | 15 ++++++++++++ 2 files changed, 65 insertions(+), 9 deletions(-) diff --git a/pex_reactor.go b/pex_reactor.go index 5cea1cb3c..3e03138c1 100644 --- a/pex_reactor.go +++ b/pex_reactor.go @@ -12,10 +12,15 @@ import ( ) const ( - PexChannel = byte(0x00) + PexChannel = byte(0x00) + // period to ensure peers connected defaultEnsurePeersPeriod = 30 * time.Second minNumOutboundPeers = 10 maxPexMessageSize = 1048576 // 1MB + + // maximum messages one peer can send to us during `msgCountByPeerFlushInterval` + defaultMaxMsgCountByPeer = 1000 + msgCountByPeerFlushInterval = 1 * time.Hour ) // PEXReactor handles PEX (peer exchange) and ensures that an @@ -26,12 +31,18 @@ type PEXReactor struct { sw *Switch book *AddrBook ensurePeersPeriod time.Duration + + // tracks message count by peer, so we can prevent abuse + msgCountByPeer map[string]uint16 + maxMsgCountByPeer uint16 } func NewPEXReactor(b *AddrBook) *PEXReactor { r := &PEXReactor{ book: b, ensurePeersPeriod: defaultEnsurePeersPeriod, + msgCountByPeer: make(map[string]uint16), + maxMsgCountByPeer: defaultMaxMsgCountByPeer, } r.BaseReactor = *NewBaseReactor(log, "PEXReactor", r) return r @@ -41,6 +52,7 @@ func (r *PEXReactor) OnStart() error { r.BaseReactor.OnStart() r.book.Start() go r.ensurePeersRoutine() + go r.flushMsgCountByPeer() return nil } @@ -89,24 +101,29 @@ func (r *PEXReactor) RemovePeer(p *Peer, reason interface{}) { // Receive implements Reactor by handling incoming PEX messages. func (r *PEXReactor) Receive(chID byte, src *Peer, msgBytes []byte) { + srcAddr := src.Connection().RemoteAddress + srcAddrStr := srcAddr.String() + r.msgCountByPeer[srcAddrStr]++ + if r.ReachedMaxMsgCountForPeer(srcAddrStr) { + log.Warn("Maximum number of messages reached for peer", "peer", srcAddrStr) + // TODO remove src from peers? + return + } + _, msg, err := DecodeMessage(msgBytes) if err != nil { log.Warn("Error decoding message", "error", err) return } - log.Notice("Received message", "msg", msg) switch msg := msg.(type) { case *pexRequestMessage: // src requested some peers. - // TODO: prevent abuse. r.SendAddrs(src, r.book.GetSelection()) case *pexAddrsMessage: // We received some peer addresses from src. - // TODO: prevent abuse. // (We don't want to get spammed with bad peers) - srcAddr := src.Connection().RemoteAddress for _, addr := range msg.Addrs { if addr != nil { r.book.AddAddress(addr, srcAddr) @@ -132,6 +149,17 @@ func (r *PEXReactor) SetEnsurePeersPeriod(d time.Duration) { r.ensurePeersPeriod = d } +// SetMaxMsgCountByPeer sets maximum messages one peer can send to us during 'msgCountByPeerFlushInterval'. +func (r *PEXReactor) SetMaxMsgCountByPeer(v uint16) { + r.maxMsgCountByPeer = v +} + +// ReachedMaxMsgCountForPeer returns true if we received too many +// messages from peer with address `addr`. +func (r *PEXReactor) ReachedMaxMsgCountForPeer(addr string) bool { + return r.msgCountByPeer[addr] >= r.maxMsgCountByPeer +} + // Ensures that sufficient peers are connected. (continuous) func (r *PEXReactor) ensurePeersRoutine() { // Randomize when routine starts @@ -143,17 +171,16 @@ func (r *PEXReactor) ensurePeersRoutine() { // fire periodically ticker := time.NewTicker(r.ensurePeersPeriod) -FOR_LOOP: + for { select { case <-ticker.C: r.ensurePeers() case <-r.Quit: - break FOR_LOOP + ticker.Stop() + return } } - - ticker.Stop() } // ensurePeers ensures that sufficient peers are connected. (once) @@ -222,6 +249,20 @@ func (r *PEXReactor) ensurePeers() { } } +func (r *PEXReactor) flushMsgCountByPeer() { + ticker := time.NewTicker(msgCountByPeerFlushInterval) + + for { + select { + case <-ticker.C: + r.msgCountByPeer = make(map[string]uint16) + case <-r.Quit: + ticker.Stop() + return + } + } +} + //----------------------------------------------------------------------------- // Messages diff --git a/pex_reactor_test.go b/pex_reactor_test.go index 762d96810..7c3a2dae4 100644 --- a/pex_reactor_test.go +++ b/pex_reactor_test.go @@ -102,6 +102,21 @@ func TestPEXReactorReceive(t *testing.T) { r.Receive(PexChannel, peer, msg) } +func TestPEXReactorAbuseFromPeer(t *testing.T) { + book := NewAddrBook(createTempFileName("addrbook"), true) + r := NewPEXReactor(book) + r.SetMaxMsgCountByPeer(5) + + peer := createRandomPeer(false) + + msg := wire.BinaryBytes(struct{ PexMessage }{&pexRequestMessage{}}) + for i := 0; i < 10; i++ { + r.Receive(PexChannel, peer, msg) + } + + assert.True(t, r.ReachedMaxMsgCountForPeer(peer.ListenAddr)) +} + func createRandomPeer(outbound bool) *Peer { addr := Fmt("%v.%v.%v.%v:46656", rand.Int()%256, rand.Int()%256, rand.Int()%256, rand.Int()%256) return &Peer{ From 07e7b98c7034befb350c878bf68e6175d6a5658a Mon Sep 17 00:00:00 2001 From: Anton Kalyaev Date: Thu, 12 Jan 2017 22:28:40 +0400 Subject: [PATCH 153/309] improve ensurePeers routine optimizations: - if we move peer to the old bucket as soon as connected and pick only from new group, we can skip alreadyConnected check --- pex_reactor.go | 32 ++++++++++++++++---------------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/pex_reactor.go b/pex_reactor.go index 3e03138c1..a16823e33 100644 --- a/pex_reactor.go +++ b/pex_reactor.go @@ -191,30 +191,27 @@ func (r *PEXReactor) ensurePeers() { if numToDial <= 0 { return } - toDial := NewCMap() + + toDial := make(map[string]*NetAddress) // Try to pick numToDial addresses to dial. - // TODO: improve logic. for i := 0; i < numToDial; i++ { - newBias := MinInt(numOutPeers, 8)*10 + 10 var picked *NetAddress // Try to fetch a new peer 3 times. // This caps the maximum number of tries to 3 * numToDial. for j := 0; j < 3; j++ { - try := r.book.PickAddress(newBias) + // NOTE always picking from the new group because old one stores already + // connected peers. + try := r.book.PickAddress(100) if try == nil { break } - alreadySelected := toDial.Has(try.IP.String()) + _, alreadySelected := toDial[try.IP.String()] alreadyDialing := r.Switch.IsDialing(try) - alreadyConnected := r.Switch.Peers().Has(try.IP.String()) - if alreadySelected || alreadyDialing || alreadyConnected { - /* - log.Info("Cannot dial address", "addr", try, - "alreadySelected", alreadySelected, - "alreadyDialing", alreadyDialing, - "alreadyConnected", alreadyConnected) - */ + if alreadySelected || alreadyDialing { + // log.Info("Cannot dial address", "addr", try, + // "alreadySelected", alreadySelected, + // "alreadyDialing", alreadyDialing) continue } else { log.Info("Will dial address", "addr", try) @@ -225,17 +222,20 @@ func (r *PEXReactor) ensurePeers() { if picked == nil { continue } - toDial.Set(picked.IP.String(), picked) + toDial[picked.IP.String()] = picked } // Dial picked addresses - for _, item := range toDial.Values() { + for _, item := range toDial { go func(picked *NetAddress) { _, err := r.Switch.DialPeerWithAddress(picked, false) if err != nil { r.book.MarkAttempt(picked) + } else { + // move address to the old group + r.book.MarkGood(picked) } - }(item.(*NetAddress)) + }(item) } // If we need more addresses, pick a random peer and ask for more. From 5eeaffd38ee08ab2b765583df2682225b7f9fc0d Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Mon, 16 Jan 2017 20:31:50 +0400 Subject: [PATCH 154/309] do not create file, just temp dir --- pex_reactor_test.go | 39 ++++++++++++++++++++++++++++++--------- 1 file changed, 30 insertions(+), 9 deletions(-) diff --git a/pex_reactor_test.go b/pex_reactor_test.go index 7c3a2dae4..67d123bec 100644 --- a/pex_reactor_test.go +++ b/pex_reactor_test.go @@ -1,18 +1,24 @@ package p2p import ( + "io/ioutil" "math/rand" + "os" "testing" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - . "github.com/tendermint/go-common" + cmn "github.com/tendermint/go-common" wire "github.com/tendermint/go-wire" ) func TestPEXReactorBasic(t *testing.T) { - book := NewAddrBook(createTempFileName("addrbook"), true) + dir, err := ioutil.TempDir("", "pex_reactor") + require.Nil(t, err) + defer os.RemoveAll(dir) + book := NewAddrBook(dir+"addrbook.json", true) + r := NewPEXReactor(book) assert.NotNil(t, r) @@ -20,7 +26,11 @@ func TestPEXReactorBasic(t *testing.T) { } func TestPEXReactorAddRemovePeer(t *testing.T) { - book := NewAddrBook(createTempFileName("addrbook"), true) + dir, err := ioutil.TempDir("", "pex_reactor") + require.Nil(t, err) + defer os.RemoveAll(dir) + book := NewAddrBook(dir+"addrbook.json", true) + r := NewPEXReactor(book) size := book.Size() @@ -45,11 +55,14 @@ func TestPEXReactorRunning(t *testing.T) { N := 3 switches := make([]*Switch, N) - book := NewAddrBook(createTempFileName("addrbook"), false) + dir, err := ioutil.TempDir("", "pex_reactor") + require.Nil(t, err) + defer os.RemoveAll(dir) + book := NewAddrBook(dir+"addrbook.json", false) // create switches for i := 0; i < N; i++ { - switches[i] = makeSwitch(i, "172.17.0.2", "123.123.123", func(i int, sw *Switch) *Switch { + switches[i] = makeSwitch(i, "127.0.0.1", "123.123.123", func(i int, sw *Switch) *Switch { r := NewPEXReactor(book) r.SetEnsurePeersPeriod(250 * time.Millisecond) sw.AddReactor("pex", r) @@ -87,7 +100,11 @@ func TestPEXReactorRunning(t *testing.T) { } func TestPEXReactorReceive(t *testing.T) { - book := NewAddrBook(createTempFileName("addrbook"), true) + dir, err := ioutil.TempDir("", "pex_reactor") + require.Nil(t, err) + defer os.RemoveAll(dir) + book := NewAddrBook(dir+"addrbook.json", true) + r := NewPEXReactor(book) peer := createRandomPeer(false) @@ -103,7 +120,11 @@ func TestPEXReactorReceive(t *testing.T) { } func TestPEXReactorAbuseFromPeer(t *testing.T) { - book := NewAddrBook(createTempFileName("addrbook"), true) + dir, err := ioutil.TempDir("", "pex_reactor") + require.Nil(t, err) + defer os.RemoveAll(dir) + book := NewAddrBook(dir+"addrbook.json", true) + r := NewPEXReactor(book) r.SetMaxMsgCountByPeer(5) @@ -118,9 +139,9 @@ func TestPEXReactorAbuseFromPeer(t *testing.T) { } func createRandomPeer(outbound bool) *Peer { - addr := Fmt("%v.%v.%v.%v:46656", rand.Int()%256, rand.Int()%256, rand.Int()%256, rand.Int()%256) + addr := cmn.Fmt("%v.%v.%v.%v:46656", rand.Int()%256, rand.Int()%256, rand.Int()%256, rand.Int()%256) return &Peer{ - Key: RandStr(12), + Key: cmn.RandStr(12), NodeInfo: &NodeInfo{ ListenAddr: addr, }, From 590efc10404e3bf7795e382012d71b0005f44693 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Mon, 16 Jan 2017 23:36:10 +0400 Subject: [PATCH 155/309] call saveToFile OnStop This is better than waiting because while we wait, anything could happen (crash, timeout of the code who's using addrbook, ...). If we save immediately, we have much greater chances of success. --- addrbook.go | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/addrbook.go b/addrbook.go index ace0dba4a..7a65cb4be 100644 --- a/addrbook.go +++ b/addrbook.go @@ -15,7 +15,6 @@ import ( "time" . "github.com/tendermint/go-common" - "github.com/tendermint/go-crypto" ) const ( @@ -86,7 +85,6 @@ type AddrBook struct { addrLookup map[string]*knownAddress // new & old addrNew []map[string]*knownAddress addrOld []map[string]*knownAddress - wg sync.WaitGroup nOld int nNew int } @@ -128,7 +126,6 @@ func (a *AddrBook) init() { func (a *AddrBook) OnStart() error { a.BaseService.OnStart() a.loadFromFile(a.filePath) - a.wg.Add(1) go a.saveRoutine() return nil } @@ -139,6 +136,7 @@ func (a *AddrBook) OnStop() { func (a *AddrBook) Wait() { a.wg.Wait() + a.saveToFile(a.filePath) } func (a *AddrBook) AddOurAddress(addr *NetAddress) { @@ -309,6 +307,8 @@ type addrBookJSON struct { } func (a *AddrBook) saveToFile(filePath string) { + log.Info("Saving AddrBook to file", "size", a.Size()) + // Compile Addrs addrs := []*knownAddress{} for _, ka := range a.addrLookup { @@ -386,7 +386,6 @@ out: for { select { case <-dumpAddressTicker.C: - log.Info("Saving AddrBook to file", "size", a.Size()) a.saveToFile(a.filePath) case <-a.Quit: break out @@ -394,7 +393,6 @@ out: } dumpAddressTicker.Stop() a.saveToFile(a.filePath) - a.wg.Done() log.Notice("Address handler done") } From 52d9cf080e08fd539a8aebbb82aacaa9a5459551 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Mon, 16 Jan 2017 23:57:07 +0400 Subject: [PATCH 156/309] make GoLint happy --- pex_reactor.go | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/pex_reactor.go b/pex_reactor.go index a16823e33..89599f4b4 100644 --- a/pex_reactor.go +++ b/pex_reactor.go @@ -7,12 +7,13 @@ import ( "reflect" "time" - . "github.com/tendermint/go-common" wire "github.com/tendermint/go-wire" ) const ( + // PexChannel is a channel for PEX messages PexChannel = byte(0x00) + // period to ensure peers connected defaultEnsurePeersPeriod = 30 * time.Second minNumOutboundPeers = 10 @@ -25,6 +26,8 @@ const ( // PEXReactor handles PEX (peer exchange) and ensures that an // adequate number of peers are connected to the switch. +// +// It uses `AddrBook` (address book) to store `NetAddress`es of the peers. type PEXReactor struct { BaseReactor @@ -37,6 +40,7 @@ type PEXReactor struct { maxMsgCountByPeer uint16 } +// NewPEXReactor creates new PEX reactor. func NewPEXReactor(b *AddrBook) *PEXReactor { r := &PEXReactor{ book: b, @@ -48,6 +52,7 @@ func NewPEXReactor(b *AddrBook) *PEXReactor { return r } +// OnStart implements BaseService func (r *PEXReactor) OnStart() error { r.BaseReactor.OnStart() r.book.Start() @@ -56,6 +61,7 @@ func (r *PEXReactor) OnStart() error { return nil } +// OnStop implements BaseService func (r *PEXReactor) OnStop() { r.BaseReactor.OnStop() r.book.Stop() @@ -92,7 +98,7 @@ func (r *PEXReactor) AddPeer(p *Peer) { } } -// RemovePeer implements Reactor +// RemovePeer implements Reactor by removing peer from the address book. func (r *PEXReactor) RemovePeer(p *Peer, reason interface{}) { addr := NewNetAddressString(p.ListenAddr) // addr will be ejected from the book @@ -130,7 +136,7 @@ func (r *PEXReactor) Receive(chID byte, src *Peer, msgBytes []byte) { } } default: - log.Warn(Fmt("Unknown message type %v", reflect.TypeOf(msg))) + log.Warn(fmt.Sprintf("Unknown message type %v", reflect.TypeOf(msg))) } } @@ -271,6 +277,8 @@ const ( msgTypeAddrs = byte(0x02) ) +// PexMessage is a primary type for PEX messages. Underneath, it could contain +// either pexRequestMessage, or pexAddrsMessage messages. type PexMessage interface{} var _ = wire.RegisterInterface( @@ -279,6 +287,7 @@ var _ = wire.RegisterInterface( wire.ConcreteType{&pexAddrsMessage{}, msgTypeAddrs}, ) +// DecodeMessage implements interface registered above. func DecodeMessage(bz []byte) (msgType byte, msg PexMessage, err error) { msgType = bz[0] n := new(int) From 324293f4cbbc108c66fa09bc24ac3e863f2b7671 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Tue, 17 Jan 2017 22:30:03 +0400 Subject: [PATCH 157/309] note on preventing abuse [ci skip] --- pex_reactor.go | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/pex_reactor.go b/pex_reactor.go index 89599f4b4..3a3d66714 100644 --- a/pex_reactor.go +++ b/pex_reactor.go @@ -28,6 +28,18 @@ const ( // adequate number of peers are connected to the switch. // // It uses `AddrBook` (address book) to store `NetAddress`es of the peers. +// +// ## Preventing abuse +// +// For now, it just limits the number of messages from one peer to +// `defaultMaxMsgCountByPeer` messages per `msgCountByPeerFlushInterval` (1000 +// msg/hour). +// +// NOTE [2017-01-17]: +// Limiting is fine for now. Maybe down the road we want to keep track of the +// quality of peer messages so if peerA keeps telling us about peers we can't +// connect to then maybe we should care less about peerA. But I don't think +// that kind of complexity is priority right now. type PEXReactor struct { BaseReactor From cf18bf296628e6b32f6562c40671e0c331102b0e Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Fri, 20 Jan 2017 15:27:33 +0400 Subject: [PATCH 158/309] add public RemoveAddress API after discussion with @ebuchman (https://github.com/tendermint/go-p2p/pull/10#discussion_r96471729) --- addrbook.go | 10 ++++++++-- addrbook_test.go | 19 +++++++++++++++++++ pex_reactor.go | 8 ++++++-- 3 files changed, 33 insertions(+), 4 deletions(-) diff --git a/addrbook.go b/addrbook.go index 7a65cb4be..9dbbc2bf5 100644 --- a/addrbook.go +++ b/addrbook.go @@ -252,15 +252,21 @@ func (a *AddrBook) MarkAttempt(addr *NetAddress) { ka.markAttempt() } +// MarkBad currently just ejects the address. In the future, consider +// blacklisting. func (a *AddrBook) MarkBad(addr *NetAddress) { + a.RemoveAddress(addr) +} + +// RemoveAddress removes the address from the book. +func (a *AddrBook) RemoveAddress(addr *NetAddress) { a.mtx.Lock() defer a.mtx.Unlock() ka := a.addrLookup[addr.String()] if ka == nil { return } - // We currently just eject the address. - // In the future, consider blacklisting. + log.Info("Remove address from book", "addr", addr) a.removeFromAllBuckets(ka) } diff --git a/addrbook_test.go b/addrbook_test.go index 7e8cb8d76..0f5ced5cf 100644 --- a/addrbook_test.go +++ b/addrbook_test.go @@ -9,6 +9,9 @@ import ( "github.com/stretchr/testify/assert" ) + "github.com/stretchr/testify/assert" +) + func createTempFileName(prefix string) string { f, err := ioutil.TempFile("", prefix) if err != nil { @@ -148,3 +151,19 @@ func randIPv4Address(t *testing.T) *NetAddress { } } } + +func TestAddrBookRemoveAddress(t *testing.T) { + fname := createTempFileName("addrbook_test") + book := NewAddrBook(fname, true) + + addr := randIPv4Address() + book.AddAddress(addr, addr) + assert.Equal(t, 1, book.Size()) + + book.RemoveAddress(addr) + assert.Equal(t, 0, book.Size()) + + nonExistingAddr := randIPv4Address() + book.RemoveAddress(nonExistingAddr) + assert.Equal(t, 0, book.Size()) +} diff --git a/pex_reactor.go b/pex_reactor.go index 3a3d66714..79a9200ff 100644 --- a/pex_reactor.go +++ b/pex_reactor.go @@ -111,10 +111,14 @@ func (r *PEXReactor) AddPeer(p *Peer) { } // RemovePeer implements Reactor by removing peer from the address book. +// +// The peer will be proposed to us by other peers (PexAddrsMessage) or himself +// and we will add him again upon successful connection. Note that other peers +// will remove him too. The peer will need to send first requests to others by +// himself (he will have an addrbook or the seeds). func (r *PEXReactor) RemovePeer(p *Peer, reason interface{}) { addr := NewNetAddressString(p.ListenAddr) - // addr will be ejected from the book - r.book.MarkBad(addr) + r.book.RemoveAddress(addr) } // Receive implements Reactor by handling incoming PEX messages. From 0277e52bd5f27e4f2148353be6d674871a6ba41e Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Fri, 14 Apr 2017 23:59:22 +0400 Subject: [PATCH 159/309] fix merge --- addrbook.go | 2 +- addrbook_test.go | 7 ++----- pex_reactor.go | 21 ++++++++++++--------- pex_reactor_test.go | 8 +++++--- 4 files changed, 20 insertions(+), 18 deletions(-) diff --git a/addrbook.go b/addrbook.go index 9dbbc2bf5..c33b97aa8 100644 --- a/addrbook.go +++ b/addrbook.go @@ -15,6 +15,7 @@ import ( "time" . "github.com/tendermint/go-common" + crypto "github.com/tendermint/go-crypto" ) const ( @@ -135,7 +136,6 @@ func (a *AddrBook) OnStop() { } func (a *AddrBook) Wait() { - a.wg.Wait() a.saveToFile(a.filePath) } diff --git a/addrbook_test.go b/addrbook_test.go index 0f5ced5cf..16aea8ef9 100644 --- a/addrbook_test.go +++ b/addrbook_test.go @@ -9,9 +9,6 @@ import ( "github.com/stretchr/testify/assert" ) - "github.com/stretchr/testify/assert" -) - func createTempFileName(prefix string) string { f, err := ioutil.TempFile("", prefix) if err != nil { @@ -156,14 +153,14 @@ func TestAddrBookRemoveAddress(t *testing.T) { fname := createTempFileName("addrbook_test") book := NewAddrBook(fname, true) - addr := randIPv4Address() + addr := randIPv4Address(t) book.AddAddress(addr, addr) assert.Equal(t, 1, book.Size()) book.RemoveAddress(addr) assert.Equal(t, 0, book.Size()) - nonExistingAddr := randIPv4Address() + nonExistingAddr := randIPv4Address(t) book.RemoveAddress(nonExistingAddr) assert.Equal(t, 0, book.Size()) } diff --git a/pex_reactor.go b/pex_reactor.go index 79a9200ff..a86bebe12 100644 --- a/pex_reactor.go +++ b/pex_reactor.go @@ -93,19 +93,17 @@ func (r *PEXReactor) GetChannels() []*ChannelDescriptor { // AddPeer implements Reactor by adding peer to the address book (if inbound) // or by requesting more addresses (if outbound). func (r *PEXReactor) AddPeer(p *Peer) { - netAddr, err := NewNetAddressString(p.ListenAddr) - if err != nil { - // this should never happen - log.Error("Error in AddPeer: invalid peer address", "addr", p.ListenAddr, "error", err) - return - } - if p.IsOutbound() { // For outbound peers, the address is already in the books if r.book.NeedMoreAddrs() { r.RequestPEX(p) } } else { // For inbound connections, the peer is its own source - addr := NewNetAddressString(p.ListenAddr) + addr, err := NewNetAddressString(p.ListenAddr) + if err != nil { + // this should never happen + log.Error("Error in AddPeer: invalid peer address", "addr", p.ListenAddr, "error", err) + return + } r.book.AddAddress(addr, addr) } } @@ -117,7 +115,12 @@ func (r *PEXReactor) AddPeer(p *Peer) { // will remove him too. The peer will need to send first requests to others by // himself (he will have an addrbook or the seeds). func (r *PEXReactor) RemovePeer(p *Peer, reason interface{}) { - addr := NewNetAddressString(p.ListenAddr) + addr, err := NewNetAddressString(p.ListenAddr) + if err != nil { + // this should never happen + log.Error("Error in AddPeer: invalid peer address", "addr", p.ListenAddr, "error", err) + return + } r.book.RemoveAddress(addr) } diff --git a/pex_reactor_test.go b/pex_reactor_test.go index 67d123bec..525efd3cb 100644 --- a/pex_reactor_test.go +++ b/pex_reactor_test.go @@ -72,7 +72,7 @@ func TestPEXReactorRunning(t *testing.T) { // fill the address book and add listeners for _, s := range switches { - addr := NewNetAddressString(s.NodeInfo().ListenAddr) + addr, _ := NewNetAddressString(s.NodeInfo().ListenAddr) book.AddAddress(addr, addr) s.AddListener(NewDefaultListener("tcp", s.NodeInfo().ListenAddr, true)) } @@ -110,7 +110,8 @@ func TestPEXReactorReceive(t *testing.T) { peer := createRandomPeer(false) size := book.Size() - addrs := []*NetAddress{NewNetAddressString(peer.ListenAddr)} + netAddr, _ := NewNetAddressString(peer.ListenAddr) + addrs := []*NetAddress{netAddr} msg := wire.BinaryBytes(struct{ PexMessage }{&pexAddrsMessage{Addrs: addrs}}) r.Receive(PexChannel, peer, msg) assert.Equal(t, size+1, book.Size()) @@ -140,12 +141,13 @@ func TestPEXReactorAbuseFromPeer(t *testing.T) { func createRandomPeer(outbound bool) *Peer { addr := cmn.Fmt("%v.%v.%v.%v:46656", rand.Int()%256, rand.Int()%256, rand.Int()%256, rand.Int()%256) + netAddr, _ := NewNetAddressString(addr) return &Peer{ Key: cmn.RandStr(12), NodeInfo: &NodeInfo{ ListenAddr: addr, }, outbound: outbound, - mconn: &MConnection{RemoteAddress: NewNetAddressString(addr)}, + mconn: &MConnection{RemoteAddress: netAddr}, } } From 4c0d1d3ad2987fe99826915dc935d4c51339aade Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Mon, 17 Apr 2017 13:03:26 +0400 Subject: [PATCH 160/309] return wg to addrbook --- addrbook.go | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/addrbook.go b/addrbook.go index c33b97aa8..5450c515f 100644 --- a/addrbook.go +++ b/addrbook.go @@ -73,7 +73,12 @@ const ( serializationVersion = 1 ) -/* AddrBook - concurrency safe peer address manager */ +const ( + bucketTypeNew = 0x01 + bucketTypeOld = 0x02 +) + +// AddrBook - concurrency safe peer address manager. type AddrBook struct { BaseService @@ -86,15 +91,12 @@ type AddrBook struct { addrLookup map[string]*knownAddress // new & old addrNew []map[string]*knownAddress addrOld []map[string]*knownAddress + wg sync.WaitGroup nOld int nNew int } -const ( - bucketTypeNew = 0x01 - bucketTypeOld = 0x02 -) - +// NewAddrBook creates a new address book. // Use Start to begin processing asynchronous address updates. func NewAddrBook(filePath string, routabilityStrict bool) *AddrBook { am := &AddrBook{ @@ -124,19 +126,22 @@ func (a *AddrBook) init() { } } +// OnStart implements Service. func (a *AddrBook) OnStart() error { a.BaseService.OnStart() a.loadFromFile(a.filePath) + a.wg.Add(1) go a.saveRoutine() return nil } -func (a *AddrBook) OnStop() { - a.BaseService.OnStop() +func (a *AddrBook) Wait() { + a.wg.Wait() } -func (a *AddrBook) Wait() { - a.saveToFile(a.filePath) +// OnStop implements Service. +func (a *AddrBook) OnStop() { + a.BaseService.OnStop() } func (a *AddrBook) AddOurAddress(addr *NetAddress) { @@ -399,6 +404,7 @@ out: } dumpAddressTicker.Stop() a.saveToFile(a.filePath) + a.wg.Done() log.Notice("Address handler done") } From 5ab8ca0868a94e776e297d47c31226d9e66cca38 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Mon, 17 Apr 2017 13:22:59 +0400 Subject: [PATCH 161/309] fix race --- addrbook.go | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/addrbook.go b/addrbook.go index 5450c515f..8a1698f41 100644 --- a/addrbook.go +++ b/addrbook.go @@ -135,15 +135,15 @@ func (a *AddrBook) OnStart() error { return nil } -func (a *AddrBook) Wait() { - a.wg.Wait() -} - // OnStop implements Service. func (a *AddrBook) OnStop() { a.BaseService.OnStop() } +func (a *AddrBook) Wait() { + a.wg.Wait() +} + func (a *AddrBook) AddOurAddress(addr *NetAddress) { a.mtx.Lock() defer a.mtx.Unlock() @@ -320,6 +320,8 @@ type addrBookJSON struct { func (a *AddrBook) saveToFile(filePath string) { log.Info("Saving AddrBook to file", "size", a.Size()) + a.mtx.Lock() + defer a.mtx.Unlock() // Compile Addrs addrs := []*knownAddress{} for _, ka := range a.addrLookup { From 9ce71013df9ccf08890307314ec13500ec58f6f3 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Thu, 20 Apr 2017 12:49:54 +0400 Subject: [PATCH 162/309] revert e448199 --- pex_reactor.go | 31 +++++++++++++++++++++++-------- 1 file changed, 23 insertions(+), 8 deletions(-) diff --git a/pex_reactor.go b/pex_reactor.go index a86bebe12..489635556 100644 --- a/pex_reactor.go +++ b/pex_reactor.go @@ -7,6 +7,7 @@ import ( "reflect" "time" + cmn "github.com/tendermint/go-common" wire "github.com/tendermint/go-wire" ) @@ -209,6 +210,17 @@ func (r *PEXReactor) ensurePeersRoutine() { } // ensurePeers ensures that sufficient peers are connected. (once) +// +// Old bucket / New bucket are arbitrary categories to denote whether an +// address is vetted or not, and this needs to be determined over time via a +// heuristic that we haven't perfected yet, or, perhaps is manually edited by +// the node operator. It should not be used to compute what addresses are +// already connected or not. +// +// TODO Basically, we need to work harder on our good-peer/bad-peer marking. +// What we're currently doing in terms of marking good/bad peers is just a +// placeholder. It should not be the case that an address becomes old/vetted +// upon a single successful connection. func (r *PEXReactor) ensurePeers() { numOutPeers, _, numDialing := r.Switch.NumPeers() numToDial := minNumOutboundPeers - (numOutPeers + numDialing) @@ -221,22 +233,28 @@ func (r *PEXReactor) ensurePeers() { // Try to pick numToDial addresses to dial. for i := 0; i < numToDial; i++ { + // The purpose of newBias is to first prioritize old (more vetted) peers + // when we have few connections, but to allow for new (less vetted) peers + // if we already have many connections. This algorithm isn't perfect, but + // it somewhat ensures that we prioritize connecting to more-vetted + // peers. + newBias := cmn.MinInt(numOutPeers, 8)*10 + 10 var picked *NetAddress // Try to fetch a new peer 3 times. // This caps the maximum number of tries to 3 * numToDial. for j := 0; j < 3; j++ { - // NOTE always picking from the new group because old one stores already - // connected peers. - try := r.book.PickAddress(100) + try := r.book.PickAddress(newBias) if try == nil { break } _, alreadySelected := toDial[try.IP.String()] alreadyDialing := r.Switch.IsDialing(try) - if alreadySelected || alreadyDialing { + alreadyConnected := r.Switch.Peers().Has(try.IP.String()) + if alreadySelected || alreadyDialing || alreadyConnected { // log.Info("Cannot dial address", "addr", try, // "alreadySelected", alreadySelected, - // "alreadyDialing", alreadyDialing) + // "alreadyDialing", alreadyDialing, + // "alreadyConnected", alreadyConnected) continue } else { log.Info("Will dial address", "addr", try) @@ -256,9 +274,6 @@ func (r *PEXReactor) ensurePeers() { _, err := r.Switch.DialPeerWithAddress(picked, false) if err != nil { r.book.MarkAttempt(picked) - } else { - // move address to the old group - r.book.MarkGood(picked) } }(item) } From 17ec70fc096be1cc3eee7b8580caee21ab0f0c71 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Thu, 20 Apr 2017 13:04:40 +0400 Subject: [PATCH 163/309] revert 2710873 --- pex_reactor.go | 16 +++------------- pex_reactor_test.go | 38 ++++++++++++++++++++++++-------------- 2 files changed, 27 insertions(+), 27 deletions(-) diff --git a/pex_reactor.go b/pex_reactor.go index 489635556..c6e4fbf3d 100644 --- a/pex_reactor.go +++ b/pex_reactor.go @@ -109,20 +109,10 @@ func (r *PEXReactor) AddPeer(p *Peer) { } } -// RemovePeer implements Reactor by removing peer from the address book. -// -// The peer will be proposed to us by other peers (PexAddrsMessage) or himself -// and we will add him again upon successful connection. Note that other peers -// will remove him too. The peer will need to send first requests to others by -// himself (he will have an addrbook or the seeds). +// RemovePeer implements Reactor. func (r *PEXReactor) RemovePeer(p *Peer, reason interface{}) { - addr, err := NewNetAddressString(p.ListenAddr) - if err != nil { - // this should never happen - log.Error("Error in AddPeer: invalid peer address", "addr", p.ListenAddr, "error", err) - return - } - r.book.RemoveAddress(addr) + // If we aren't keeping track of local temp data for each peer here, then we + // don't have to do anything. } // Receive implements Reactor by handling incoming PEX messages. diff --git a/pex_reactor_test.go b/pex_reactor_test.go index 525efd3cb..13f2fa208 100644 --- a/pex_reactor_test.go +++ b/pex_reactor_test.go @@ -14,20 +14,24 @@ import ( ) func TestPEXReactorBasic(t *testing.T) { + assert, require := assert.New(t), require.New(t) + dir, err := ioutil.TempDir("", "pex_reactor") - require.Nil(t, err) + require.Nil(err) defer os.RemoveAll(dir) book := NewAddrBook(dir+"addrbook.json", true) r := NewPEXReactor(book) - assert.NotNil(t, r) - assert.NotEmpty(t, r.GetChannels()) + assert.NotNil(r) + assert.NotEmpty(r.GetChannels()) } func TestPEXReactorAddRemovePeer(t *testing.T) { + assert, require := assert.New(t), require.New(t) + dir, err := ioutil.TempDir("", "pex_reactor") - require.Nil(t, err) + require.Nil(err) defer os.RemoveAll(dir) book := NewAddrBook(dir+"addrbook.json", true) @@ -37,26 +41,28 @@ func TestPEXReactorAddRemovePeer(t *testing.T) { peer := createRandomPeer(false) r.AddPeer(peer) - assert.Equal(t, size+1, book.Size()) + assert.Equal(size+1, book.Size()) r.RemovePeer(peer, "peer not available") - assert.Equal(t, size, book.Size()) + assert.Equal(size+1, book.Size()) outboundPeer := createRandomPeer(true) r.AddPeer(outboundPeer) - assert.Equal(t, size, book.Size(), "size must not change") + assert.Equal(size+1, book.Size(), "outbound peers should not be added to the address book") r.RemovePeer(outboundPeer, "peer not available") - assert.Equal(t, size, book.Size(), "size must not change") + assert.Equal(size+1, book.Size()) } func TestPEXReactorRunning(t *testing.T) { + require := require.New(t) + N := 3 switches := make([]*Switch, N) dir, err := ioutil.TempDir("", "pex_reactor") - require.Nil(t, err) + require.Nil(err) defer os.RemoveAll(dir) book := NewAddrBook(dir+"addrbook.json", false) @@ -80,7 +86,7 @@ func TestPEXReactorRunning(t *testing.T) { // start switches for _, s := range switches { _, err := s.Start() // start switch and reactors - require.Nil(t, err) + require.Nil(err) } time.Sleep(1 * time.Second) @@ -100,8 +106,10 @@ func TestPEXReactorRunning(t *testing.T) { } func TestPEXReactorReceive(t *testing.T) { + assert, require := assert.New(t), require.New(t) + dir, err := ioutil.TempDir("", "pex_reactor") - require.Nil(t, err) + require.Nil(err) defer os.RemoveAll(dir) book := NewAddrBook(dir+"addrbook.json", true) @@ -114,15 +122,17 @@ func TestPEXReactorReceive(t *testing.T) { addrs := []*NetAddress{netAddr} msg := wire.BinaryBytes(struct{ PexMessage }{&pexAddrsMessage{Addrs: addrs}}) r.Receive(PexChannel, peer, msg) - assert.Equal(t, size+1, book.Size()) + assert.Equal(size+1, book.Size()) msg = wire.BinaryBytes(struct{ PexMessage }{&pexRequestMessage{}}) r.Receive(PexChannel, peer, msg) } func TestPEXReactorAbuseFromPeer(t *testing.T) { + assert, require := assert.New(t), require.New(t) + dir, err := ioutil.TempDir("", "pex_reactor") - require.Nil(t, err) + require.Nil(err) defer os.RemoveAll(dir) book := NewAddrBook(dir+"addrbook.json", true) @@ -136,7 +146,7 @@ func TestPEXReactorAbuseFromPeer(t *testing.T) { r.Receive(PexChannel, peer, msg) } - assert.True(t, r.ReachedMaxMsgCountForPeer(peer.ListenAddr)) + assert.True(r.ReachedMaxMsgCountForPeer(peer.ListenAddr)) } func createRandomPeer(outbound bool) *Peer { From 8655e2456e7f7551549f1c2b7d65115925a9b0f8 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Thu, 20 Apr 2017 13:33:27 +0400 Subject: [PATCH 164/309] it is non-deterministic (could fail sometimes) --- connection_test.go | 1 - 1 file changed, 1 deletion(-) diff --git a/connection_test.go b/connection_test.go index 84e20eee3..33d8adfd1 100644 --- a/connection_test.go +++ b/connection_test.go @@ -39,7 +39,6 @@ func TestMConnectionSend(t *testing.T) { assert.True(mconn.Send(0x01, msg)) // Note: subsequent Send/TrySend calls could pass because we are reading from // the send queue in a separate goroutine. - assert.False(mconn.CanSend(0x01), "CanSend should return false because queue is full") server.Read(make([]byte, len(msg))) assert.True(mconn.CanSend(0x01)) From 391c738959f7c800e0ff04d49b7d3cbfda5df427 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Thu, 20 Apr 2017 12:21:45 -0400 Subject: [PATCH 165/309] update comment about outbound peers and addrbook --- pex_reactor.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/pex_reactor.go b/pex_reactor.go index c6e4fbf3d..0244416d1 100644 --- a/pex_reactor.go +++ b/pex_reactor.go @@ -94,7 +94,10 @@ func (r *PEXReactor) GetChannels() []*ChannelDescriptor { // AddPeer implements Reactor by adding peer to the address book (if inbound) // or by requesting more addresses (if outbound). func (r *PEXReactor) AddPeer(p *Peer) { - if p.IsOutbound() { // For outbound peers, the address is already in the books + if p.IsOutbound() { + // For outbound peers, the address is already in the books. + // Either it was added in DialSeeds or when we + // received the peer's address in r.Receive if r.book.NeedMoreAddrs() { r.RequestPEX(p) } From 75bad132fc71e08b13dbf3b1b15b6fa8026d7adf Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Thu, 20 Apr 2017 17:29:43 -0400 Subject: [PATCH 166/309] msgCountByPeer is a CMap --- pex_reactor.go | 23 ++++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/pex_reactor.go b/pex_reactor.go index 0244416d1..4b6129762 100644 --- a/pex_reactor.go +++ b/pex_reactor.go @@ -49,7 +49,7 @@ type PEXReactor struct { ensurePeersPeriod time.Duration // tracks message count by peer, so we can prevent abuse - msgCountByPeer map[string]uint16 + msgCountByPeer *cmn.CMap maxMsgCountByPeer uint16 } @@ -58,7 +58,7 @@ func NewPEXReactor(b *AddrBook) *PEXReactor { r := &PEXReactor{ book: b, ensurePeersPeriod: defaultEnsurePeersPeriod, - msgCountByPeer: make(map[string]uint16), + msgCountByPeer: cmn.NewCMap(), maxMsgCountByPeer: defaultMaxMsgCountByPeer, } r.BaseReactor = *NewBaseReactor(log, "PEXReactor", r) @@ -122,7 +122,8 @@ func (r *PEXReactor) RemovePeer(p *Peer, reason interface{}) { func (r *PEXReactor) Receive(chID byte, src *Peer, msgBytes []byte) { srcAddr := src.Connection().RemoteAddress srcAddrStr := srcAddr.String() - r.msgCountByPeer[srcAddrStr]++ + + r.IncrementMsgCountForPeer(srcAddrStr) if r.ReachedMaxMsgCountForPeer(srcAddrStr) { log.Warn("Maximum number of messages reached for peer", "peer", srcAddrStr) // TODO remove src from peers? @@ -175,8 +176,20 @@ func (r *PEXReactor) SetMaxMsgCountByPeer(v uint16) { // ReachedMaxMsgCountForPeer returns true if we received too many // messages from peer with address `addr`. +// NOTE: assumes the value in the CMap is non-nil func (r *PEXReactor) ReachedMaxMsgCountForPeer(addr string) bool { - return r.msgCountByPeer[addr] >= r.maxMsgCountByPeer + return r.msgCountByPeer.Get(addr).(uint16) >= r.maxMsgCountByPeer +} + +// Increment or initialize the msg count for the peer in the CMap +func (r *PEXReactor) IncrementMsgCountForPeer(addr string) { + var count uint16 + countI := r.msgCountByPeer.Get(addr) + if countI != nil { + count = countI.(uint16) + } + count++ + r.msgCountByPeer.Set(addr, count) } // Ensures that sufficient peers are connected. (continuous) @@ -288,7 +301,7 @@ func (r *PEXReactor) flushMsgCountByPeer() { for { select { case <-ticker.C: - r.msgCountByPeer = make(map[string]uint16) + r.msgCountByPeer.Clear() case <-r.Quit: ticker.Stop() return From d6fd0c4ca07c0be6d6503d5231060301a3494ab1 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Fri, 21 Apr 2017 18:30:22 +0300 Subject: [PATCH 167/309] fix backward compatibility for WS --- rpc_test.go | 28 ++++++++++++++++++++++++++++ server/handlers.go | 2 +- 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/rpc_test.go b/rpc_test.go index 56b8ade32..ed28cbc8d 100644 --- a/rpc_test.go +++ b/rpc_test.go @@ -261,6 +261,34 @@ func TestWSNewWSRPCFunc(t *testing.T) { } } +func TestWSHandlesArrayParams(t *testing.T) { + cl := client.NewWSClient(tcpAddr, websocketEndpoint) + _, err := cl.Start() + require.Nil(t, err) + defer cl.Stop() + + val := "acbd" + params := []interface{}{val} + err = cl.WriteJSON(types.RPCRequest{ + JSONRPC: "2.0", + ID: "", + Method: "echo_ws", + Params: params, + }) + require.Nil(t, err) + + select { + case msg := <-cl.ResultsCh: + result := new(Result) + wire.ReadJSONPtr(result, msg, &err) + require.Nil(t, err) + got := (*result).(*ResultEcho).Value + assert.Equal(t, got, val) + case err := <-cl.ErrorsCh: + t.Fatalf("%+v", err) + } +} + func randBytes(t *testing.T) []byte { n := rand.Intn(10) + 2 buf := make([]byte, n) diff --git a/server/handlers.go b/server/handlers.go index de2b8094f..9fa327cbb 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -173,7 +173,7 @@ func jsonParamsToArgs(rpcFunc *RPCFunc, paramsI interface{}, argsOffset int) ([] } values := make([]reflect.Value, len(params)) for i, p := range params { - ty := rpcFunc.args[i] + ty := rpcFunc.args[i+argsOffset] v, err := _jsonObjectToArg(ty, p) if err != nil { return nil, err From a01cff9ce630a93168ff7aa003072a7164bdc1ef Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 21 Apr 2017 12:18:21 -0400 Subject: [PATCH 168/309] jsonParamsToArgsRPC func --- server/handlers.go | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/server/handlers.go b/server/handlers.go index 9fa327cbb..9be64b775 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -124,7 +124,7 @@ func makeJSONRPCHandler(funcMap map[string]*RPCFunc) http.HandlerFunc { WriteRPCResponseHTTP(w, types.NewRPCResponse(request.ID, nil, "RPC method is only for websockets: "+request.Method)) return } - args, err := jsonParamsToArgs(rpcFunc, request.Params, 0) + args, err := jsonParamsToArgsRPC(rpcFunc, request.Params) if err != nil { WriteRPCResponseHTTP(w, types.NewRPCResponse(request.ID, nil, fmt.Sprintf("Error converting json params to arguments: %v", err.Error()))) return @@ -142,7 +142,7 @@ func makeJSONRPCHandler(funcMap map[string]*RPCFunc) http.HandlerFunc { // Convert a []interface{} OR a map[string]interface{} to properly typed values // -// argsOffset is used in jsonParamsToArgsWS, where len(rpcFunc.args) != len(rpcFunc.argNames). +// argsOffset should be 0 for RPC calls, and 1 for WS requests, where len(rpcFunc.args) != len(rpcFunc.argNames). // Example: // rpcFunc.args = [rpctypes.WSRPCContext string] // rpcFunc.argNames = ["arg"] @@ -187,6 +187,11 @@ func jsonParamsToArgs(rpcFunc *RPCFunc, paramsI interface{}, argsOffset int) ([] return values, nil } +// Convert a []interface{} OR a map[string]interface{} to properly typed values +func jsonParamsToArgsRPC(rpcFunc *RPCFunc, paramsI interface{}) ([]reflect.Value, error) { + return jsonParamsToArgs(rpcFunc, paramsI, 0) +} + // Same as above, but with the first param the websocket connection func jsonParamsToArgsWS(rpcFunc *RPCFunc, paramsI interface{}, wsCtx types.WSRPCContext) ([]reflect.Value, error) { values, err := jsonParamsToArgs(rpcFunc, paramsI, 1) @@ -494,7 +499,7 @@ func (wsc *wsConnection) readRoutine() { wsCtx := types.WSRPCContext{Request: request, WSRPCConnection: wsc} args, err = jsonParamsToArgsWS(rpcFunc, request.Params, wsCtx) } else { - args, err = jsonParamsToArgs(rpcFunc, request.Params, 0) + args, err = jsonParamsToArgsRPC(rpcFunc, request.Params) } if err != nil { wsc.WriteRPCResponse(types.NewRPCResponse(request.ID, nil, err.Error())) From 58ccefa407c843123ecb9224ed2b16d387f6e953 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 21 Apr 2017 13:06:26 -0400 Subject: [PATCH 169/309] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bba6dd77b..cae2f4c9f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## 0.5.0 (April 18, 2017) +## 0.5.0 (April 21, 2017) BREAKING CHANGES: From 516e78ea54915ac2c1defc6c595dd6bda4862fa7 Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Tue, 21 Mar 2017 22:12:02 +0100 Subject: [PATCH 170/309] Fix types to use updated go-crypto --- glide.lock | 4 ++-- types/priv_validator.go | 44 +++++++++++++++---------------------- types/validator_set_test.go | 6 ++--- 3 files changed, 23 insertions(+), 31 deletions(-) diff --git a/glide.lock b/glide.lock index 42712c232..a1a29b9db 100644 --- a/glide.lock +++ b/glide.lock @@ -90,9 +90,9 @@ imports: - name: github.com/tendermint/go-config version: 620dcbbd7d587cf3599dedbf329b64311b0c307a - name: github.com/tendermint/go-crypto - version: 0ca2c6fdb0706001ca4c4b9b80c9f428e8cf39da + version: 3e1dba7ab762bb689123eec30c468967f077a6a4 - name: github.com/tendermint/go-data - version: e7fcc6d081ec8518912fcdc103188275f83a3ee5 + version: 9fbf0684fefc4fad580992394a0bcf47c1b3d77e - name: github.com/tendermint/go-db version: 9643f60bc2578693844aacf380a7c32e4c029fee - name: github.com/tendermint/go-events diff --git a/types/priv_validator.go b/types/priv_validator.go index c200dff3c..8752e430d 100644 --- a/types/priv_validator.go +++ b/types/priv_validator.go @@ -11,8 +11,6 @@ import ( . "github.com/tendermint/go-common" "github.com/tendermint/go-crypto" "github.com/tendermint/go-wire" - - "github.com/tendermint/ed25519" ) const ( @@ -81,22 +79,15 @@ func (privVal *PrivValidator) SetSigner(s Signer) { // Generates a new validator with private key. func GenPrivValidator() *PrivValidator { - privKeyBytes := new([64]byte) - copy(privKeyBytes[:32], crypto.CRandBytes(32)) - pubKeyBytes := ed25519.MakePublicKey(privKeyBytes) - pubKey := crypto.PubKeyEd25519(*pubKeyBytes) - privKey := crypto.PrivKeyEd25519(*privKeyBytes) + privKey := crypto.WrapPrivKey(crypto.GenPrivKeyEd25519()) + pubKey := privKey.PubKey() return &PrivValidator{ - Address: pubKey.Address(), - PubKey: pubKey, - PrivKey: privKey, - LastHeight: 0, - LastRound: 0, - LastStep: stepNone, - LastSignature: nil, - LastSignBytes: nil, - filePath: "", - Signer: NewDefaultSigner(privKey), + Address: pubKey.Address(), + PubKey: pubKey, + PrivKey: privKey, + LastStep: stepNone, + filePath: "", + Signer: NewDefaultSigner(privKey), } } @@ -158,7 +149,7 @@ func (privVal *PrivValidator) Reset() { privVal.LastHeight = 0 privVal.LastRound = 0 privVal.LastStep = 0 - privVal.LastSignature = nil + privVal.LastSignature = crypto.Signature{} privVal.LastSignBytes = nil privVal.Save() } @@ -191,23 +182,24 @@ func (privVal *PrivValidator) SignProposal(chainID string, proposal *Proposal) e // check if there's a regression. Else sign and write the hrs+signature to disk func (privVal *PrivValidator) signBytesHRS(height, round int, step int8, signBytes []byte) (crypto.Signature, error) { + sig := crypto.Signature{} // If height regression, err if privVal.LastHeight > height { - return nil, errors.New("Height regression") + return sig, errors.New("Height regression") } // More cases for when the height matches if privVal.LastHeight == height { // If round regression, err if privVal.LastRound > round { - return nil, errors.New("Round regression") + return sig, errors.New("Round regression") } // If step regression, err if privVal.LastRound == round { if privVal.LastStep > step { - return nil, errors.New("Step regression") + return sig, errors.New("Step regression") } else if privVal.LastStep == step { if privVal.LastSignBytes != nil { - if privVal.LastSignature == nil { + if privVal.LastSignature.Empty() { PanicSanity("privVal: LastSignature is nil but LastSignBytes is not!") } // so we dont sign a conflicting vote or proposal @@ -218,23 +210,23 @@ func (privVal *PrivValidator) signBytesHRS(height, round int, step int8, signByt return privVal.LastSignature, nil } } - return nil, errors.New("Step regression") + return sig, errors.New("Step regression") } } } // Sign - signature := privVal.Sign(signBytes) + sig = privVal.Sign(signBytes) // Persist height/round/step privVal.LastHeight = height privVal.LastRound = round privVal.LastStep = step - privVal.LastSignature = signature + privVal.LastSignature = sig privVal.LastSignBytes = signBytes privVal.save() - return signature, nil + return sig, nil } diff --git a/types/validator_set_test.go b/types/validator_set_test.go index bc7fef798..b918b8d5f 100644 --- a/types/validator_set_test.go +++ b/types/validator_set_test.go @@ -9,10 +9,10 @@ import ( "github.com/tendermint/go-crypto" ) -func randPubKey() crypto.PubKeyEd25519 { +func randPubKey() crypto.PubKey { var pubKey [32]byte copy(pubKey[:], cmn.RandBytes(32)) - return crypto.PubKeyEd25519(pubKey) + return crypto.WrapPubKey(crypto.PubKeyEd25519(pubKey)) } func randValidator_() *Validator { @@ -194,7 +194,7 @@ func BenchmarkValidatorSetCopy(b *testing.B) { vset := NewValidatorSet([]*Validator{}) for i := 0; i < 1000; i++ { privKey := crypto.GenPrivKeyEd25519() - pubKey := privKey.PubKey().(crypto.PubKeyEd25519) + pubKey := privKey.PubKey() val := NewValidator(pubKey, 0) if !vset.Add(val) { panic("Failed to add validator") From e325ffc681f3efff705bbe281b86234b8e10dfd2 Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Tue, 21 Mar 2017 22:46:15 +0100 Subject: [PATCH 171/309] Lots of updates to use new go-crypto / json style --- benchmarks/codec_test.go | 10 +++++----- cmd/tendermint/commands/show_validator.go | 5 +++-- config/tendermint_test/config.go | 24 +++++++++++------------ glide.lock | 2 +- node/node.go | 2 +- types/genesis.go | 14 ++++++++----- types/priv_validator.go | 15 +++++++++----- 7 files changed, 41 insertions(+), 31 deletions(-) diff --git a/benchmarks/codec_test.go b/benchmarks/codec_test.go index 35dc591ea..0e77156cf 100644 --- a/benchmarks/codec_test.go +++ b/benchmarks/codec_test.go @@ -12,10 +12,10 @@ import ( func BenchmarkEncodeStatusWire(b *testing.B) { b.StopTimer() - pubKey := crypto.GenPrivKeyEd25519().PubKey().(crypto.PubKeyEd25519) + pubKey := crypto.GenPrivKeyEd25519().PubKey() status := &ctypes.ResultStatus{ NodeInfo: &p2p.NodeInfo{ - PubKey: pubKey, + PubKey: pubKey.Unwrap().(crypto.PubKeyEd25519), Moniker: "SOMENAME", Network: "SOMENAME", RemoteAddr: "SOMEADDR", @@ -40,7 +40,7 @@ func BenchmarkEncodeStatusWire(b *testing.B) { func BenchmarkEncodeNodeInfoWire(b *testing.B) { b.StopTimer() - pubKey := crypto.GenPrivKeyEd25519().PubKey().(crypto.PubKeyEd25519) + pubKey := crypto.GenPrivKeyEd25519().PubKey().Unwrap().(crypto.PubKeyEd25519) nodeInfo := &p2p.NodeInfo{ PubKey: pubKey, Moniker: "SOMENAME", @@ -61,7 +61,7 @@ func BenchmarkEncodeNodeInfoWire(b *testing.B) { func BenchmarkEncodeNodeInfoBinary(b *testing.B) { b.StopTimer() - pubKey := crypto.GenPrivKeyEd25519().PubKey().(crypto.PubKeyEd25519) + pubKey := crypto.GenPrivKeyEd25519().PubKey().Unwrap().(crypto.PubKeyEd25519) nodeInfo := &p2p.NodeInfo{ PubKey: pubKey, Moniker: "SOMENAME", @@ -83,7 +83,7 @@ func BenchmarkEncodeNodeInfoBinary(b *testing.B) { func BenchmarkEncodeNodeInfoProto(b *testing.B) { b.StopTimer() - pubKey := crypto.GenPrivKeyEd25519().PubKey().(crypto.PubKeyEd25519) + pubKey := crypto.GenPrivKeyEd25519().PubKey().Unwrap().(crypto.PubKeyEd25519) pubKey2 := &proto.PubKey{Ed25519: &proto.PubKeyEd25519{Bytes: pubKey[:]}} nodeInfo := &proto.NodeInfo{ PubKey: pubKey2, diff --git a/cmd/tendermint/commands/show_validator.go b/cmd/tendermint/commands/show_validator.go index 4aa80ae14..0b349f98c 100644 --- a/cmd/tendermint/commands/show_validator.go +++ b/cmd/tendermint/commands/show_validator.go @@ -5,7 +5,7 @@ import ( "github.com/spf13/cobra" - "github.com/tendermint/go-wire" + data "github.com/tendermint/go-data" "github.com/tendermint/tendermint/types" ) @@ -22,5 +22,6 @@ func init() { func showValidator(cmd *cobra.Command, args []string) { privValidatorFile := config.GetString("priv_validator_file") privValidator := types.LoadOrGenPrivValidator(privValidatorFile) - fmt.Println(string(wire.JSONBytesPretty(privValidator.PubKey))) + pubKeyJSONBytes, _ := data.ToJSON(privValidator.PubKey) + fmt.Println(string(pubKeyJSONBytes)) } diff --git a/config/tendermint_test/config.go b/config/tendermint_test/config.go index 9d405dc95..78c3bb337 100644 --- a/config/tendermint_test/config.go +++ b/config/tendermint_test/config.go @@ -137,10 +137,10 @@ var defaultGenesis = `{ "chain_id": "tendermint_test", "validators": [ { - "pub_key": [ - 1, - "3B3069C422E19688B45CBFAE7BB009FC0FA1B1EA86593519318B7214853803C8" - ], + "pub_key": { + "type": "ed25519", + "data":"3B3069C422E19688B45CBFAE7BB009FC0FA1B1EA86593519318B7214853803C8" + }, "amount": 10, "name": "" } @@ -150,14 +150,14 @@ var defaultGenesis = `{ var defaultPrivValidator = `{ "address": "D028C9981F7A87F3093672BF0D5B0E2A1B3ED456", - "pub_key": [ - 1, - "3B3069C422E19688B45CBFAE7BB009FC0FA1B1EA86593519318B7214853803C8" - ], - "priv_key": [ - 1, - "27F82582AEFAE7AB151CFB01C48BB6C1A0DA78F9BDDA979A9F70A84D074EB07D3B3069C422E19688B45CBFAE7BB009FC0FA1B1EA86593519318B7214853803C8" - ], + "pub_key": { + "type": "ed25519", + "data": "3B3069C422E19688B45CBFAE7BB009FC0FA1B1EA86593519318B7214853803C8" + }, + "priv_key": { + "type": "ed25519", + "data": "27F82582AEFAE7AB151CFB01C48BB6C1A0DA78F9BDDA979A9F70A84D074EB07D3B3069C422E19688B45CBFAE7BB009FC0FA1B1EA86593519318B7214853803C8" + }, "last_height": 0, "last_round": 0, "last_step": 0 diff --git a/glide.lock b/glide.lock index a1a29b9db..f49e2d3ad 100644 --- a/glide.lock +++ b/glide.lock @@ -106,7 +106,7 @@ imports: - name: github.com/tendermint/go-merkle version: 714d4d04557fd068a7c2a1748241ce8428015a96 - name: github.com/tendermint/go-p2p - version: e8f33a47846708269d373f9c8080613d6c4f66b2 + version: a163fddbdd2541793d22402afb113e6ccb391774 subpackages: - upnp - name: github.com/tendermint/go-rpc diff --git a/node/node.go b/node/node.go index 990779486..96440e910 100644 --- a/node/node.go +++ b/node/node.go @@ -372,7 +372,7 @@ func (n *Node) makeNodeInfo() *p2p.NodeInfo { } nodeInfo := &p2p.NodeInfo{ - PubKey: n.privKey.PubKey().(crypto.PubKeyEd25519), + PubKey: n.privKey.PubKey().Unwrap().(crypto.PubKeyEd25519), Moniker: n.config.GetString("moniker"), Network: n.config.GetString("chain_id"), Version: version.Version, diff --git a/types/genesis.go b/types/genesis.go index 3a0395488..2e1ebb649 100644 --- a/types/genesis.go +++ b/types/genesis.go @@ -1,11 +1,11 @@ package types import ( + "encoding/json" "time" . "github.com/tendermint/go-common" "github.com/tendermint/go-crypto" - "github.com/tendermint/go-wire" ) //------------------------------------------------------------ @@ -31,14 +31,18 @@ type GenesisDoc struct { // Utility method for saving GenensisDoc as JSON file. func (genDoc *GenesisDoc) SaveAs(file string) error { - genDocBytes := wire.JSONBytesPretty(genDoc) + genDocBytes, err := json.Marshal(genDoc) + if err != nil { + return err + } return WriteFile(file, genDocBytes, 0644) } //------------------------------------------------------------ // Make genesis state from file -func GenesisDocFromJSON(jsonBlob []byte) (genDoc *GenesisDoc, err error) { - wire.ReadJSONPtr(&genDoc, jsonBlob, &err) - return +func GenesisDocFromJSON(jsonBlob []byte) (*GenesisDoc, error) { + genDoc := GenesisDoc{} + err := json.Unmarshal(jsonBlob, &genDoc) + return &genDoc, err } diff --git a/types/priv_validator.go b/types/priv_validator.go index 8752e430d..905f3bf15 100644 --- a/types/priv_validator.go +++ b/types/priv_validator.go @@ -2,6 +2,7 @@ package types import ( "bytes" + "encoding/json" "errors" "fmt" "io/ioutil" @@ -10,7 +11,6 @@ import ( . "github.com/tendermint/go-common" "github.com/tendermint/go-crypto" - "github.com/tendermint/go-wire" ) const ( @@ -96,13 +96,14 @@ func LoadPrivValidator(filePath string) *PrivValidator { if err != nil { Exit(err.Error()) } - privVal := wire.ReadJSON(&PrivValidator{}, privValJSONBytes, &err).(*PrivValidator) + privVal := PrivValidator{} + err = json.Unmarshal(privValJSONBytes, &privVal) if err != nil { Exit(Fmt("Error reading PrivValidator from %v: %v\n", filePath, err)) } privVal.filePath = filePath privVal.Signer = NewDefaultSigner(privVal.PrivKey) - return privVal + return &privVal } func LoadOrGenPrivValidator(filePath string) *PrivValidator { @@ -136,8 +137,12 @@ func (privVal *PrivValidator) save() { if privVal.filePath == "" { PanicSanity("Cannot save PrivValidator: filePath not set") } - jsonBytes := wire.JSONBytesPretty(privVal) - err := WriteFileAtomic(privVal.filePath, jsonBytes, 0600) + jsonBytes, err := json.Marshal(privVal) + if err != nil { + // `@; BOOM!!! + PanicCrisis(err) + } + err = WriteFileAtomic(privVal.filePath, jsonBytes, 0600) if err != nil { // `@; BOOM!!! PanicCrisis(err) From 7e56aad51a9a2b6039b4f1a323d82e3acbd83fd9 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Wed, 22 Mar 2017 12:43:50 +0400 Subject: [PATCH 172/309] [consensus/test_data/build.sh] install tendermint if absent --- consensus/test_data/build.sh | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) mode change 100644 => 100755 consensus/test_data/build.sh diff --git a/consensus/test_data/build.sh b/consensus/test_data/build.sh old mode 100644 new mode 100755 index 2759c0e38..93a74b8ba --- a/consensus/test_data/build.sh +++ b/consensus/test_data/build.sh @@ -1,18 +1,23 @@ -#! /bin/bash +#!/usr/bin/env bash # XXX: removes tendermint dir -cd $GOPATH/src/github.com/tendermint/tendermint +cd "$GOPATH/src/github.com/tendermint/tendermint" || exit 1 + +# Make sure we have a tendermint command. +if ! hash tendermint 2>/dev/null; then + make install +fi # specify a dir to copy # TODO: eventually we should replace with `tendermint init --test` -DIR=$HOME/.tendermint_test/consensus_state_test +DIR_TO_COPY=$HOME/.tendermint_test/consensus_state_test -rm -rf $HOME/.tendermint -cp -r $DIR $HOME/.tendermint +rm -rf "$HOME/.tendermint" +cp -r "$DIR_TO_COPY" "$HOME/.tendermint" function reset(){ - rm -rf $HOME/.tendermint/data + rm -rf "$HOME/.tendermint/data" tendermint unsafe_reset_priv_validator } @@ -24,8 +29,8 @@ tendermint node --proxy_app=dummy &> /dev/null & sleep 5 killall tendermint -# /q would print up to and including the match, then quit. -# /Q doesn't include the match. +# /q would print up to and including the match, then quit. +# /Q doesn't include the match. # http://unix.stackexchange.com/questions/11305/grep-show-all-the-file-up-to-the-match sed '/ENDHEIGHT: 1/Q' ~/.tendermint/data/cs.wal/wal > consensus/test_data/empty_block.cswal @@ -80,7 +85,7 @@ reset -case "$1" in +case "$1" in "small_block1") small_block1 ;; From b798169c6e636c4b88d9cecde764224dca93b479 Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Wed, 22 Mar 2017 16:02:37 +0100 Subject: [PATCH 173/309] Update go-crypto to read/write properly with go-wire in wal files --- glide.lock | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/glide.lock b/glide.lock index f49e2d3ad..fcede6fc9 100644 --- a/glide.lock +++ b/glide.lock @@ -90,7 +90,7 @@ imports: - name: github.com/tendermint/go-config version: 620dcbbd7d587cf3599dedbf329b64311b0c307a - name: github.com/tendermint/go-crypto - version: 3e1dba7ab762bb689123eec30c468967f077a6a4 + version: 67c7682135e7e9a8c56a7eeae9ac885d342a3315 - name: github.com/tendermint/go-data version: 9fbf0684fefc4fad580992394a0bcf47c1b3d77e - name: github.com/tendermint/go-db From 6a0217688f93fcd4d14fcc9b563dbca2e8259c50 Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Wed, 22 Mar 2017 18:16:22 +0100 Subject: [PATCH 174/309] Ensure private validator addresses are hex --- consensus/replay_test.go | 8 ++++- glide.lock | 2 +- types/priv_validator.go | 7 +++-- types/priv_validator_test.go | 60 ++++++++++++++++++++++++++++++++++++ 4 files changed, 72 insertions(+), 5 deletions(-) create mode 100644 types/priv_validator_test.go diff --git a/consensus/replay_test.go b/consensus/replay_test.go index 43204ab72..9368df99d 100644 --- a/consensus/replay_test.go +++ b/consensus/replay_test.go @@ -131,7 +131,13 @@ func runReplayTest(t *testing.T, cs *ConsensusState, walFile string, newBlockCh thisCase *testCase, i int) { cs.config.Set("cs_wal_file", walFile) - cs.Start() + started, err := cs.Start() + if err != nil { + t.Fatalf("Cannot start consensus: %v", err) + } + if !started { + t.Error("Consensus did not start") + } // Wait to make a new block. // This is just a signal that we haven't halted; its not something contained in the WAL itself. // Assuming the consensus state is running, replay of any WAL, including the empty one, diff --git a/glide.lock b/glide.lock index fcede6fc9..5bddeea33 100644 --- a/glide.lock +++ b/glide.lock @@ -92,7 +92,7 @@ imports: - name: github.com/tendermint/go-crypto version: 67c7682135e7e9a8c56a7eeae9ac885d342a3315 - name: github.com/tendermint/go-data - version: 9fbf0684fefc4fad580992394a0bcf47c1b3d77e + version: 3a135dc080d4304da75b57806f0f83a2ea9d40f8 - name: github.com/tendermint/go-db version: 9643f60bc2578693844aacf380a7c32e4c029fee - name: github.com/tendermint/go-events diff --git a/types/priv_validator.go b/types/priv_validator.go index 905f3bf15..ed6313b81 100644 --- a/types/priv_validator.go +++ b/types/priv_validator.go @@ -11,6 +11,7 @@ import ( . "github.com/tendermint/go-common" "github.com/tendermint/go-crypto" + data "github.com/tendermint/go-data" ) const ( @@ -33,13 +34,13 @@ func voteToStep(vote *Vote) int8 { } type PrivValidator struct { - Address []byte `json:"address"` + Address data.Bytes `json:"address"` PubKey crypto.PubKey `json:"pub_key"` LastHeight int `json:"last_height"` LastRound int `json:"last_round"` LastStep int8 `json:"last_step"` - LastSignature crypto.Signature `json:"last_signature"` // so we dont lose signatures - LastSignBytes []byte `json:"last_signbytes"` // so we dont lose signatures + LastSignature crypto.Signature `json:"last_signature,omitempty"` // so we dont lose signatures + LastSignBytes data.Bytes `json:"last_signbytes,omitempty"` // so we dont lose signatures // PrivKey should be empty if a Signer other than the default is being used. PrivKey crypto.PrivKey `json:"priv_key"` diff --git a/types/priv_validator_test.go b/types/priv_validator_test.go new file mode 100644 index 000000000..1eb0b57db --- /dev/null +++ b/types/priv_validator_test.go @@ -0,0 +1,60 @@ +package types + +import ( + "encoding/hex" + "encoding/json" + "fmt" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + crypto "github.com/tendermint/go-crypto" +) + +func TestLoadValidator(t *testing.T) { + assert, require := assert.New(t), require.New(t) + + // create some fixed values + addrStr := "D028C9981F7A87F3093672BF0D5B0E2A1B3ED456" + pubStr := "3B3069C422E19688B45CBFAE7BB009FC0FA1B1EA86593519318B7214853803C8" + privStr := "27F82582AEFAE7AB151CFB01C48BB6C1A0DA78F9BDDA979A9F70A84D074EB07D3B3069C422E19688B45CBFAE7BB009FC0FA1B1EA86593519318B7214853803C8" + addrBytes, _ := hex.DecodeString(addrStr) + pubBytes, _ := hex.DecodeString(pubStr) + privBytes, _ := hex.DecodeString(privStr) + + // prepend type byte + pubKey, err := crypto.PubKeyFromBytes(append([]byte{1}, pubBytes...)) + require.Nil(err, "%+v", err) + privKey, err := crypto.PrivKeyFromBytes(append([]byte{1}, privBytes...)) + require.Nil(err, "%+v", err) + + serialized := fmt.Sprintf(`{ + "address": "%s", + "pub_key": { + "type": "ed25519", + "data": "%s" + }, + "priv_key": { + "type": "ed25519", + "data": "%s" + }, + "last_height": 0, + "last_round": 0, + "last_step": 0, + "last_signature": null +}`, addrStr, pubStr, privStr) + + val := PrivValidator{} + err = json.Unmarshal([]byte(serialized), &val) + require.Nil(err, "%+v", err) + + // make sure the values match + assert.EqualValues(addrBytes, val.Address) + assert.EqualValues(pubKey, val.PubKey) + assert.EqualValues(privKey, val.PrivKey) + + // export it and make sure it is the same + out, err := json.Marshal(val) + require.Nil(err, "%+v", err) + assert.JSONEq(serialized, string(out)) +} From 90abc61c567f30185cf1ca9fc7e89dd7cd455b12 Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Wed, 22 Mar 2017 20:13:18 +0100 Subject: [PATCH 175/309] Improve go-data json support in rpc --- rpc/client/httpclient.go | 3 ++- rpc/client/interface.go | 3 ++- rpc/client/localclient.go | 3 ++- rpc/client/mock/abci.go | 9 +++++---- rpc/client/mock/abci_test.go | 9 +++++---- rpc/client/mock/client.go | 3 ++- rpc/client/mock/status_test.go | 5 +++-- rpc/core/abci.go | 3 ++- rpc/core/mempool.go | 3 ++- rpc/core/routes.go | 10 ++++++---- rpc/core/status.go | 5 +++-- rpc/core/types/responses.go | 7 ++++--- rpc/test/client_test.go | 7 +++---- 13 files changed, 41 insertions(+), 29 deletions(-) diff --git a/rpc/client/httpclient.go b/rpc/client/httpclient.go index 04595e766..88a592348 100644 --- a/rpc/client/httpclient.go +++ b/rpc/client/httpclient.go @@ -4,6 +4,7 @@ import ( "fmt" "github.com/pkg/errors" + data "github.com/tendermint/go-data" events "github.com/tendermint/go-events" "github.com/tendermint/go-rpc/client" wire "github.com/tendermint/go-wire" @@ -67,7 +68,7 @@ func (c *HTTP) ABCIInfo() (*ctypes.ResultABCIInfo, error) { return (*tmResult).(*ctypes.ResultABCIInfo), nil } -func (c *HTTP) ABCIQuery(path string, data []byte, prove bool) (*ctypes.ResultABCIQuery, error) { +func (c *HTTP) ABCIQuery(path string, data data.Bytes, prove bool) (*ctypes.ResultABCIQuery, error) { tmResult := new(ctypes.TMResult) _, err := c.rpc.Call("abci_query", map[string]interface{}{"path": path, "data": data, "prove": prove}, diff --git a/rpc/client/interface.go b/rpc/client/interface.go index 2ba890798..eb79db8b1 100644 --- a/rpc/client/interface.go +++ b/rpc/client/interface.go @@ -20,6 +20,7 @@ implementation. package client import ( + data "github.com/tendermint/go-data" ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/types" ) @@ -30,7 +31,7 @@ import ( type ABCIClient interface { // reading from abci app ABCIInfo() (*ctypes.ResultABCIInfo, error) - ABCIQuery(path string, data []byte, prove bool) (*ctypes.ResultABCIQuery, error) + ABCIQuery(path string, data data.Bytes, prove bool) (*ctypes.ResultABCIQuery, error) // writing to abci app BroadcastTxCommit(tx types.Tx) (*ctypes.ResultBroadcastTxCommit, error) diff --git a/rpc/client/localclient.go b/rpc/client/localclient.go index d0f0d11b1..74051d8c9 100644 --- a/rpc/client/localclient.go +++ b/rpc/client/localclient.go @@ -1,6 +1,7 @@ package client import ( + data "github.com/tendermint/go-data" nm "github.com/tendermint/tendermint/node" "github.com/tendermint/tendermint/rpc/core" ctypes "github.com/tendermint/tendermint/rpc/core/types" @@ -56,7 +57,7 @@ func (c Local) ABCIInfo() (*ctypes.ResultABCIInfo, error) { return core.ABCIInfo() } -func (c Local) ABCIQuery(path string, data []byte, prove bool) (*ctypes.ResultABCIQuery, error) { +func (c Local) ABCIQuery(path string, data data.Bytes, prove bool) (*ctypes.ResultABCIQuery, error) { return core.ABCIQuery(path, data, prove) } diff --git a/rpc/client/mock/abci.go b/rpc/client/mock/abci.go index 6f6fa1d47..6a9fe6bdf 100644 --- a/rpc/client/mock/abci.go +++ b/rpc/client/mock/abci.go @@ -2,6 +2,7 @@ package mock import ( abci "github.com/tendermint/abci/types" + data "github.com/tendermint/go-data" "github.com/tendermint/tendermint/rpc/client" ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/types" @@ -22,7 +23,7 @@ func (a ABCIApp) ABCIInfo() (*ctypes.ResultABCIInfo, error) { return &ctypes.ResultABCIInfo{a.App.Info()}, nil } -func (a ABCIApp) ABCIQuery(path string, data []byte, prove bool) (*ctypes.ResultABCIQuery, error) { +func (a ABCIApp) ABCIQuery(path string, data data.Bytes, prove bool) (*ctypes.ResultABCIQuery, error) { q := a.App.Query(abci.RequestQuery{data, path, 0, prove}) return &ctypes.ResultABCIQuery{q}, nil } @@ -79,7 +80,7 @@ func (m ABCIMock) ABCIInfo() (*ctypes.ResultABCIInfo, error) { return &ctypes.ResultABCIInfo{res.(abci.ResponseInfo)}, nil } -func (m ABCIMock) ABCIQuery(path string, data []byte, prove bool) (*ctypes.ResultABCIQuery, error) { +func (m ABCIMock) ABCIQuery(path string, data data.Bytes, prove bool) (*ctypes.ResultABCIQuery, error) { res, err := m.Query.GetResponse(QueryArgs{path, data, prove}) if err != nil { return nil, err @@ -131,7 +132,7 @@ func (r *ABCIRecorder) _assertABCIClient() client.ABCIClient { type QueryArgs struct { Path string - Data []byte + Data data.Bytes Prove bool } @@ -149,7 +150,7 @@ func (r *ABCIRecorder) ABCIInfo() (*ctypes.ResultABCIInfo, error) { return res, err } -func (r *ABCIRecorder) ABCIQuery(path string, data []byte, prove bool) (*ctypes.ResultABCIQuery, error) { +func (r *ABCIRecorder) ABCIQuery(path string, data data.Bytes, prove bool) (*ctypes.ResultABCIQuery, error) { res, err := r.Client.ABCIQuery(path, data, prove) r.addCall(Call{ Name: "abci_query", diff --git a/rpc/client/mock/abci_test.go b/rpc/client/mock/abci_test.go index 823752caf..bb3a734a7 100644 --- a/rpc/client/mock/abci_test.go +++ b/rpc/client/mock/abci_test.go @@ -10,6 +10,7 @@ import ( "github.com/stretchr/testify/require" "github.com/tendermint/abci/example/dummy" abci "github.com/tendermint/abci/types" + data "github.com/tendermint/go-data" ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/types" @@ -35,8 +36,8 @@ func TestABCIMock(t *testing.T) { BroadcastCommit: mock.Call{ Args: goodTx, Response: &ctypes.ResultBroadcastTxCommit{ - CheckTx: &abci.ResponseCheckTx{Data: []byte("stand")}, - DeliverTx: &abci.ResponseDeliverTx{Data: []byte("deliver")}, + CheckTx: &abci.ResponseCheckTx{Data: data.Bytes("stand")}, + DeliverTx: &abci.ResponseDeliverTx{Data: data.Bytes("deliver")}, }, Error: errors.New("bad tx"), }, @@ -91,7 +92,7 @@ func TestABCIRecorder(t *testing.T) { require.Equal(0, len(r.Calls)) r.ABCIInfo() - r.ABCIQuery("path", []byte("data"), true) + r.ABCIQuery("path", data.Bytes("data"), true) require.Equal(2, len(r.Calls)) info := r.Calls[0] @@ -163,7 +164,7 @@ func TestABCIApp(t *testing.T) { assert.True(res.DeliverTx.Code.IsOK()) // check the key - qres, err := m.ABCIQuery("/key", []byte(key), false) + qres, err := m.ABCIQuery("/key", data.Bytes(key), false) require.Nil(err) assert.EqualValues(value, qres.Response.Value) } diff --git a/rpc/client/mock/client.go b/rpc/client/mock/client.go index a3cecfca1..478862380 100644 --- a/rpc/client/mock/client.go +++ b/rpc/client/mock/client.go @@ -16,6 +16,7 @@ package mock import ( "reflect" + data "github.com/tendermint/go-data" "github.com/tendermint/tendermint/rpc/client" "github.com/tendermint/tendermint/rpc/core" ctypes "github.com/tendermint/tendermint/rpc/core/types" @@ -83,7 +84,7 @@ func (c Client) ABCIInfo() (*ctypes.ResultABCIInfo, error) { return core.ABCIInfo() } -func (c Client) ABCIQuery(path string, data []byte, prove bool) (*ctypes.ResultABCIQuery, error) { +func (c Client) ABCIQuery(path string, data data.Bytes, prove bool) (*ctypes.ResultABCIQuery, error) { return core.ABCIQuery(path, data, prove) } diff --git a/rpc/client/mock/status_test.go b/rpc/client/mock/status_test.go index 3e695cd57..12edc8af0 100644 --- a/rpc/client/mock/status_test.go +++ b/rpc/client/mock/status_test.go @@ -5,6 +5,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + data "github.com/tendermint/go-data" ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/rpc/client/mock" @@ -16,8 +17,8 @@ func TestStatus(t *testing.T) { m := &mock.StatusMock{ Call: mock.Call{ Response: &ctypes.ResultStatus{ - LatestBlockHash: []byte("block"), - LatestAppHash: []byte("app"), + LatestBlockHash: data.Bytes("block"), + LatestAppHash: data.Bytes("app"), LatestBlockHeight: 10, }}, } diff --git a/rpc/core/abci.go b/rpc/core/abci.go index 957727267..47b599ada 100644 --- a/rpc/core/abci.go +++ b/rpc/core/abci.go @@ -2,12 +2,13 @@ package core import ( abci "github.com/tendermint/abci/types" + data "github.com/tendermint/go-data" ctypes "github.com/tendermint/tendermint/rpc/core/types" ) //----------------------------------------------------------------------------- -func ABCIQuery(path string, data []byte, prove bool) (*ctypes.ResultABCIQuery, error) { +func ABCIQuery(path string, data data.Bytes, prove bool) (*ctypes.ResultABCIQuery, error) { resQuery, err := proxyAppQuery.QuerySync(abci.RequestQuery{ Path: path, Data: data, diff --git a/rpc/core/mempool.go b/rpc/core/mempool.go index 4da83a1f6..358671635 100644 --- a/rpc/core/mempool.go +++ b/rpc/core/mempool.go @@ -5,6 +5,7 @@ import ( "time" abci "github.com/tendermint/abci/types" + data "github.com/tendermint/go-data" ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/types" ) @@ -84,7 +85,7 @@ func BroadcastTxCommit(tx types.Tx) (*ctypes.ResultBroadcastTxCommit, error) { Data: deliverTxRes.Data, Log: deliverTxRes.Log, } - log.Notice("DeliverTx passed ", "tx", []byte(tx), "response", deliverTxR) + log.Notice("DeliverTx passed ", "tx", data.Bytes(tx), "response", deliverTxR) return &ctypes.ResultBroadcastTxCommit{ CheckTx: checkTxR, DeliverTx: deliverTxR, diff --git a/rpc/core/routes.go b/rpc/core/routes.go index 38e609601..58b464208 100644 --- a/rpc/core/routes.go +++ b/rpc/core/routes.go @@ -1,9 +1,11 @@ package core import ( + data "github.com/tendermint/go-data" rpc "github.com/tendermint/go-rpc/server" "github.com/tendermint/go-rpc/types" ctypes "github.com/tendermint/tendermint/rpc/core/types" + "github.com/tendermint/tendermint/types" ) // TODO: better system than "unsafe" prefix @@ -104,19 +106,19 @@ func TxResult(hash []byte, prove bool) (ctypes.TMResult, error) { return Tx(hash, prove) } -func BroadcastTxCommitResult(tx []byte) (ctypes.TMResult, error) { +func BroadcastTxCommitResult(tx types.Tx) (ctypes.TMResult, error) { return BroadcastTxCommit(tx) } -func BroadcastTxSyncResult(tx []byte) (ctypes.TMResult, error) { +func BroadcastTxSyncResult(tx types.Tx) (ctypes.TMResult, error) { return BroadcastTxSync(tx) } -func BroadcastTxAsyncResult(tx []byte) (ctypes.TMResult, error) { +func BroadcastTxAsyncResult(tx types.Tx) (ctypes.TMResult, error) { return BroadcastTxAsync(tx) } -func ABCIQueryResult(path string, data []byte, prove bool) (ctypes.TMResult, error) { +func ABCIQueryResult(path string, data data.Bytes, prove bool) (ctypes.TMResult, error) { return ABCIQuery(path, data, prove) } diff --git a/rpc/core/status.go b/rpc/core/status.go index 96ed46ea6..d7d503802 100644 --- a/rpc/core/status.go +++ b/rpc/core/status.go @@ -1,6 +1,7 @@ package core import ( + data "github.com/tendermint/go-data" ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/types" ) @@ -9,8 +10,8 @@ func Status() (*ctypes.ResultStatus, error) { latestHeight := blockStore.Height() var ( latestBlockMeta *types.BlockMeta - latestBlockHash []byte - latestAppHash []byte + latestBlockHash data.Bytes + latestAppHash data.Bytes latestBlockTime int64 ) if latestHeight != 0 { diff --git a/rpc/core/types/responses.go b/rpc/core/types/responses.go index 7cab8535d..59fa09aa0 100644 --- a/rpc/core/types/responses.go +++ b/rpc/core/types/responses.go @@ -5,6 +5,7 @@ import ( abci "github.com/tendermint/abci/types" "github.com/tendermint/go-crypto" + data "github.com/tendermint/go-data" "github.com/tendermint/go-p2p" "github.com/tendermint/go-rpc/types" "github.com/tendermint/go-wire" @@ -34,8 +35,8 @@ type ResultCommit struct { type ResultStatus struct { NodeInfo *p2p.NodeInfo `json:"node_info"` PubKey crypto.PubKey `json:"pub_key"` - LatestBlockHash []byte `json:"latest_block_hash"` - LatestAppHash []byte `json:"latest_app_hash"` + LatestBlockHash data.Bytes `json:"latest_block_hash"` + LatestAppHash data.Bytes `json:"latest_app_hash"` LatestBlockHeight int `json:"latest_block_height"` LatestBlockTime int64 `json:"latest_block_time"` // nano } @@ -81,7 +82,7 @@ type ResultDumpConsensusState struct { type ResultBroadcastTx struct { Code abci.CodeType `json:"code"` - Data []byte `json:"data"` + Data data.Bytes `json:"data"` Log string `json:"log"` Hash []byte `json:"hash"` diff --git a/rpc/test/client_test.go b/rpc/test/client_test.go index 50e326050..a9792b5be 100644 --- a/rpc/test/client_test.go +++ b/rpc/test/client_test.go @@ -12,6 +12,7 @@ import ( "github.com/stretchr/testify/require" abci "github.com/tendermint/abci/types" . "github.com/tendermint/go-common" + data "github.com/tendermint/go-data" rpc "github.com/tendermint/go-rpc/client" "github.com/tendermint/tendermint/rpc/core" ctypes "github.com/tendermint/tendermint/rpc/core/types" @@ -85,10 +86,10 @@ func testBroadcastTxSync(t *testing.T, client rpc.HTTPClient) { //-------------------------------------------------------------------------------- // query -func testTxKV(t *testing.T) ([]byte, []byte, []byte) { +func testTxKV(t *testing.T) ([]byte, []byte, types.Tx) { k := randBytes(t) v := randBytes(t) - return k, v, []byte(Fmt("%s=%s", k, v)) + return k, v, types.Tx(Fmt("%s=%s", k, v)) } func sendTx(t *testing.T, client rpc.HTTPClient) ([]byte, []byte) { @@ -114,8 +115,6 @@ func testABCIQuery(t *testing.T, client rpc.HTTPClient) { _, err := client.Call("abci_query", map[string]interface{}{"path": "", "data": k, "prove": false}, tmResult) require.Nil(t, err) - - resQuery := (*tmResult).(*ctypes.ResultABCIQuery) require.EqualValues(t, 0, resQuery.Response.Code) // XXX: specific to value returned by the dummy From 3d9ca32e95c7dbd1715462eb4d8c6fc436bba7fe Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Wed, 22 Mar 2017 20:17:56 +0100 Subject: [PATCH 176/309] Update all config for p2p integration tests --- test/p2p/data/chain_config.json | 34 ++++++++++---------- test/p2p/data/mach1/core/genesis.json | 34 ++++++++++---------- test/p2p/data/mach1/core/priv_validator.json | 18 +++++------ test/p2p/data/mach2/core/genesis.json | 34 ++++++++++---------- test/p2p/data/mach2/core/priv_validator.json | 18 +++++------ test/p2p/data/mach3/core/genesis.json | 34 ++++++++++---------- test/p2p/data/mach3/core/priv_validator.json | 18 +++++------ test/p2p/data/mach4/core/genesis.json | 34 ++++++++++---------- test/p2p/data/mach4/core/priv_validator.json | 18 +++++------ 9 files changed, 121 insertions(+), 121 deletions(-) diff --git a/test/p2p/data/chain_config.json b/test/p2p/data/chain_config.json index 54fcea524..4221ba8da 100644 --- a/test/p2p/data/chain_config.json +++ b/test/p2p/data/chain_config.json @@ -5,10 +5,10 @@ { "validator": { "id": "mach1", - "pub_key": [ - 1, - "BE8933DFF1600C026E34718F1785A4CDEAB90C35698B394E38B6947AE91DE116" - ] + "pub_key": { + "type": "ed25519", + "data": "BE8933DFF1600C026E34718F1785A4CDEAB90C35698B394E38B6947AE91DE116" + } }, "p2p_addr": "", "rpc_addr": "" @@ -16,10 +16,10 @@ { "validator": { "id": "mach2", - "pub_key": [ - 1, - "6DC534465323126587D2A2A93B59D689B717073B1DE968A25A6EF13D595318AD" - ] + "pub_key": { + "type": "ed25519", + "data": "6DC534465323126587D2A2A93B59D689B717073B1DE968A25A6EF13D595318AD" + } }, "p2p_addr": "", "rpc_addr": "", @@ -28,10 +28,10 @@ { "validator": { "id": "mach3", - "pub_key": [ - 1, - "AE67AC697D135AA0B4601EA57EAAB3FEBF4BAA4F229C45A598C2985B12FCD1A1" - ] + "pub_key": { + "type": "ed25519", + "data": "AE67AC697D135AA0B4601EA57EAAB3FEBF4BAA4F229C45A598C2985B12FCD1A1" + } }, "p2p_addr": "", "rpc_addr": "", @@ -40,14 +40,14 @@ { "validator": { "id": "mach4", - "pub_key": [ - 1, - "9EBC8F58CED4B46DCD5AB8ABA591DD253CD7CB5037273FDA32BC0B6461C4EFD9" - ] + "pub_key": { + "type": "ed25519", + "data": "9EBC8F58CED4B46DCD5AB8ABA591DD253CD7CB5037273FDA32BC0B6461C4EFD9" + } }, "p2p_addr": "", "rpc_addr": "", "index": 3 } ] -} \ No newline at end of file +} diff --git a/test/p2p/data/mach1/core/genesis.json b/test/p2p/data/mach1/core/genesis.json index 3f6fbe5a2..522f9831a 100644 --- a/test/p2p/data/mach1/core/genesis.json +++ b/test/p2p/data/mach1/core/genesis.json @@ -6,34 +6,34 @@ { "amount": 1, "name": "mach1", - "pub_key": [ - 1, - "BE8933DFF1600C026E34718F1785A4CDEAB90C35698B394E38B6947AE91DE116" - ] + "pub_key": { + "type": "ed25519", + "data": "BE8933DFF1600C026E34718F1785A4CDEAB90C35698B394E38B6947AE91DE116" + } }, { "amount": 1, "name": "mach2", - "pub_key": [ - 1, - "6DC534465323126587D2A2A93B59D689B717073B1DE968A25A6EF13D595318AD" - ] + "pub_key": { + "type": "ed25519", + "data": "6DC534465323126587D2A2A93B59D689B717073B1DE968A25A6EF13D595318AD" + } }, { "amount": 1, "name": "mach3", - "pub_key": [ - 1, - "AE67AC697D135AA0B4601EA57EAAB3FEBF4BAA4F229C45A598C2985B12FCD1A1" - ] + "pub_key": { + "type": "ed25519", + "data": "AE67AC697D135AA0B4601EA57EAAB3FEBF4BAA4F229C45A598C2985B12FCD1A1" + } }, { "amount": 1, "name": "mach4", - "pub_key": [ - 1, - "9EBC8F58CED4B46DCD5AB8ABA591DD253CD7CB5037273FDA32BC0B6461C4EFD9" - ] + "pub_key": { + "type": "ed25519", + "data": "9EBC8F58CED4B46DCD5AB8ABA591DD253CD7CB5037273FDA32BC0B6461C4EFD9" + } } ] -} \ No newline at end of file +} diff --git a/test/p2p/data/mach1/core/priv_validator.json b/test/p2p/data/mach1/core/priv_validator.json index 242c7b9fc..6538281b4 100644 --- a/test/p2p/data/mach1/core/priv_validator.json +++ b/test/p2p/data/mach1/core/priv_validator.json @@ -3,12 +3,12 @@ "last_height": 0, "last_round": 0, "last_step": 0, - "priv_key": [ - 1, - "547AA07C7A8CE16C5CB2A40C6C26D15B0A32960410A9F1EA6E50B636F1AB389ABE8933DFF1600C026E34718F1785A4CDEAB90C35698B394E38B6947AE91DE116" - ], - "pub_key": [ - 1, - "BE8933DFF1600C026E34718F1785A4CDEAB90C35698B394E38B6947AE91DE116" - ] -} \ No newline at end of file + "priv_key": { + "type": "ed25519", + "data": "547AA07C7A8CE16C5CB2A40C6C26D15B0A32960410A9F1EA6E50B636F1AB389ABE8933DFF1600C026E34718F1785A4CDEAB90C35698B394E38B6947AE91DE116" + }, + "pub_key": { + "type": "ed25519", + "data": "BE8933DFF1600C026E34718F1785A4CDEAB90C35698B394E38B6947AE91DE116" + } +} diff --git a/test/p2p/data/mach2/core/genesis.json b/test/p2p/data/mach2/core/genesis.json index 3f6fbe5a2..522f9831a 100644 --- a/test/p2p/data/mach2/core/genesis.json +++ b/test/p2p/data/mach2/core/genesis.json @@ -6,34 +6,34 @@ { "amount": 1, "name": "mach1", - "pub_key": [ - 1, - "BE8933DFF1600C026E34718F1785A4CDEAB90C35698B394E38B6947AE91DE116" - ] + "pub_key": { + "type": "ed25519", + "data": "BE8933DFF1600C026E34718F1785A4CDEAB90C35698B394E38B6947AE91DE116" + } }, { "amount": 1, "name": "mach2", - "pub_key": [ - 1, - "6DC534465323126587D2A2A93B59D689B717073B1DE968A25A6EF13D595318AD" - ] + "pub_key": { + "type": "ed25519", + "data": "6DC534465323126587D2A2A93B59D689B717073B1DE968A25A6EF13D595318AD" + } }, { "amount": 1, "name": "mach3", - "pub_key": [ - 1, - "AE67AC697D135AA0B4601EA57EAAB3FEBF4BAA4F229C45A598C2985B12FCD1A1" - ] + "pub_key": { + "type": "ed25519", + "data": "AE67AC697D135AA0B4601EA57EAAB3FEBF4BAA4F229C45A598C2985B12FCD1A1" + } }, { "amount": 1, "name": "mach4", - "pub_key": [ - 1, - "9EBC8F58CED4B46DCD5AB8ABA591DD253CD7CB5037273FDA32BC0B6461C4EFD9" - ] + "pub_key": { + "type": "ed25519", + "data": "9EBC8F58CED4B46DCD5AB8ABA591DD253CD7CB5037273FDA32BC0B6461C4EFD9" + } } ] -} \ No newline at end of file +} diff --git a/test/p2p/data/mach2/core/priv_validator.json b/test/p2p/data/mach2/core/priv_validator.json index ead45d5e6..3602454f5 100644 --- a/test/p2p/data/mach2/core/priv_validator.json +++ b/test/p2p/data/mach2/core/priv_validator.json @@ -3,12 +3,12 @@ "last_height": 0, "last_round": 0, "last_step": 0, - "priv_key": [ - 1, - "D047889E60502FC3129D0AB7F334B1838ED9ED1ECD99CBB96B71AD5ABF5A81436DC534465323126587D2A2A93B59D689B717073B1DE968A25A6EF13D595318AD" - ], - "pub_key": [ - 1, - "6DC534465323126587D2A2A93B59D689B717073B1DE968A25A6EF13D595318AD" - ] -} \ No newline at end of file + "priv_key": { + "type": "ed25519", + "data": "D047889E60502FC3129D0AB7F334B1838ED9ED1ECD99CBB96B71AD5ABF5A81436DC534465323126587D2A2A93B59D689B717073B1DE968A25A6EF13D595318AD" + }, + "pub_key": { + "type": "ed25519", + "data": "6DC534465323126587D2A2A93B59D689B717073B1DE968A25A6EF13D595318AD" + } +} diff --git a/test/p2p/data/mach3/core/genesis.json b/test/p2p/data/mach3/core/genesis.json index 3f6fbe5a2..522f9831a 100644 --- a/test/p2p/data/mach3/core/genesis.json +++ b/test/p2p/data/mach3/core/genesis.json @@ -6,34 +6,34 @@ { "amount": 1, "name": "mach1", - "pub_key": [ - 1, - "BE8933DFF1600C026E34718F1785A4CDEAB90C35698B394E38B6947AE91DE116" - ] + "pub_key": { + "type": "ed25519", + "data": "BE8933DFF1600C026E34718F1785A4CDEAB90C35698B394E38B6947AE91DE116" + } }, { "amount": 1, "name": "mach2", - "pub_key": [ - 1, - "6DC534465323126587D2A2A93B59D689B717073B1DE968A25A6EF13D595318AD" - ] + "pub_key": { + "type": "ed25519", + "data": "6DC534465323126587D2A2A93B59D689B717073B1DE968A25A6EF13D595318AD" + } }, { "amount": 1, "name": "mach3", - "pub_key": [ - 1, - "AE67AC697D135AA0B4601EA57EAAB3FEBF4BAA4F229C45A598C2985B12FCD1A1" - ] + "pub_key": { + "type": "ed25519", + "data": "AE67AC697D135AA0B4601EA57EAAB3FEBF4BAA4F229C45A598C2985B12FCD1A1" + } }, { "amount": 1, "name": "mach4", - "pub_key": [ - 1, - "9EBC8F58CED4B46DCD5AB8ABA591DD253CD7CB5037273FDA32BC0B6461C4EFD9" - ] + "pub_key": { + "type": "ed25519", + "data": "9EBC8F58CED4B46DCD5AB8ABA591DD253CD7CB5037273FDA32BC0B6461C4EFD9" + } } ] -} \ No newline at end of file +} diff --git a/test/p2p/data/mach3/core/priv_validator.json b/test/p2p/data/mach3/core/priv_validator.json index dd366d205..743a931f5 100644 --- a/test/p2p/data/mach3/core/priv_validator.json +++ b/test/p2p/data/mach3/core/priv_validator.json @@ -3,12 +3,12 @@ "last_height": 0, "last_round": 0, "last_step": 0, - "priv_key": [ - 1, - "C1A4E47F349FC5F556F4A9A27BA776B94424C312BAA6CF6EE44B867348D7C3F2AE67AC697D135AA0B4601EA57EAAB3FEBF4BAA4F229C45A598C2985B12FCD1A1" - ], - "pub_key": [ - 1, - "AE67AC697D135AA0B4601EA57EAAB3FEBF4BAA4F229C45A598C2985B12FCD1A1" - ] -} \ No newline at end of file + "priv_key": { + "type": "ed25519", + "data": "C1A4E47F349FC5F556F4A9A27BA776B94424C312BAA6CF6EE44B867348D7C3F2AE67AC697D135AA0B4601EA57EAAB3FEBF4BAA4F229C45A598C2985B12FCD1A1" + }, + "pub_key": { + "type": "ed25519", + "data": "AE67AC697D135AA0B4601EA57EAAB3FEBF4BAA4F229C45A598C2985B12FCD1A1" + } +} diff --git a/test/p2p/data/mach4/core/genesis.json b/test/p2p/data/mach4/core/genesis.json index 3f6fbe5a2..522f9831a 100644 --- a/test/p2p/data/mach4/core/genesis.json +++ b/test/p2p/data/mach4/core/genesis.json @@ -6,34 +6,34 @@ { "amount": 1, "name": "mach1", - "pub_key": [ - 1, - "BE8933DFF1600C026E34718F1785A4CDEAB90C35698B394E38B6947AE91DE116" - ] + "pub_key": { + "type": "ed25519", + "data": "BE8933DFF1600C026E34718F1785A4CDEAB90C35698B394E38B6947AE91DE116" + } }, { "amount": 1, "name": "mach2", - "pub_key": [ - 1, - "6DC534465323126587D2A2A93B59D689B717073B1DE968A25A6EF13D595318AD" - ] + "pub_key": { + "type": "ed25519", + "data": "6DC534465323126587D2A2A93B59D689B717073B1DE968A25A6EF13D595318AD" + } }, { "amount": 1, "name": "mach3", - "pub_key": [ - 1, - "AE67AC697D135AA0B4601EA57EAAB3FEBF4BAA4F229C45A598C2985B12FCD1A1" - ] + "pub_key": { + "type": "ed25519", + "data": "AE67AC697D135AA0B4601EA57EAAB3FEBF4BAA4F229C45A598C2985B12FCD1A1" + } }, { "amount": 1, "name": "mach4", - "pub_key": [ - 1, - "9EBC8F58CED4B46DCD5AB8ABA591DD253CD7CB5037273FDA32BC0B6461C4EFD9" - ] + "pub_key": { + "type": "ed25519", + "data": "9EBC8F58CED4B46DCD5AB8ABA591DD253CD7CB5037273FDA32BC0B6461C4EFD9" + } } ] -} \ No newline at end of file +} diff --git a/test/p2p/data/mach4/core/priv_validator.json b/test/p2p/data/mach4/core/priv_validator.json index 4a73707e8..1c10eb8a6 100644 --- a/test/p2p/data/mach4/core/priv_validator.json +++ b/test/p2p/data/mach4/core/priv_validator.json @@ -3,12 +3,12 @@ "last_height": 0, "last_round": 0, "last_step": 0, - "priv_key": [ - 1, - "C4CC3ED28F020C2DBDA98BCDBF08C3CED370470E74F25E938D5D295E8E3D2B0C9EBC8F58CED4B46DCD5AB8ABA591DD253CD7CB5037273FDA32BC0B6461C4EFD9" - ], - "pub_key": [ - 1, - "9EBC8F58CED4B46DCD5AB8ABA591DD253CD7CB5037273FDA32BC0B6461C4EFD9" - ] -} \ No newline at end of file + "priv_key": { + "type": "ed25519", + "data": "C4CC3ED28F020C2DBDA98BCDBF08C3CED370470E74F25E938D5D295E8E3D2B0C9EBC8F58CED4B46DCD5AB8ABA591DD253CD7CB5037273FDA32BC0B6461C4EFD9" + }, + "pub_key": { + "type": "ed25519", + "data": "9EBC8F58CED4B46DCD5AB8ABA591DD253CD7CB5037273FDA32BC0B6461C4EFD9" + } +} From 6d223d552694b4709d4aec5b8d548e47a77ce098 Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Mon, 10 Apr 2017 16:15:41 +0200 Subject: [PATCH 177/309] Update to latest go-crypto --- glide.lock | 14 +++++++------- glide.yaml | 2 +- types/priv_validator.go | 2 +- types/validator_set_test.go | 2 +- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/glide.lock b/glide.lock index 5bddeea33..9bd333507 100644 --- a/glide.lock +++ b/glide.lock @@ -1,5 +1,5 @@ -hash: d9724aa287c40d1b3856b6565f09235d809c8b2f7c6537c04f597137c0d6cd26 -updated: 2017-04-21T13:09:25.708801802-04:00 +hash: 4fcbf7902a356824c9b4d4de99ccc62175ef3be8b610987dcf4a37eae9ed64f5 +updated: 2017-04-10T15:48:51.218742111+02:00 imports: - name: github.com/btcsuite/btcd version: 4b348c1d33373d672edd83fc576892d0e46686d2 @@ -67,7 +67,7 @@ imports: - leveldb/table - leveldb/util - name: github.com/tendermint/abci - version: 56e13d87f4e3ec1ea756957d6b23caa6ebcf0998 + version: af792eac777de757cd496349a5f6b5313738fcbc subpackages: - client - example/counter @@ -84,15 +84,15 @@ imports: - name: github.com/tendermint/go-clist version: 3baa390bbaf7634251c42ad69a8682e7e3990552 - name: github.com/tendermint/go-common - version: f9e3db037330c8a8d61d3966de8473eaf01154fa + version: 6af2364fa91ef2f3afc8ba0db33b66d9d3ae006c subpackages: - test - name: github.com/tendermint/go-config version: 620dcbbd7d587cf3599dedbf329b64311b0c307a - name: github.com/tendermint/go-crypto - version: 67c7682135e7e9a8c56a7eeae9ac885d342a3315 + version: 51791d8de6414468dc068b48d750e923bd269432 - name: github.com/tendermint/go-data - version: 3a135dc080d4304da75b57806f0f83a2ea9d40f8 + version: e7fcc6d081ec8518912fcdc103188275f83a3ee5 - name: github.com/tendermint/go-db version: 9643f60bc2578693844aacf380a7c32e4c029fee - name: github.com/tendermint/go-events @@ -106,7 +106,7 @@ imports: - name: github.com/tendermint/go-merkle version: 714d4d04557fd068a7c2a1748241ce8428015a96 - name: github.com/tendermint/go-p2p - version: a163fddbdd2541793d22402afb113e6ccb391774 + version: bc930547797de88267a3a22b15ce37c3eee2215f subpackages: - upnp - name: github.com/tendermint/go-rpc diff --git a/glide.yaml b/glide.yaml index cdb083e69..b2afd6203 100644 --- a/glide.yaml +++ b/glide.yaml @@ -21,7 +21,7 @@ import: - package: github.com/tendermint/go-merkle version: develop - package: github.com/tendermint/go-p2p - version: develop + version: feature/improve-godata - package: github.com/tendermint/go-rpc version: develop - package: github.com/tendermint/go-wire diff --git a/types/priv_validator.go b/types/priv_validator.go index ed6313b81..6798f64be 100644 --- a/types/priv_validator.go +++ b/types/priv_validator.go @@ -80,7 +80,7 @@ func (privVal *PrivValidator) SetSigner(s Signer) { // Generates a new validator with private key. func GenPrivValidator() *PrivValidator { - privKey := crypto.WrapPrivKey(crypto.GenPrivKeyEd25519()) + privKey := crypto.GenPrivKeyEd25519().Wrap() pubKey := privKey.PubKey() return &PrivValidator{ Address: pubKey.Address(), diff --git a/types/validator_set_test.go b/types/validator_set_test.go index b918b8d5f..6cd048cc3 100644 --- a/types/validator_set_test.go +++ b/types/validator_set_test.go @@ -12,7 +12,7 @@ import ( func randPubKey() crypto.PubKey { var pubKey [32]byte copy(pubKey[:], cmn.RandBytes(32)) - return crypto.WrapPubKey(crypto.PubKeyEd25519(pubKey)) + return crypto.PubKeyEd25519(pubKey).Wrap() } func randValidator_() *Validator { From 543eea4f4edf7123f5cdd2010157142d5726aa8c Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Mon, 10 Apr 2017 20:20:25 +0200 Subject: [PATCH 178/309] update deps to unstable --- glide.lock | 4 ++-- glide.yaml | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/glide.lock b/glide.lock index 9bd333507..2050c5d28 100644 --- a/glide.lock +++ b/glide.lock @@ -90,7 +90,7 @@ imports: - name: github.com/tendermint/go-config version: 620dcbbd7d587cf3599dedbf329b64311b0c307a - name: github.com/tendermint/go-crypto - version: 51791d8de6414468dc068b48d750e923bd269432 + version: c410fc5e246e9accf95c6e80cb3c6aca2280755c - name: github.com/tendermint/go-data version: e7fcc6d081ec8518912fcdc103188275f83a3ee5 - name: github.com/tendermint/go-db @@ -106,7 +106,7 @@ imports: - name: github.com/tendermint/go-merkle version: 714d4d04557fd068a7c2a1748241ce8428015a96 - name: github.com/tendermint/go-p2p - version: bc930547797de88267a3a22b15ce37c3eee2215f + version: b5f314ffed65c81bd019ba1dd2bae0e95f3937f3 subpackages: - upnp - name: github.com/tendermint/go-rpc diff --git a/glide.yaml b/glide.yaml index b2afd6203..03f328722 100644 --- a/glide.yaml +++ b/glide.yaml @@ -21,7 +21,7 @@ import: - package: github.com/tendermint/go-merkle version: develop - package: github.com/tendermint/go-p2p - version: feature/improve-godata + version: unstable - package: github.com/tendermint/go-rpc version: develop - package: github.com/tendermint/go-wire From 3240ce21b845655cf9f50f9e052d71c52c130240 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 21 Apr 2017 17:28:13 -0400 Subject: [PATCH 179/309] update glide --- glide.lock | 63 +++++++++++++++++++---------------------- rpc/test/client_test.go | 8 ++++-- 2 files changed, 34 insertions(+), 37 deletions(-) diff --git a/glide.lock b/glide.lock index 2050c5d28..9e59179b3 100644 --- a/glide.lock +++ b/glide.lock @@ -1,12 +1,12 @@ -hash: 4fcbf7902a356824c9b4d4de99ccc62175ef3be8b610987dcf4a37eae9ed64f5 -updated: 2017-04-10T15:48:51.218742111+02:00 +hash: 7fc53c3edfe508d56a5f2241ab73cef88652cbc40036ca2598730619edac7740 +updated: 2017-04-21T16:57:57.932584858-04:00 imports: - name: github.com/btcsuite/btcd - version: 4b348c1d33373d672edd83fc576892d0e46686d2 + version: 583684b21bfbde9b5fc4403916fd7c807feb0289 subpackages: - btcec - name: github.com/BurntSushi/toml - version: b26d9c308763d68093482582cea63d69be07a0f0 + version: 99064174e013895bbd9b025c31100bd1d9b590ca - name: github.com/davecgh/go-spew version: 6d212800a42e8ab5c146b8ace3490ee17e5225f9 subpackages: @@ -20,12 +20,11 @@ imports: subpackages: - proto - name: github.com/golang/protobuf - version: 2bba0603135d7d7f5cb73b2125beeda19c09f4ef + version: 8ee79997227bf9b34611aee7946ae64735e6fd93 subpackages: - proto - - ptypes/any - name: github.com/golang/snappy - version: 553a641470496b2327abcac10b36396bd98e45c9 + version: d9eb7a3d35ec988b8585d4a0068e462c27d28380 - name: github.com/gorilla/websocket version: 3ab3a8b8831546bd18fd182c20687ca853b2bb13 - name: github.com/inconshreveable/mousetrap @@ -33,9 +32,9 @@ imports: - name: github.com/jmhodges/levigo version: c42d9e0ca023e2198120196f842701bb4c55d7b9 - name: github.com/mattn/go-colorable - version: ded68f7a9561c023e790de24279db7ebf473ea80 + version: d228849504861217f796da67fae4f6e347643f15 - name: github.com/mattn/go-isatty - version: fc9e8d8ef48496124e79ae0df75490096eccf6fe + version: 30a891c33c7cde7b02a981314b4228ec99380cca - name: github.com/pkg/errors version: 645ef00459ed84a119197bfb8d8205042c6df63d - name: github.com/pmezard/go-difflib @@ -43,16 +42,16 @@ imports: subpackages: - difflib - name: github.com/spf13/cobra - version: 10f6b9d7e1631a54ad07c5c0fb71c28a1abfd3c2 + version: fcd0c5a1df88f5d6784cb4feead962c3f3d0b66c - name: github.com/spf13/pflag - version: 2300d0f8576fe575f71aaa5b9bbe4e1b0dc2eb51 + version: 9ff6c6923cfffbcd502984b8e0c80539a94968b7 - name: github.com/stretchr/testify version: 69483b4bd14f5845b5a1e55bca19e954e827f1d0 subpackages: - assert - require - name: github.com/syndtr/goleveldb - version: 8c81ea47d4c41a385645e133e15510fc6a2a74b4 + version: 23851d93a2292dcc56e71a18ec9e0624d84a0f65 subpackages: - leveldb - leveldb/cache @@ -67,7 +66,7 @@ imports: - leveldb/table - leveldb/util - name: github.com/tendermint/abci - version: af792eac777de757cd496349a5f6b5313738fcbc + version: 56e13d87f4e3ec1ea756957d6b23caa6ebcf0998 subpackages: - client - example/counter @@ -84,13 +83,13 @@ imports: - name: github.com/tendermint/go-clist version: 3baa390bbaf7634251c42ad69a8682e7e3990552 - name: github.com/tendermint/go-common - version: 6af2364fa91ef2f3afc8ba0db33b66d9d3ae006c + version: f9e3db037330c8a8d61d3966de8473eaf01154fa subpackages: - test - name: github.com/tendermint/go-config version: 620dcbbd7d587cf3599dedbf329b64311b0c307a - name: github.com/tendermint/go-crypto - version: c410fc5e246e9accf95c6e80cb3c6aca2280755c + version: 9b95da8fa4187f6799558d89b271dc8ab6485615 - name: github.com/tendermint/go-data version: e7fcc6d081ec8518912fcdc103188275f83a3ee5 - name: github.com/tendermint/go-db @@ -116,19 +115,28 @@ imports: - server - types - name: github.com/tendermint/go-wire - version: c1c9a57ab8038448ddea1714c0698f8051e5748c + version: 334005c236d19c632fb5f073f9de3b0fab6a522b + subpackages: + - data - name: github.com/tendermint/log15 version: ae0f3d6450da9eac7074b439c8e1c3cabf0d5ce6 subpackages: - term - name: github.com/tendermint/merkleeyes - version: 9fb76efa5aebe773a598f97e68e75fe53d520e70 + version: 742c791e1b412ef0f2016a2d53647b58e40c8964 subpackages: - app - client + - iavl - testutil +- name: github.com/tendermint/tmlibs + version: df250b69416a35a943a6e2a92118667e9ef031d4 + subpackages: + - common + - db + - logger - name: golang.org/x/crypto - version: 96846453c37f0876340a66a47f3f75b1f3a6cd2d + version: 7c6cc321c680f03b9ef0764448e780704f486b51 subpackages: - curve25519 - nacl/box @@ -139,7 +147,7 @@ imports: - ripemd160 - salsa20/salsa - name: golang.org/x/net - version: c8c74377599bd978aee1cf3b9b63a8634051cec2 + version: 61557ac0112b576429a0df080e1c2cef5dfbb642 subpackages: - context - http2 @@ -149,33 +157,20 @@ imports: - lex/httplex - trace - name: golang.org/x/sys - version: ea9bcade75cb975a0b9738936568ab388b845617 + version: d75a52659825e75fff6158388dddc6a5b04f9ba5 subpackages: - unix -- name: golang.org/x/text - version: 19e3104b43db45fca0303f489a9536087b184802 - subpackages: - - secure/bidirule - - transform - - unicode/bidi - - unicode/norm -- name: google.golang.org/genproto - version: 411e09b969b1170a9f0c467558eb4c4c110d9c77 - subpackages: - - googleapis/rpc/status - name: google.golang.org/grpc - version: 6914ab1e338c92da4218a23d27fcd03d0ad78d46 + version: cbcceb2942a489498cf22b2f918536e819d33f0a subpackages: - codes - credentials - grpclog - internal - - keepalive - metadata - naming - peer - stats - - status - tap - transport testImports: [] diff --git a/rpc/test/client_test.go b/rpc/test/client_test.go index a9792b5be..747c5c3cb 100644 --- a/rpc/test/client_test.go +++ b/rpc/test/client_test.go @@ -12,7 +12,6 @@ import ( "github.com/stretchr/testify/require" abci "github.com/tendermint/abci/types" . "github.com/tendermint/go-common" - data "github.com/tendermint/go-data" rpc "github.com/tendermint/go-rpc/client" "github.com/tendermint/tendermint/rpc/core" ctypes "github.com/tendermint/tendermint/rpc/core/types" @@ -95,7 +94,8 @@ func testTxKV(t *testing.T) ([]byte, []byte, types.Tx) { func sendTx(t *testing.T, client rpc.HTTPClient) ([]byte, []byte) { tmResult := new(ctypes.TMResult) k, v, tx := testTxKV(t) - _, err := client.Call("broadcast_tx_commit", map[string]interface{}{"tx": tx}, tmResult) + txBytes := []byte(tx) // XXX + _, err := client.Call("broadcast_tx_commit", map[string]interface{}{"tx": txBytes}, tmResult) require.Nil(t, err) return k, v } @@ -110,11 +110,13 @@ func TestJSONABCIQuery(t *testing.T) { func testABCIQuery(t *testing.T, client rpc.HTTPClient) { k, _ := sendTx(t, client) - time.Sleep(time.Millisecond * 100) + time.Sleep(time.Millisecond * 500) tmResult := new(ctypes.TMResult) _, err := client.Call("abci_query", map[string]interface{}{"path": "", "data": k, "prove": false}, tmResult) require.Nil(t, err) + + resQuery := (*tmResult).(*ctypes.ResultABCIQuery) require.EqualValues(t, 0, resQuery.Response.Code) // XXX: specific to value returned by the dummy From 0017fb7ffe947ddbcd9eff0ffc5089600296b119 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 21 Apr 2017 17:38:40 -0400 Subject: [PATCH 180/309] premerge --- CHANGELOG.md => premerge/CHANGELOG.md | 0 CONTRIBUTING.md => premerge/CONTRIBUTING.md | 0 INSTALL.md => premerge/INSTALL.md | 0 LICENSE => premerge/LICENSE | 0 Makefile => premerge/Makefile | 0 README.md => premerge/README.md | 0 Vagrantfile => premerge/Vagrantfile | 0 circle.yml => premerge/circle.yml | 0 glide.lock => premerge/glide.lock | 0 glide.yaml => premerge/glide.yaml | 0 {test => premerge/test}/README.md | 0 {test => premerge/test}/app/clean.sh | 0 {test => premerge/test}/app/counter_test.sh | 0 {test => premerge/test}/app/dummy_test.sh | 0 {test => premerge/test}/app/grpc_client.go | 0 {test => premerge/test}/app/test.sh | 0 {test => premerge/test}/docker/Dockerfile | 0 {test => premerge/test}/docker/build.sh | 0 {test => premerge/test}/docker/update.sh | 0 {test => premerge/test}/net/setup.sh | 0 {test => premerge/test}/net/start.sh | 0 {test => premerge/test}/net/test.sh | 0 {test => premerge/test}/p2p/README.md | 0 {test => premerge/test}/p2p/atomic_broadcast/test.sh | 0 {test => premerge/test}/p2p/basic/test.sh | 0 {test => premerge/test}/p2p/clean.sh | 0 {test => premerge/test}/p2p/client.sh | 0 {test => premerge/test}/p2p/data/app/init.sh | 0 {test => premerge/test}/p2p/data/chain_config.json | 0 {test => premerge/test}/p2p/data/core/init.sh | 0 {test => premerge/test}/p2p/data/data/init.sh | 0 {test => premerge/test}/p2p/data/mach1/core/genesis.json | 0 {test => premerge/test}/p2p/data/mach1/core/priv_validator.json | 0 {test => premerge/test}/p2p/data/mach2/core/genesis.json | 0 {test => premerge/test}/p2p/data/mach2/core/priv_validator.json | 0 {test => premerge/test}/p2p/data/mach3/core/genesis.json | 0 {test => premerge/test}/p2p/data/mach3/core/priv_validator.json | 0 {test => premerge/test}/p2p/data/mach4/core/genesis.json | 0 {test => premerge/test}/p2p/data/mach4/core/priv_validator.json | 0 {test => premerge/test}/p2p/fast_sync/check_peer.sh | 0 {test => premerge/test}/p2p/fast_sync/test.sh | 0 {test => premerge/test}/p2p/fast_sync/test_peer.sh | 0 {test => premerge/test}/p2p/ip.sh | 0 {test => premerge/test}/p2p/kill_all/check_peers.sh | 0 {test => premerge/test}/p2p/kill_all/test.sh | 0 {test => premerge/test}/p2p/local_testnet_start.sh | 0 {test => premerge/test}/p2p/local_testnet_stop.sh | 0 {test => premerge/test}/p2p/peer.sh | 0 {test => premerge/test}/p2p/pex/check_peer.sh | 0 {test => premerge/test}/p2p/pex/dial_seeds.sh | 0 {test => premerge/test}/p2p/pex/test.sh | 0 {test => premerge/test}/p2p/pex/test_addrbook.sh | 0 {test => premerge/test}/p2p/pex/test_dial_seeds.sh | 0 {test => premerge/test}/p2p/seeds.sh | 0 {test => premerge/test}/p2p/test.sh | 0 {test => premerge/test}/persist/test.sh | 0 {test => premerge/test}/persist/test_failure_indices.sh | 0 {test => premerge/test}/persist/test_simple.sh | 0 {test => premerge/test}/run_test.sh | 0 {test => premerge/test}/test.sh | 0 {test => premerge/test}/test_cover.sh | 0 {test => premerge/test}/test_libs.sh | 0 {test => premerge/test}/utils/txs.sh | 0 {types => premerge/types}/block.go | 0 {types => premerge/types}/block_meta.go | 0 {types => premerge/types}/canonical_json.go | 0 {types => premerge/types}/events.go | 0 {types => premerge/types}/genesis.go | 0 {types => premerge/types}/keys.go | 0 {types => premerge/types}/log.go | 0 {types => premerge/types}/part_set.go | 0 {types => premerge/types}/part_set_test.go | 0 {types => premerge/types}/priv_validator.go | 0 {types => premerge/types}/priv_validator_test.go | 0 {types => premerge/types}/proposal.go | 0 {types => premerge/types}/proposal_test.go | 0 {types => premerge/types}/protobuf.go | 0 {types => premerge/types}/services.go | 0 {types => premerge/types}/signable.go | 0 {types => premerge/types}/tx.go | 0 {types => premerge/types}/tx_test.go | 0 {types => premerge/types}/validator.go | 0 {types => premerge/types}/validator_set.go | 0 {types => premerge/types}/validator_set_test.go | 0 {types => premerge/types}/vote.go | 0 {types => premerge/types}/vote_set.go | 0 {types => premerge/types}/vote_set_test.go | 0 {types => premerge/types}/vote_test.go | 0 88 files changed, 0 insertions(+), 0 deletions(-) rename CHANGELOG.md => premerge/CHANGELOG.md (100%) rename CONTRIBUTING.md => premerge/CONTRIBUTING.md (100%) rename INSTALL.md => premerge/INSTALL.md (100%) rename LICENSE => premerge/LICENSE (100%) rename Makefile => premerge/Makefile (100%) rename README.md => premerge/README.md (100%) rename Vagrantfile => premerge/Vagrantfile (100%) rename circle.yml => premerge/circle.yml (100%) rename glide.lock => premerge/glide.lock (100%) rename glide.yaml => premerge/glide.yaml (100%) rename {test => premerge/test}/README.md (100%) rename {test => premerge/test}/app/clean.sh (100%) rename {test => premerge/test}/app/counter_test.sh (100%) rename {test => premerge/test}/app/dummy_test.sh (100%) rename {test => premerge/test}/app/grpc_client.go (100%) rename {test => premerge/test}/app/test.sh (100%) rename {test => premerge/test}/docker/Dockerfile (100%) rename {test => premerge/test}/docker/build.sh (100%) rename {test => premerge/test}/docker/update.sh (100%) rename {test => premerge/test}/net/setup.sh (100%) rename {test => premerge/test}/net/start.sh (100%) rename {test => premerge/test}/net/test.sh (100%) rename {test => premerge/test}/p2p/README.md (100%) rename {test => premerge/test}/p2p/atomic_broadcast/test.sh (100%) rename {test => premerge/test}/p2p/basic/test.sh (100%) rename {test => premerge/test}/p2p/clean.sh (100%) rename {test => premerge/test}/p2p/client.sh (100%) rename {test => premerge/test}/p2p/data/app/init.sh (100%) rename {test => premerge/test}/p2p/data/chain_config.json (100%) rename {test => premerge/test}/p2p/data/core/init.sh (100%) rename {test => premerge/test}/p2p/data/data/init.sh (100%) rename {test => premerge/test}/p2p/data/mach1/core/genesis.json (100%) rename {test => premerge/test}/p2p/data/mach1/core/priv_validator.json (100%) rename {test => premerge/test}/p2p/data/mach2/core/genesis.json (100%) rename {test => premerge/test}/p2p/data/mach2/core/priv_validator.json (100%) rename {test => premerge/test}/p2p/data/mach3/core/genesis.json (100%) rename {test => premerge/test}/p2p/data/mach3/core/priv_validator.json (100%) rename {test => premerge/test}/p2p/data/mach4/core/genesis.json (100%) rename {test => premerge/test}/p2p/data/mach4/core/priv_validator.json (100%) rename {test => premerge/test}/p2p/fast_sync/check_peer.sh (100%) rename {test => premerge/test}/p2p/fast_sync/test.sh (100%) rename {test => premerge/test}/p2p/fast_sync/test_peer.sh (100%) rename {test => premerge/test}/p2p/ip.sh (100%) rename {test => premerge/test}/p2p/kill_all/check_peers.sh (100%) rename {test => premerge/test}/p2p/kill_all/test.sh (100%) rename {test => premerge/test}/p2p/local_testnet_start.sh (100%) rename {test => premerge/test}/p2p/local_testnet_stop.sh (100%) rename {test => premerge/test}/p2p/peer.sh (100%) rename {test => premerge/test}/p2p/pex/check_peer.sh (100%) rename {test => premerge/test}/p2p/pex/dial_seeds.sh (100%) rename {test => premerge/test}/p2p/pex/test.sh (100%) rename {test => premerge/test}/p2p/pex/test_addrbook.sh (100%) rename {test => premerge/test}/p2p/pex/test_dial_seeds.sh (100%) rename {test => premerge/test}/p2p/seeds.sh (100%) rename {test => premerge/test}/p2p/test.sh (100%) rename {test => premerge/test}/persist/test.sh (100%) rename {test => premerge/test}/persist/test_failure_indices.sh (100%) rename {test => premerge/test}/persist/test_simple.sh (100%) rename {test => premerge/test}/run_test.sh (100%) rename {test => premerge/test}/test.sh (100%) rename {test => premerge/test}/test_cover.sh (100%) rename {test => premerge/test}/test_libs.sh (100%) rename {test => premerge/test}/utils/txs.sh (100%) rename {types => premerge/types}/block.go (100%) rename {types => premerge/types}/block_meta.go (100%) rename {types => premerge/types}/canonical_json.go (100%) rename {types => premerge/types}/events.go (100%) rename {types => premerge/types}/genesis.go (100%) rename {types => premerge/types}/keys.go (100%) rename {types => premerge/types}/log.go (100%) rename {types => premerge/types}/part_set.go (100%) rename {types => premerge/types}/part_set_test.go (100%) rename {types => premerge/types}/priv_validator.go (100%) rename {types => premerge/types}/priv_validator_test.go (100%) rename {types => premerge/types}/proposal.go (100%) rename {types => premerge/types}/proposal_test.go (100%) rename {types => premerge/types}/protobuf.go (100%) rename {types => premerge/types}/services.go (100%) rename {types => premerge/types}/signable.go (100%) rename {types => premerge/types}/tx.go (100%) rename {types => premerge/types}/tx_test.go (100%) rename {types => premerge/types}/validator.go (100%) rename {types => premerge/types}/validator_set.go (100%) rename {types => premerge/types}/validator_set_test.go (100%) rename {types => premerge/types}/vote.go (100%) rename {types => premerge/types}/vote_set.go (100%) rename {types => premerge/types}/vote_set_test.go (100%) rename {types => premerge/types}/vote_test.go (100%) diff --git a/CHANGELOG.md b/premerge/CHANGELOG.md similarity index 100% rename from CHANGELOG.md rename to premerge/CHANGELOG.md diff --git a/CONTRIBUTING.md b/premerge/CONTRIBUTING.md similarity index 100% rename from CONTRIBUTING.md rename to premerge/CONTRIBUTING.md diff --git a/INSTALL.md b/premerge/INSTALL.md similarity index 100% rename from INSTALL.md rename to premerge/INSTALL.md diff --git a/LICENSE b/premerge/LICENSE similarity index 100% rename from LICENSE rename to premerge/LICENSE diff --git a/Makefile b/premerge/Makefile similarity index 100% rename from Makefile rename to premerge/Makefile diff --git a/README.md b/premerge/README.md similarity index 100% rename from README.md rename to premerge/README.md diff --git a/Vagrantfile b/premerge/Vagrantfile similarity index 100% rename from Vagrantfile rename to premerge/Vagrantfile diff --git a/circle.yml b/premerge/circle.yml similarity index 100% rename from circle.yml rename to premerge/circle.yml diff --git a/glide.lock b/premerge/glide.lock similarity index 100% rename from glide.lock rename to premerge/glide.lock diff --git a/glide.yaml b/premerge/glide.yaml similarity index 100% rename from glide.yaml rename to premerge/glide.yaml diff --git a/test/README.md b/premerge/test/README.md similarity index 100% rename from test/README.md rename to premerge/test/README.md diff --git a/test/app/clean.sh b/premerge/test/app/clean.sh similarity index 100% rename from test/app/clean.sh rename to premerge/test/app/clean.sh diff --git a/test/app/counter_test.sh b/premerge/test/app/counter_test.sh similarity index 100% rename from test/app/counter_test.sh rename to premerge/test/app/counter_test.sh diff --git a/test/app/dummy_test.sh b/premerge/test/app/dummy_test.sh similarity index 100% rename from test/app/dummy_test.sh rename to premerge/test/app/dummy_test.sh diff --git a/test/app/grpc_client.go b/premerge/test/app/grpc_client.go similarity index 100% rename from test/app/grpc_client.go rename to premerge/test/app/grpc_client.go diff --git a/test/app/test.sh b/premerge/test/app/test.sh similarity index 100% rename from test/app/test.sh rename to premerge/test/app/test.sh diff --git a/test/docker/Dockerfile b/premerge/test/docker/Dockerfile similarity index 100% rename from test/docker/Dockerfile rename to premerge/test/docker/Dockerfile diff --git a/test/docker/build.sh b/premerge/test/docker/build.sh similarity index 100% rename from test/docker/build.sh rename to premerge/test/docker/build.sh diff --git a/test/docker/update.sh b/premerge/test/docker/update.sh similarity index 100% rename from test/docker/update.sh rename to premerge/test/docker/update.sh diff --git a/test/net/setup.sh b/premerge/test/net/setup.sh similarity index 100% rename from test/net/setup.sh rename to premerge/test/net/setup.sh diff --git a/test/net/start.sh b/premerge/test/net/start.sh similarity index 100% rename from test/net/start.sh rename to premerge/test/net/start.sh diff --git a/test/net/test.sh b/premerge/test/net/test.sh similarity index 100% rename from test/net/test.sh rename to premerge/test/net/test.sh diff --git a/test/p2p/README.md b/premerge/test/p2p/README.md similarity index 100% rename from test/p2p/README.md rename to premerge/test/p2p/README.md diff --git a/test/p2p/atomic_broadcast/test.sh b/premerge/test/p2p/atomic_broadcast/test.sh similarity index 100% rename from test/p2p/atomic_broadcast/test.sh rename to premerge/test/p2p/atomic_broadcast/test.sh diff --git a/test/p2p/basic/test.sh b/premerge/test/p2p/basic/test.sh similarity index 100% rename from test/p2p/basic/test.sh rename to premerge/test/p2p/basic/test.sh diff --git a/test/p2p/clean.sh b/premerge/test/p2p/clean.sh similarity index 100% rename from test/p2p/clean.sh rename to premerge/test/p2p/clean.sh diff --git a/test/p2p/client.sh b/premerge/test/p2p/client.sh similarity index 100% rename from test/p2p/client.sh rename to premerge/test/p2p/client.sh diff --git a/test/p2p/data/app/init.sh b/premerge/test/p2p/data/app/init.sh similarity index 100% rename from test/p2p/data/app/init.sh rename to premerge/test/p2p/data/app/init.sh diff --git a/test/p2p/data/chain_config.json b/premerge/test/p2p/data/chain_config.json similarity index 100% rename from test/p2p/data/chain_config.json rename to premerge/test/p2p/data/chain_config.json diff --git a/test/p2p/data/core/init.sh b/premerge/test/p2p/data/core/init.sh similarity index 100% rename from test/p2p/data/core/init.sh rename to premerge/test/p2p/data/core/init.sh diff --git a/test/p2p/data/data/init.sh b/premerge/test/p2p/data/data/init.sh similarity index 100% rename from test/p2p/data/data/init.sh rename to premerge/test/p2p/data/data/init.sh diff --git a/test/p2p/data/mach1/core/genesis.json b/premerge/test/p2p/data/mach1/core/genesis.json similarity index 100% rename from test/p2p/data/mach1/core/genesis.json rename to premerge/test/p2p/data/mach1/core/genesis.json diff --git a/test/p2p/data/mach1/core/priv_validator.json b/premerge/test/p2p/data/mach1/core/priv_validator.json similarity index 100% rename from test/p2p/data/mach1/core/priv_validator.json rename to premerge/test/p2p/data/mach1/core/priv_validator.json diff --git a/test/p2p/data/mach2/core/genesis.json b/premerge/test/p2p/data/mach2/core/genesis.json similarity index 100% rename from test/p2p/data/mach2/core/genesis.json rename to premerge/test/p2p/data/mach2/core/genesis.json diff --git a/test/p2p/data/mach2/core/priv_validator.json b/premerge/test/p2p/data/mach2/core/priv_validator.json similarity index 100% rename from test/p2p/data/mach2/core/priv_validator.json rename to premerge/test/p2p/data/mach2/core/priv_validator.json diff --git a/test/p2p/data/mach3/core/genesis.json b/premerge/test/p2p/data/mach3/core/genesis.json similarity index 100% rename from test/p2p/data/mach3/core/genesis.json rename to premerge/test/p2p/data/mach3/core/genesis.json diff --git a/test/p2p/data/mach3/core/priv_validator.json b/premerge/test/p2p/data/mach3/core/priv_validator.json similarity index 100% rename from test/p2p/data/mach3/core/priv_validator.json rename to premerge/test/p2p/data/mach3/core/priv_validator.json diff --git a/test/p2p/data/mach4/core/genesis.json b/premerge/test/p2p/data/mach4/core/genesis.json similarity index 100% rename from test/p2p/data/mach4/core/genesis.json rename to premerge/test/p2p/data/mach4/core/genesis.json diff --git a/test/p2p/data/mach4/core/priv_validator.json b/premerge/test/p2p/data/mach4/core/priv_validator.json similarity index 100% rename from test/p2p/data/mach4/core/priv_validator.json rename to premerge/test/p2p/data/mach4/core/priv_validator.json diff --git a/test/p2p/fast_sync/check_peer.sh b/premerge/test/p2p/fast_sync/check_peer.sh similarity index 100% rename from test/p2p/fast_sync/check_peer.sh rename to premerge/test/p2p/fast_sync/check_peer.sh diff --git a/test/p2p/fast_sync/test.sh b/premerge/test/p2p/fast_sync/test.sh similarity index 100% rename from test/p2p/fast_sync/test.sh rename to premerge/test/p2p/fast_sync/test.sh diff --git a/test/p2p/fast_sync/test_peer.sh b/premerge/test/p2p/fast_sync/test_peer.sh similarity index 100% rename from test/p2p/fast_sync/test_peer.sh rename to premerge/test/p2p/fast_sync/test_peer.sh diff --git a/test/p2p/ip.sh b/premerge/test/p2p/ip.sh similarity index 100% rename from test/p2p/ip.sh rename to premerge/test/p2p/ip.sh diff --git a/test/p2p/kill_all/check_peers.sh b/premerge/test/p2p/kill_all/check_peers.sh similarity index 100% rename from test/p2p/kill_all/check_peers.sh rename to premerge/test/p2p/kill_all/check_peers.sh diff --git a/test/p2p/kill_all/test.sh b/premerge/test/p2p/kill_all/test.sh similarity index 100% rename from test/p2p/kill_all/test.sh rename to premerge/test/p2p/kill_all/test.sh diff --git a/test/p2p/local_testnet_start.sh b/premerge/test/p2p/local_testnet_start.sh similarity index 100% rename from test/p2p/local_testnet_start.sh rename to premerge/test/p2p/local_testnet_start.sh diff --git a/test/p2p/local_testnet_stop.sh b/premerge/test/p2p/local_testnet_stop.sh similarity index 100% rename from test/p2p/local_testnet_stop.sh rename to premerge/test/p2p/local_testnet_stop.sh diff --git a/test/p2p/peer.sh b/premerge/test/p2p/peer.sh similarity index 100% rename from test/p2p/peer.sh rename to premerge/test/p2p/peer.sh diff --git a/test/p2p/pex/check_peer.sh b/premerge/test/p2p/pex/check_peer.sh similarity index 100% rename from test/p2p/pex/check_peer.sh rename to premerge/test/p2p/pex/check_peer.sh diff --git a/test/p2p/pex/dial_seeds.sh b/premerge/test/p2p/pex/dial_seeds.sh similarity index 100% rename from test/p2p/pex/dial_seeds.sh rename to premerge/test/p2p/pex/dial_seeds.sh diff --git a/test/p2p/pex/test.sh b/premerge/test/p2p/pex/test.sh similarity index 100% rename from test/p2p/pex/test.sh rename to premerge/test/p2p/pex/test.sh diff --git a/test/p2p/pex/test_addrbook.sh b/premerge/test/p2p/pex/test_addrbook.sh similarity index 100% rename from test/p2p/pex/test_addrbook.sh rename to premerge/test/p2p/pex/test_addrbook.sh diff --git a/test/p2p/pex/test_dial_seeds.sh b/premerge/test/p2p/pex/test_dial_seeds.sh similarity index 100% rename from test/p2p/pex/test_dial_seeds.sh rename to premerge/test/p2p/pex/test_dial_seeds.sh diff --git a/test/p2p/seeds.sh b/premerge/test/p2p/seeds.sh similarity index 100% rename from test/p2p/seeds.sh rename to premerge/test/p2p/seeds.sh diff --git a/test/p2p/test.sh b/premerge/test/p2p/test.sh similarity index 100% rename from test/p2p/test.sh rename to premerge/test/p2p/test.sh diff --git a/test/persist/test.sh b/premerge/test/persist/test.sh similarity index 100% rename from test/persist/test.sh rename to premerge/test/persist/test.sh diff --git a/test/persist/test_failure_indices.sh b/premerge/test/persist/test_failure_indices.sh similarity index 100% rename from test/persist/test_failure_indices.sh rename to premerge/test/persist/test_failure_indices.sh diff --git a/test/persist/test_simple.sh b/premerge/test/persist/test_simple.sh similarity index 100% rename from test/persist/test_simple.sh rename to premerge/test/persist/test_simple.sh diff --git a/test/run_test.sh b/premerge/test/run_test.sh similarity index 100% rename from test/run_test.sh rename to premerge/test/run_test.sh diff --git a/test/test.sh b/premerge/test/test.sh similarity index 100% rename from test/test.sh rename to premerge/test/test.sh diff --git a/test/test_cover.sh b/premerge/test/test_cover.sh similarity index 100% rename from test/test_cover.sh rename to premerge/test/test_cover.sh diff --git a/test/test_libs.sh b/premerge/test/test_libs.sh similarity index 100% rename from test/test_libs.sh rename to premerge/test/test_libs.sh diff --git a/test/utils/txs.sh b/premerge/test/utils/txs.sh similarity index 100% rename from test/utils/txs.sh rename to premerge/test/utils/txs.sh diff --git a/types/block.go b/premerge/types/block.go similarity index 100% rename from types/block.go rename to premerge/types/block.go diff --git a/types/block_meta.go b/premerge/types/block_meta.go similarity index 100% rename from types/block_meta.go rename to premerge/types/block_meta.go diff --git a/types/canonical_json.go b/premerge/types/canonical_json.go similarity index 100% rename from types/canonical_json.go rename to premerge/types/canonical_json.go diff --git a/types/events.go b/premerge/types/events.go similarity index 100% rename from types/events.go rename to premerge/types/events.go diff --git a/types/genesis.go b/premerge/types/genesis.go similarity index 100% rename from types/genesis.go rename to premerge/types/genesis.go diff --git a/types/keys.go b/premerge/types/keys.go similarity index 100% rename from types/keys.go rename to premerge/types/keys.go diff --git a/types/log.go b/premerge/types/log.go similarity index 100% rename from types/log.go rename to premerge/types/log.go diff --git a/types/part_set.go b/premerge/types/part_set.go similarity index 100% rename from types/part_set.go rename to premerge/types/part_set.go diff --git a/types/part_set_test.go b/premerge/types/part_set_test.go similarity index 100% rename from types/part_set_test.go rename to premerge/types/part_set_test.go diff --git a/types/priv_validator.go b/premerge/types/priv_validator.go similarity index 100% rename from types/priv_validator.go rename to premerge/types/priv_validator.go diff --git a/types/priv_validator_test.go b/premerge/types/priv_validator_test.go similarity index 100% rename from types/priv_validator_test.go rename to premerge/types/priv_validator_test.go diff --git a/types/proposal.go b/premerge/types/proposal.go similarity index 100% rename from types/proposal.go rename to premerge/types/proposal.go diff --git a/types/proposal_test.go b/premerge/types/proposal_test.go similarity index 100% rename from types/proposal_test.go rename to premerge/types/proposal_test.go diff --git a/types/protobuf.go b/premerge/types/protobuf.go similarity index 100% rename from types/protobuf.go rename to premerge/types/protobuf.go diff --git a/types/services.go b/premerge/types/services.go similarity index 100% rename from types/services.go rename to premerge/types/services.go diff --git a/types/signable.go b/premerge/types/signable.go similarity index 100% rename from types/signable.go rename to premerge/types/signable.go diff --git a/types/tx.go b/premerge/types/tx.go similarity index 100% rename from types/tx.go rename to premerge/types/tx.go diff --git a/types/tx_test.go b/premerge/types/tx_test.go similarity index 100% rename from types/tx_test.go rename to premerge/types/tx_test.go diff --git a/types/validator.go b/premerge/types/validator.go similarity index 100% rename from types/validator.go rename to premerge/types/validator.go diff --git a/types/validator_set.go b/premerge/types/validator_set.go similarity index 100% rename from types/validator_set.go rename to premerge/types/validator_set.go diff --git a/types/validator_set_test.go b/premerge/types/validator_set_test.go similarity index 100% rename from types/validator_set_test.go rename to premerge/types/validator_set_test.go diff --git a/types/vote.go b/premerge/types/vote.go similarity index 100% rename from types/vote.go rename to premerge/types/vote.go diff --git a/types/vote_set.go b/premerge/types/vote_set.go similarity index 100% rename from types/vote_set.go rename to premerge/types/vote_set.go diff --git a/types/vote_set_test.go b/premerge/types/vote_set_test.go similarity index 100% rename from types/vote_set_test.go rename to premerge/types/vote_set_test.go diff --git a/types/vote_test.go b/premerge/types/vote_test.go similarity index 100% rename from types/vote_test.go rename to premerge/types/vote_test.go From 992b11c450ee1ebae66af86838a3383426885e4c Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 21 Apr 2017 17:39:51 -0400 Subject: [PATCH 181/309] premerge2: rpc -> rpc/tendermint --- rpc/{ => tendermint}/client/event_test.go | 0 rpc/{ => tendermint}/client/helpers.go | 0 rpc/{ => tendermint}/client/helpers_test.go | 0 rpc/{ => tendermint}/client/httpclient.go | 0 rpc/{ => tendermint}/client/interface.go | 0 rpc/{ => tendermint}/client/localclient.go | 0 rpc/{ => tendermint}/client/main_test.go | 0 rpc/{ => tendermint}/client/mock/abci.go | 0 rpc/{ => tendermint}/client/mock/abci_test.go | 0 rpc/{ => tendermint}/client/mock/client.go | 0 rpc/{ => tendermint}/client/mock/status.go | 0 rpc/{ => tendermint}/client/mock/status_test.go | 0 rpc/{ => tendermint}/client/rpc_test.go | 0 rpc/{ => tendermint}/core/abci.go | 0 rpc/{ => tendermint}/core/blocks.go | 0 rpc/{ => tendermint}/core/consensus.go | 0 rpc/{ => tendermint}/core/dev.go | 0 rpc/{ => tendermint}/core/events.go | 0 rpc/{ => tendermint}/core/log.go | 0 rpc/{ => tendermint}/core/mempool.go | 0 rpc/{ => tendermint}/core/net.go | 0 rpc/{ => tendermint}/core/pipe.go | 0 rpc/{ => tendermint}/core/routes.go | 0 rpc/{ => tendermint}/core/status.go | 0 rpc/{ => tendermint}/core/tx.go | 0 rpc/{ => tendermint}/core/types/responses.go | 0 rpc/{ => tendermint}/core/types/responses_test.go | 0 rpc/{ => tendermint}/core/version.go | 0 rpc/{ => tendermint}/grpc/api.go | 0 rpc/{ => tendermint}/grpc/client_server.go | 0 rpc/{ => tendermint}/grpc/compile.sh | 0 rpc/{ => tendermint}/grpc/types.pb.go | 0 rpc/{ => tendermint}/grpc/types.proto | 0 rpc/{ => tendermint}/test/client_test.go | 0 rpc/{ => tendermint}/test/grpc_test.go | 0 rpc/{ => tendermint}/test/helpers.go | 0 rpc/{ => tendermint}/test/main_test.go | 0 37 files changed, 0 insertions(+), 0 deletions(-) rename rpc/{ => tendermint}/client/event_test.go (100%) rename rpc/{ => tendermint}/client/helpers.go (100%) rename rpc/{ => tendermint}/client/helpers_test.go (100%) rename rpc/{ => tendermint}/client/httpclient.go (100%) rename rpc/{ => tendermint}/client/interface.go (100%) rename rpc/{ => tendermint}/client/localclient.go (100%) rename rpc/{ => tendermint}/client/main_test.go (100%) rename rpc/{ => tendermint}/client/mock/abci.go (100%) rename rpc/{ => tendermint}/client/mock/abci_test.go (100%) rename rpc/{ => tendermint}/client/mock/client.go (100%) rename rpc/{ => tendermint}/client/mock/status.go (100%) rename rpc/{ => tendermint}/client/mock/status_test.go (100%) rename rpc/{ => tendermint}/client/rpc_test.go (100%) rename rpc/{ => tendermint}/core/abci.go (100%) rename rpc/{ => tendermint}/core/blocks.go (100%) rename rpc/{ => tendermint}/core/consensus.go (100%) rename rpc/{ => tendermint}/core/dev.go (100%) rename rpc/{ => tendermint}/core/events.go (100%) rename rpc/{ => tendermint}/core/log.go (100%) rename rpc/{ => tendermint}/core/mempool.go (100%) rename rpc/{ => tendermint}/core/net.go (100%) rename rpc/{ => tendermint}/core/pipe.go (100%) rename rpc/{ => tendermint}/core/routes.go (100%) rename rpc/{ => tendermint}/core/status.go (100%) rename rpc/{ => tendermint}/core/tx.go (100%) rename rpc/{ => tendermint}/core/types/responses.go (100%) rename rpc/{ => tendermint}/core/types/responses_test.go (100%) rename rpc/{ => tendermint}/core/version.go (100%) rename rpc/{ => tendermint}/grpc/api.go (100%) rename rpc/{ => tendermint}/grpc/client_server.go (100%) rename rpc/{ => tendermint}/grpc/compile.sh (100%) rename rpc/{ => tendermint}/grpc/types.pb.go (100%) rename rpc/{ => tendermint}/grpc/types.proto (100%) rename rpc/{ => tendermint}/test/client_test.go (100%) rename rpc/{ => tendermint}/test/grpc_test.go (100%) rename rpc/{ => tendermint}/test/helpers.go (100%) rename rpc/{ => tendermint}/test/main_test.go (100%) diff --git a/rpc/client/event_test.go b/rpc/tendermint/client/event_test.go similarity index 100% rename from rpc/client/event_test.go rename to rpc/tendermint/client/event_test.go diff --git a/rpc/client/helpers.go b/rpc/tendermint/client/helpers.go similarity index 100% rename from rpc/client/helpers.go rename to rpc/tendermint/client/helpers.go diff --git a/rpc/client/helpers_test.go b/rpc/tendermint/client/helpers_test.go similarity index 100% rename from rpc/client/helpers_test.go rename to rpc/tendermint/client/helpers_test.go diff --git a/rpc/client/httpclient.go b/rpc/tendermint/client/httpclient.go similarity index 100% rename from rpc/client/httpclient.go rename to rpc/tendermint/client/httpclient.go diff --git a/rpc/client/interface.go b/rpc/tendermint/client/interface.go similarity index 100% rename from rpc/client/interface.go rename to rpc/tendermint/client/interface.go diff --git a/rpc/client/localclient.go b/rpc/tendermint/client/localclient.go similarity index 100% rename from rpc/client/localclient.go rename to rpc/tendermint/client/localclient.go diff --git a/rpc/client/main_test.go b/rpc/tendermint/client/main_test.go similarity index 100% rename from rpc/client/main_test.go rename to rpc/tendermint/client/main_test.go diff --git a/rpc/client/mock/abci.go b/rpc/tendermint/client/mock/abci.go similarity index 100% rename from rpc/client/mock/abci.go rename to rpc/tendermint/client/mock/abci.go diff --git a/rpc/client/mock/abci_test.go b/rpc/tendermint/client/mock/abci_test.go similarity index 100% rename from rpc/client/mock/abci_test.go rename to rpc/tendermint/client/mock/abci_test.go diff --git a/rpc/client/mock/client.go b/rpc/tendermint/client/mock/client.go similarity index 100% rename from rpc/client/mock/client.go rename to rpc/tendermint/client/mock/client.go diff --git a/rpc/client/mock/status.go b/rpc/tendermint/client/mock/status.go similarity index 100% rename from rpc/client/mock/status.go rename to rpc/tendermint/client/mock/status.go diff --git a/rpc/client/mock/status_test.go b/rpc/tendermint/client/mock/status_test.go similarity index 100% rename from rpc/client/mock/status_test.go rename to rpc/tendermint/client/mock/status_test.go diff --git a/rpc/client/rpc_test.go b/rpc/tendermint/client/rpc_test.go similarity index 100% rename from rpc/client/rpc_test.go rename to rpc/tendermint/client/rpc_test.go diff --git a/rpc/core/abci.go b/rpc/tendermint/core/abci.go similarity index 100% rename from rpc/core/abci.go rename to rpc/tendermint/core/abci.go diff --git a/rpc/core/blocks.go b/rpc/tendermint/core/blocks.go similarity index 100% rename from rpc/core/blocks.go rename to rpc/tendermint/core/blocks.go diff --git a/rpc/core/consensus.go b/rpc/tendermint/core/consensus.go similarity index 100% rename from rpc/core/consensus.go rename to rpc/tendermint/core/consensus.go diff --git a/rpc/core/dev.go b/rpc/tendermint/core/dev.go similarity index 100% rename from rpc/core/dev.go rename to rpc/tendermint/core/dev.go diff --git a/rpc/core/events.go b/rpc/tendermint/core/events.go similarity index 100% rename from rpc/core/events.go rename to rpc/tendermint/core/events.go diff --git a/rpc/core/log.go b/rpc/tendermint/core/log.go similarity index 100% rename from rpc/core/log.go rename to rpc/tendermint/core/log.go diff --git a/rpc/core/mempool.go b/rpc/tendermint/core/mempool.go similarity index 100% rename from rpc/core/mempool.go rename to rpc/tendermint/core/mempool.go diff --git a/rpc/core/net.go b/rpc/tendermint/core/net.go similarity index 100% rename from rpc/core/net.go rename to rpc/tendermint/core/net.go diff --git a/rpc/core/pipe.go b/rpc/tendermint/core/pipe.go similarity index 100% rename from rpc/core/pipe.go rename to rpc/tendermint/core/pipe.go diff --git a/rpc/core/routes.go b/rpc/tendermint/core/routes.go similarity index 100% rename from rpc/core/routes.go rename to rpc/tendermint/core/routes.go diff --git a/rpc/core/status.go b/rpc/tendermint/core/status.go similarity index 100% rename from rpc/core/status.go rename to rpc/tendermint/core/status.go diff --git a/rpc/core/tx.go b/rpc/tendermint/core/tx.go similarity index 100% rename from rpc/core/tx.go rename to rpc/tendermint/core/tx.go diff --git a/rpc/core/types/responses.go b/rpc/tendermint/core/types/responses.go similarity index 100% rename from rpc/core/types/responses.go rename to rpc/tendermint/core/types/responses.go diff --git a/rpc/core/types/responses_test.go b/rpc/tendermint/core/types/responses_test.go similarity index 100% rename from rpc/core/types/responses_test.go rename to rpc/tendermint/core/types/responses_test.go diff --git a/rpc/core/version.go b/rpc/tendermint/core/version.go similarity index 100% rename from rpc/core/version.go rename to rpc/tendermint/core/version.go diff --git a/rpc/grpc/api.go b/rpc/tendermint/grpc/api.go similarity index 100% rename from rpc/grpc/api.go rename to rpc/tendermint/grpc/api.go diff --git a/rpc/grpc/client_server.go b/rpc/tendermint/grpc/client_server.go similarity index 100% rename from rpc/grpc/client_server.go rename to rpc/tendermint/grpc/client_server.go diff --git a/rpc/grpc/compile.sh b/rpc/tendermint/grpc/compile.sh similarity index 100% rename from rpc/grpc/compile.sh rename to rpc/tendermint/grpc/compile.sh diff --git a/rpc/grpc/types.pb.go b/rpc/tendermint/grpc/types.pb.go similarity index 100% rename from rpc/grpc/types.pb.go rename to rpc/tendermint/grpc/types.pb.go diff --git a/rpc/grpc/types.proto b/rpc/tendermint/grpc/types.proto similarity index 100% rename from rpc/grpc/types.proto rename to rpc/tendermint/grpc/types.proto diff --git a/rpc/test/client_test.go b/rpc/tendermint/test/client_test.go similarity index 100% rename from rpc/test/client_test.go rename to rpc/tendermint/test/client_test.go diff --git a/rpc/test/grpc_test.go b/rpc/tendermint/test/grpc_test.go similarity index 100% rename from rpc/test/grpc_test.go rename to rpc/tendermint/test/grpc_test.go diff --git a/rpc/test/helpers.go b/rpc/tendermint/test/helpers.go similarity index 100% rename from rpc/test/helpers.go rename to rpc/tendermint/test/helpers.go diff --git a/rpc/test/main_test.go b/rpc/tendermint/test/main_test.go similarity index 100% rename from rpc/test/main_test.go rename to rpc/tendermint/test/main_test.go From 15d5b2ac497da95cd2dceb9c087910ccec4dacb2 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 21 Apr 2017 17:51:11 -0400 Subject: [PATCH 182/309] use tmlibs --- client/ws_client.go | 2 +- server/handlers.go | 4 ++-- test/main.go | 2 +- types/types.go | 2 +- 4 files changed, 5 insertions(+), 5 deletions(-) diff --git a/client/ws_client.go b/client/ws_client.go index 16dc474c3..b83d62974 100644 --- a/client/ws_client.go +++ b/client/ws_client.go @@ -8,7 +8,7 @@ import ( "github.com/gorilla/websocket" "github.com/pkg/errors" - cmn "github.com/tendermint/go-common" + cmn "github.com/tendermint/tmlibs/common" types "github.com/tendermint/go-rpc/types" wire "github.com/tendermint/go-wire" ) diff --git a/server/handlers.go b/server/handlers.go index 9be64b775..456b4aaf5 100644 --- a/server/handlers.go +++ b/server/handlers.go @@ -14,10 +14,10 @@ import ( "github.com/gorilla/websocket" "github.com/pkg/errors" - cmn "github.com/tendermint/go-common" - events "github.com/tendermint/go-events" types "github.com/tendermint/go-rpc/types" wire "github.com/tendermint/go-wire" + cmn "github.com/tendermint/tmlibs/common" + events "github.com/tendermint/tmlibs/events" ) // Adds a route for each function in the funcMap, as well as general jsonrpc and websocket handlers for all functions. diff --git a/test/main.go b/test/main.go index 28de2be88..59c6e9b8f 100644 --- a/test/main.go +++ b/test/main.go @@ -4,7 +4,7 @@ import ( "fmt" "net/http" - cmn "github.com/tendermint/go-common" + cmn "github.com/tendermint/tmlibs/common" rpcserver "github.com/tendermint/go-rpc/server" ) diff --git a/types/types.go b/types/types.go index 38c7f09db..9c5f2625b 100644 --- a/types/types.go +++ b/types/types.go @@ -4,8 +4,8 @@ import ( "encoding/json" "strings" - events "github.com/tendermint/go-events" wire "github.com/tendermint/go-wire" + events "github.com/tendermint/tmlibs/events" ) type RPCRequest struct { From eaeb5479383fe6983c30bc9b10803ba279371036 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 21 Apr 2017 17:53:22 -0400 Subject: [PATCH 183/309] use tmlibs --- addrbook.go | 2 +- connection.go | 4 ++-- glide.lock | 8 ++++---- glide.yaml | 8 ++++---- listener.go | 2 +- log.go | 2 +- netaddress.go | 2 +- peer.go | 2 +- peer_set_test.go | 2 +- pex_reactor.go | 2 +- pex_reactor_test.go | 2 +- secret_connection.go | 2 +- secret_connection_test.go | 2 +- switch.go | 2 +- switch_test.go | 2 +- upnp/log.go | 2 +- upnp/probe.go | 2 +- 17 files changed, 24 insertions(+), 24 deletions(-) diff --git a/addrbook.go b/addrbook.go index 8a1698f41..e68cc7b3a 100644 --- a/addrbook.go +++ b/addrbook.go @@ -14,7 +14,7 @@ import ( "sync" "time" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" crypto "github.com/tendermint/go-crypto" ) diff --git a/connection.go b/connection.go index a14fa5ee4..629ab7b0d 100644 --- a/connection.go +++ b/connection.go @@ -10,9 +10,9 @@ import ( "sync/atomic" "time" - cmn "github.com/tendermint/go-common" - flow "github.com/tendermint/go-flowrate/flowrate" wire "github.com/tendermint/go-wire" + cmn "github.com/tendermint/tmlibs/common" + flow "github.com/tendermint/tmlibs/flowrate" ) const ( diff --git a/glide.lock b/glide.lock index 71505ea05..5da4e6230 100644 --- a/glide.lock +++ b/glide.lock @@ -22,19 +22,19 @@ imports: subpackages: - edwards25519 - extra25519 -- name: github.com/tendermint/go-common +- name: github.com/tendermint/tmlibs/common version: f9e3db037330c8a8d61d3966de8473eaf01154fa - name: github.com/tendermint/go-config version: 620dcbbd7d587cf3599dedbf329b64311b0c307a - name: github.com/tendermint/go-crypto version: 0ca2c6fdb0706001ca4c4b9b80c9f428e8cf39da -- name: github.com/tendermint/go-data +- name: github.com/tendermint/go-wire/data version: e7fcc6d081ec8518912fcdc103188275f83a3ee5 -- name: github.com/tendermint/go-flowrate +- name: github.com/tendermint/tmlibs/flowrate version: a20c98e61957faa93b4014fbd902f20ab9317a6a subpackages: - flowrate -- name: github.com/tendermint/go-logger +- name: github.com/tendermint/tmlibs/logger version: cefb3a45c0bf3c493a04e9bcd9b1540528be59f2 - name: github.com/tendermint/go-wire version: c1c9a57ab8038448ddea1714c0698f8051e5748c diff --git a/glide.yaml b/glide.yaml index e7edc80ae..5bf7a015e 100644 --- a/glide.yaml +++ b/glide.yaml @@ -1,17 +1,17 @@ package: github.com/tendermint/go-p2p import: -- package: github.com/tendermint/go-common +- package: github.com/tendermint/tmlibs/common version: develop - package: github.com/tendermint/go-config version: develop - package: github.com/tendermint/go-crypto version: develop -- package: github.com/tendermint/go-data +- package: github.com/tendermint/go-wire/data version: develop -- package: github.com/tendermint/go-flowrate +- package: github.com/tendermint/tmlibs/flowrate subpackages: - flowrate -- package: github.com/tendermint/go-logger +- package: github.com/tendermint/tmlibs/logger version: develop - package: github.com/tendermint/go-wire version: develop diff --git a/listener.go b/listener.go index 962c2b14c..51beb5e27 100644 --- a/listener.go +++ b/listener.go @@ -6,7 +6,7 @@ import ( "strconv" "time" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" "github.com/tendermint/go-p2p/upnp" ) diff --git a/log.go b/log.go index ac1ff22a5..af3203409 100644 --- a/log.go +++ b/log.go @@ -1,7 +1,7 @@ package p2p import ( - "github.com/tendermint/go-logger" + "github.com/tendermint/tmlibs/logger" ) var log = logger.New("module", "p2p") diff --git a/netaddress.go b/netaddress.go index 263ec9037..09787481c 100644 --- a/netaddress.go +++ b/netaddress.go @@ -11,7 +11,7 @@ import ( "strconv" "time" - cmn "github.com/tendermint/go-common" + cmn "github.com/tendermint/tmlibs/common" ) // NetAddress defines information about a peer on the network diff --git a/peer.go b/peer.go index 5461d7e8a..355f4731e 100644 --- a/peer.go +++ b/peer.go @@ -7,7 +7,7 @@ import ( "time" "github.com/pkg/errors" - cmn "github.com/tendermint/go-common" + cmn "github.com/tendermint/tmlibs/common" crypto "github.com/tendermint/go-crypto" wire "github.com/tendermint/go-wire" ) diff --git a/peer_set_test.go b/peer_set_test.go index ceb10eeee..a17f9d658 100644 --- a/peer_set_test.go +++ b/peer_set_test.go @@ -4,7 +4,7 @@ import ( "math/rand" "testing" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" ) // Returns an empty dummy peer diff --git a/pex_reactor.go b/pex_reactor.go index 4b6129762..03a383c85 100644 --- a/pex_reactor.go +++ b/pex_reactor.go @@ -7,7 +7,7 @@ import ( "reflect" "time" - cmn "github.com/tendermint/go-common" + cmn "github.com/tendermint/tmlibs/common" wire "github.com/tendermint/go-wire" ) diff --git a/pex_reactor_test.go b/pex_reactor_test.go index 13f2fa208..aed6c758d 100644 --- a/pex_reactor_test.go +++ b/pex_reactor_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - cmn "github.com/tendermint/go-common" + cmn "github.com/tendermint/tmlibs/common" wire "github.com/tendermint/go-wire" ) diff --git a/secret_connection.go b/secret_connection.go index be3e62a9d..49535a40a 100644 --- a/secret_connection.go +++ b/secret_connection.go @@ -20,7 +20,7 @@ import ( "golang.org/x/crypto/nacl/secretbox" "golang.org/x/crypto/ripemd160" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" "github.com/tendermint/go-crypto" "github.com/tendermint/go-wire" ) diff --git a/secret_connection_test.go b/secret_connection_test.go index 9bf1a7b1d..58459e62a 100644 --- a/secret_connection_test.go +++ b/secret_connection_test.go @@ -5,7 +5,7 @@ import ( "io" "testing" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" "github.com/tendermint/go-crypto" ) diff --git a/switch.go b/switch.go index 6835e0a4b..3e3ab4f87 100644 --- a/switch.go +++ b/switch.go @@ -7,7 +7,7 @@ import ( "net" "time" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" cfg "github.com/tendermint/go-config" crypto "github.com/tendermint/go-crypto" "github.com/tendermint/log15" diff --git a/switch_test.go b/switch_test.go index a81bb4ac0..1f1fe69f0 100644 --- a/switch_test.go +++ b/switch_test.go @@ -10,7 +10,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" cfg "github.com/tendermint/go-config" crypto "github.com/tendermint/go-crypto" wire "github.com/tendermint/go-wire" diff --git a/upnp/log.go b/upnp/log.go index edc5b4980..45e44439c 100644 --- a/upnp/log.go +++ b/upnp/log.go @@ -1,7 +1,7 @@ package upnp import ( - "github.com/tendermint/go-logger" + "github.com/tendermint/tmlibs/logger" ) var log = logger.New("module", "upnp") diff --git a/upnp/probe.go b/upnp/probe.go index 5ba9b2370..5488de587 100644 --- a/upnp/probe.go +++ b/upnp/probe.go @@ -6,7 +6,7 @@ import ( "net" "time" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" ) type UPNPCapabilities struct { From 34965f610d2835a348021f340fc14a4b87175aa5 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 21 Apr 2017 18:02:25 -0400 Subject: [PATCH 184/309] crypto Wrap/Unwrap --- peer.go | 4 ++-- peer_test.go | 6 +++--- secret_connection.go | 12 ++++++------ secret_connection_test.go | 6 +++--- switch.go | 8 ++++---- 5 files changed, 18 insertions(+), 18 deletions(-) diff --git a/peer.go b/peer.go index 355f4731e..bf819087d 100644 --- a/peer.go +++ b/peer.go @@ -7,9 +7,9 @@ import ( "time" "github.com/pkg/errors" - cmn "github.com/tendermint/tmlibs/common" crypto "github.com/tendermint/go-crypto" wire "github.com/tendermint/go-wire" + cmn "github.com/tendermint/tmlibs/common" ) // Peer could be marked as persistent, in which case you can use @@ -166,7 +166,7 @@ func (p *Peer) HandshakeTimeout(ourNodeInfo *NodeInfo, timeout time.Duration) er if p.config.AuthEnc { // Check that the professed PubKey matches the sconn's. - if !peerNodeInfo.PubKey.Equals(p.PubKey()) { + if !peerNodeInfo.PubKey.Equals(p.PubKey().Wrap()) { return fmt.Errorf("Ignoring connection with unmatching pubkey: %v vs %v", peerNodeInfo.PubKey, p.PubKey()) } diff --git a/peer_test.go b/peer_test.go index 5f3ed0e23..0ac776347 100644 --- a/peer_test.go +++ b/peer_test.go @@ -87,7 +87,7 @@ func createOutboundPeerAndPerformHandshake(addr *NetAddress, config *PeerConfig) return nil, err } err = p.HandshakeTimeout(&NodeInfo{ - PubKey: pk.PubKey().(crypto.PubKeyEd25519), + PubKey: pk.PubKey().Unwrap().(crypto.PubKeyEd25519), Moniker: "host_peer", Network: "testing", Version: "123.123.123", @@ -110,7 +110,7 @@ func (p *remotePeer) Addr() *NetAddress { } func (p *remotePeer) PubKey() crypto.PubKeyEd25519 { - return p.PrivKey.PubKey().(crypto.PubKeyEd25519) + return p.PrivKey.PubKey().Unwrap().(crypto.PubKeyEd25519) } func (p *remotePeer) Start() { @@ -138,7 +138,7 @@ func (p *remotePeer) accept(l net.Listener) { golog.Fatalf("Failed to create a peer: %+v", err) } err = peer.HandshakeTimeout(&NodeInfo{ - PubKey: p.PrivKey.PubKey().(crypto.PubKeyEd25519), + PubKey: p.PrivKey.PubKey().Unwrap().(crypto.PubKeyEd25519), Moniker: "remote_peer", Network: "testing", Version: "123.123.123", diff --git a/secret_connection.go b/secret_connection.go index 49535a40a..446c4f185 100644 --- a/secret_connection.go +++ b/secret_connection.go @@ -20,9 +20,9 @@ import ( "golang.org/x/crypto/nacl/secretbox" "golang.org/x/crypto/ripemd160" - . "github.com/tendermint/tmlibs/common" "github.com/tendermint/go-crypto" "github.com/tendermint/go-wire" + . "github.com/tendermint/tmlibs/common" ) // 2 + 1024 == 1026 total frame size @@ -48,7 +48,7 @@ type SecretConnection struct { // See docs/sts-final.pdf for more information. func MakeSecretConnection(conn io.ReadWriteCloser, locPrivKey crypto.PrivKeyEd25519) (*SecretConnection, error) { - locPubKey := locPrivKey.PubKey().(crypto.PubKeyEd25519) + locPubKey := locPrivKey.PubKey().Unwrap().(crypto.PubKeyEd25519) // Generate ephemeral keys for perfect forward secrecy. locEphPub, locEphPriv := genEphKeys() @@ -96,7 +96,7 @@ func MakeSecretConnection(conn io.ReadWriteCloser, locPrivKey crypto.PrivKeyEd25 } // We've authorized. - sc.remPubKey = remPubKey.(crypto.PubKeyEd25519) + sc.remPubKey = remPubKey.Unwrap().(crypto.PubKeyEd25519) return sc, nil } @@ -255,7 +255,7 @@ func genChallenge(loPubKey, hiPubKey *[32]byte) (challenge *[32]byte) { } func signChallenge(challenge *[32]byte, locPrivKey crypto.PrivKeyEd25519) (signature crypto.SignatureEd25519) { - signature = locPrivKey.Sign(challenge[:]).(crypto.SignatureEd25519) + signature = locPrivKey.Sign(challenge[:]).Unwrap().(crypto.SignatureEd25519) return } @@ -270,7 +270,7 @@ func shareAuthSignature(sc *SecretConnection, pubKey crypto.PubKeyEd25519, signa Parallel( func() { - msgBytes := wire.BinaryBytes(authSigMessage{pubKey, signature}) + msgBytes := wire.BinaryBytes(authSigMessage{pubKey.Wrap(), signature.Wrap()}) _, err1 = sc.Write(msgBytes) }, func() { @@ -294,7 +294,7 @@ func shareAuthSignature(sc *SecretConnection, pubKey crypto.PubKeyEd25519, signa } func verifyChallengeSignature(challenge *[32]byte, remPubKey crypto.PubKeyEd25519, remSignature crypto.SignatureEd25519) bool { - return remPubKey.VerifyBytes(challenge[:], remSignature) + return remPubKey.VerifyBytes(challenge[:], remSignature.Wrap()) } //-------------------------------------------------------------------------------- diff --git a/secret_connection_test.go b/secret_connection_test.go index 58459e62a..3dd962f88 100644 --- a/secret_connection_test.go +++ b/secret_connection_test.go @@ -5,8 +5,8 @@ import ( "io" "testing" - . "github.com/tendermint/tmlibs/common" "github.com/tendermint/go-crypto" + . "github.com/tendermint/tmlibs/common" ) type dummyConn struct { @@ -33,9 +33,9 @@ func makeDummyConnPair() (fooConn, barConn dummyConn) { func makeSecretConnPair(tb testing.TB) (fooSecConn, barSecConn *SecretConnection) { fooConn, barConn := makeDummyConnPair() fooPrvKey := crypto.GenPrivKeyEd25519() - fooPubKey := fooPrvKey.PubKey().(crypto.PubKeyEd25519) + fooPubKey := fooPrvKey.PubKey().Unwrap().(crypto.PubKeyEd25519) barPrvKey := crypto.GenPrivKeyEd25519() - barPubKey := barPrvKey.PubKey().(crypto.PubKeyEd25519) + barPubKey := barPrvKey.PubKey().Unwrap().(crypto.PubKeyEd25519) Parallel( func() { diff --git a/switch.go b/switch.go index 3e3ab4f87..8c771df1c 100644 --- a/switch.go +++ b/switch.go @@ -7,10 +7,10 @@ import ( "net" "time" - . "github.com/tendermint/tmlibs/common" cfg "github.com/tendermint/go-config" crypto "github.com/tendermint/go-crypto" "github.com/tendermint/log15" + . "github.com/tendermint/tmlibs/common" ) const ( @@ -154,7 +154,7 @@ func (sw *Switch) NodeInfo() *NodeInfo { func (sw *Switch) SetNodePrivKey(nodePrivKey crypto.PrivKeyEd25519) { sw.nodePrivKey = nodePrivKey if sw.nodeInfo != nil { - sw.nodeInfo.PubKey = nodePrivKey.PubKey().(crypto.PubKeyEd25519) + sw.nodeInfo.PubKey = nodePrivKey.PubKey().Unwrap().(crypto.PubKeyEd25519) } } @@ -213,7 +213,7 @@ func (sw *Switch) AddPeer(peer *Peer) error { } // Avoid self - if sw.nodeInfo.PubKey.Equals(peer.PubKey()) { + if sw.nodeInfo.PubKey.Equals(peer.PubKey().Wrap()) { return errors.New("Ignoring connection from self") } @@ -531,7 +531,7 @@ func makeSwitch(i int, network, version string, initSwitch func(int, *Switch) *S // TODO: let the config be passed in? s := initSwitch(i, NewSwitch(cfg.NewMapConfig(nil))) s.SetNodeInfo(&NodeInfo{ - PubKey: privKey.PubKey().(crypto.PubKeyEd25519), + PubKey: privKey.PubKey().Unwrap().(crypto.PubKeyEd25519), Moniker: Fmt("switch%d", i), Network: network, Version: version, From c55d83281aab041335e297064c22e5cb6de9ed57 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 21 Apr 2017 18:05:39 -0400 Subject: [PATCH 185/309] move into rpc package --- Dockerfile => rpc/Dockerfile | 0 LICENSE => rpc/LICENSE | 0 Makefile => rpc/Makefile | 0 README.md => rpc/README.md | 0 circle.yml => rpc/circle.yml | 0 {client => rpc/client}/http_client.go | 0 {client => rpc/client}/log.go | 0 {client => rpc/client}/ws_client.go | 0 rpc_test.go => rpc/rpc_test.go | 0 {server => rpc/server}/handlers.go | 0 {server => rpc/server}/http_params.go | 0 {server => rpc/server}/http_server.go | 0 {server => rpc/server}/log.go | 0 {test => rpc/test}/data.json | 0 {test => rpc/test}/integration_test.sh | 0 {test => rpc/test}/main.go | 0 {types => rpc/types}/types.go | 0 version.go => rpc/version.go | 0 18 files changed, 0 insertions(+), 0 deletions(-) rename Dockerfile => rpc/Dockerfile (100%) rename LICENSE => rpc/LICENSE (100%) rename Makefile => rpc/Makefile (100%) rename README.md => rpc/README.md (100%) rename circle.yml => rpc/circle.yml (100%) rename {client => rpc/client}/http_client.go (100%) rename {client => rpc/client}/log.go (100%) rename {client => rpc/client}/ws_client.go (100%) rename rpc_test.go => rpc/rpc_test.go (100%) rename {server => rpc/server}/handlers.go (100%) rename {server => rpc/server}/http_params.go (100%) rename {server => rpc/server}/http_server.go (100%) rename {server => rpc/server}/log.go (100%) rename {test => rpc/test}/data.json (100%) rename {test => rpc/test}/integration_test.sh (100%) rename {test => rpc/test}/main.go (100%) rename {types => rpc/types}/types.go (100%) rename version.go => rpc/version.go (100%) diff --git a/Dockerfile b/rpc/Dockerfile similarity index 100% rename from Dockerfile rename to rpc/Dockerfile diff --git a/LICENSE b/rpc/LICENSE similarity index 100% rename from LICENSE rename to rpc/LICENSE diff --git a/Makefile b/rpc/Makefile similarity index 100% rename from Makefile rename to rpc/Makefile diff --git a/README.md b/rpc/README.md similarity index 100% rename from README.md rename to rpc/README.md diff --git a/circle.yml b/rpc/circle.yml similarity index 100% rename from circle.yml rename to rpc/circle.yml diff --git a/client/http_client.go b/rpc/client/http_client.go similarity index 100% rename from client/http_client.go rename to rpc/client/http_client.go diff --git a/client/log.go b/rpc/client/log.go similarity index 100% rename from client/log.go rename to rpc/client/log.go diff --git a/client/ws_client.go b/rpc/client/ws_client.go similarity index 100% rename from client/ws_client.go rename to rpc/client/ws_client.go diff --git a/rpc_test.go b/rpc/rpc_test.go similarity index 100% rename from rpc_test.go rename to rpc/rpc_test.go diff --git a/server/handlers.go b/rpc/server/handlers.go similarity index 100% rename from server/handlers.go rename to rpc/server/handlers.go diff --git a/server/http_params.go b/rpc/server/http_params.go similarity index 100% rename from server/http_params.go rename to rpc/server/http_params.go diff --git a/server/http_server.go b/rpc/server/http_server.go similarity index 100% rename from server/http_server.go rename to rpc/server/http_server.go diff --git a/server/log.go b/rpc/server/log.go similarity index 100% rename from server/log.go rename to rpc/server/log.go diff --git a/test/data.json b/rpc/test/data.json similarity index 100% rename from test/data.json rename to rpc/test/data.json diff --git a/test/integration_test.sh b/rpc/test/integration_test.sh similarity index 100% rename from test/integration_test.sh rename to rpc/test/integration_test.sh diff --git a/test/main.go b/rpc/test/main.go similarity index 100% rename from test/main.go rename to rpc/test/main.go diff --git a/types/types.go b/rpc/types/types.go similarity index 100% rename from types/types.go rename to rpc/types/types.go diff --git a/version.go b/rpc/version.go similarity index 100% rename from version.go rename to rpc/version.go From 23a6a6f8fce4b97da2211713eb08d5d5819d5821 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 21 Apr 2017 18:07:52 -0400 Subject: [PATCH 186/309] move into p2p package --- CHANGELOG.md => p2p/CHANGELOG.md | 0 Dockerfile => p2p/Dockerfile | 0 LICENSE => p2p/LICENSE | 0 README.md => p2p/README.md | 0 addrbook.go => p2p/addrbook.go | 0 addrbook_test.go => p2p/addrbook_test.go | 0 config.go => p2p/config.go | 0 connection.go => p2p/connection.go | 0 connection_test.go => p2p/connection_test.go | 0 fuzz.go => p2p/fuzz.go | 0 glide.lock => p2p/glide.lock | 0 glide.yaml => p2p/glide.yaml | 0 ip_range_counter.go => p2p/ip_range_counter.go | 0 listener.go => p2p/listener.go | 0 listener_test.go => p2p/listener_test.go | 0 log.go => p2p/log.go | 0 netaddress.go => p2p/netaddress.go | 0 netaddress_test.go => p2p/netaddress_test.go | 0 peer.go => p2p/peer.go | 0 peer_set.go => p2p/peer_set.go | 0 peer_set_test.go => p2p/peer_set_test.go | 0 peer_test.go => p2p/peer_test.go | 0 pex_reactor.go => p2p/pex_reactor.go | 0 pex_reactor_test.go => p2p/pex_reactor_test.go | 0 secret_connection.go => p2p/secret_connection.go | 0 secret_connection_test.go => p2p/secret_connection_test.go | 0 switch.go => p2p/switch.go | 0 switch_test.go => p2p/switch_test.go | 0 types.go => p2p/types.go | 0 {upnp => p2p/upnp}/README.md | 0 {upnp => p2p/upnp}/log.go | 0 {upnp => p2p/upnp}/probe.go | 0 {upnp => p2p/upnp}/upnp.go | 0 util.go => p2p/util.go | 0 version.go => p2p/version.go | 0 35 files changed, 0 insertions(+), 0 deletions(-) rename CHANGELOG.md => p2p/CHANGELOG.md (100%) rename Dockerfile => p2p/Dockerfile (100%) rename LICENSE => p2p/LICENSE (100%) rename README.md => p2p/README.md (100%) rename addrbook.go => p2p/addrbook.go (100%) rename addrbook_test.go => p2p/addrbook_test.go (100%) rename config.go => p2p/config.go (100%) rename connection.go => p2p/connection.go (100%) rename connection_test.go => p2p/connection_test.go (100%) rename fuzz.go => p2p/fuzz.go (100%) rename glide.lock => p2p/glide.lock (100%) rename glide.yaml => p2p/glide.yaml (100%) rename ip_range_counter.go => p2p/ip_range_counter.go (100%) rename listener.go => p2p/listener.go (100%) rename listener_test.go => p2p/listener_test.go (100%) rename log.go => p2p/log.go (100%) rename netaddress.go => p2p/netaddress.go (100%) rename netaddress_test.go => p2p/netaddress_test.go (100%) rename peer.go => p2p/peer.go (100%) rename peer_set.go => p2p/peer_set.go (100%) rename peer_set_test.go => p2p/peer_set_test.go (100%) rename peer_test.go => p2p/peer_test.go (100%) rename pex_reactor.go => p2p/pex_reactor.go (100%) rename pex_reactor_test.go => p2p/pex_reactor_test.go (100%) rename secret_connection.go => p2p/secret_connection.go (100%) rename secret_connection_test.go => p2p/secret_connection_test.go (100%) rename switch.go => p2p/switch.go (100%) rename switch_test.go => p2p/switch_test.go (100%) rename types.go => p2p/types.go (100%) rename {upnp => p2p/upnp}/README.md (100%) rename {upnp => p2p/upnp}/log.go (100%) rename {upnp => p2p/upnp}/probe.go (100%) rename {upnp => p2p/upnp}/upnp.go (100%) rename util.go => p2p/util.go (100%) rename version.go => p2p/version.go (100%) diff --git a/CHANGELOG.md b/p2p/CHANGELOG.md similarity index 100% rename from CHANGELOG.md rename to p2p/CHANGELOG.md diff --git a/Dockerfile b/p2p/Dockerfile similarity index 100% rename from Dockerfile rename to p2p/Dockerfile diff --git a/LICENSE b/p2p/LICENSE similarity index 100% rename from LICENSE rename to p2p/LICENSE diff --git a/README.md b/p2p/README.md similarity index 100% rename from README.md rename to p2p/README.md diff --git a/addrbook.go b/p2p/addrbook.go similarity index 100% rename from addrbook.go rename to p2p/addrbook.go diff --git a/addrbook_test.go b/p2p/addrbook_test.go similarity index 100% rename from addrbook_test.go rename to p2p/addrbook_test.go diff --git a/config.go b/p2p/config.go similarity index 100% rename from config.go rename to p2p/config.go diff --git a/connection.go b/p2p/connection.go similarity index 100% rename from connection.go rename to p2p/connection.go diff --git a/connection_test.go b/p2p/connection_test.go similarity index 100% rename from connection_test.go rename to p2p/connection_test.go diff --git a/fuzz.go b/p2p/fuzz.go similarity index 100% rename from fuzz.go rename to p2p/fuzz.go diff --git a/glide.lock b/p2p/glide.lock similarity index 100% rename from glide.lock rename to p2p/glide.lock diff --git a/glide.yaml b/p2p/glide.yaml similarity index 100% rename from glide.yaml rename to p2p/glide.yaml diff --git a/ip_range_counter.go b/p2p/ip_range_counter.go similarity index 100% rename from ip_range_counter.go rename to p2p/ip_range_counter.go diff --git a/listener.go b/p2p/listener.go similarity index 100% rename from listener.go rename to p2p/listener.go diff --git a/listener_test.go b/p2p/listener_test.go similarity index 100% rename from listener_test.go rename to p2p/listener_test.go diff --git a/log.go b/p2p/log.go similarity index 100% rename from log.go rename to p2p/log.go diff --git a/netaddress.go b/p2p/netaddress.go similarity index 100% rename from netaddress.go rename to p2p/netaddress.go diff --git a/netaddress_test.go b/p2p/netaddress_test.go similarity index 100% rename from netaddress_test.go rename to p2p/netaddress_test.go diff --git a/peer.go b/p2p/peer.go similarity index 100% rename from peer.go rename to p2p/peer.go diff --git a/peer_set.go b/p2p/peer_set.go similarity index 100% rename from peer_set.go rename to p2p/peer_set.go diff --git a/peer_set_test.go b/p2p/peer_set_test.go similarity index 100% rename from peer_set_test.go rename to p2p/peer_set_test.go diff --git a/peer_test.go b/p2p/peer_test.go similarity index 100% rename from peer_test.go rename to p2p/peer_test.go diff --git a/pex_reactor.go b/p2p/pex_reactor.go similarity index 100% rename from pex_reactor.go rename to p2p/pex_reactor.go diff --git a/pex_reactor_test.go b/p2p/pex_reactor_test.go similarity index 100% rename from pex_reactor_test.go rename to p2p/pex_reactor_test.go diff --git a/secret_connection.go b/p2p/secret_connection.go similarity index 100% rename from secret_connection.go rename to p2p/secret_connection.go diff --git a/secret_connection_test.go b/p2p/secret_connection_test.go similarity index 100% rename from secret_connection_test.go rename to p2p/secret_connection_test.go diff --git a/switch.go b/p2p/switch.go similarity index 100% rename from switch.go rename to p2p/switch.go diff --git a/switch_test.go b/p2p/switch_test.go similarity index 100% rename from switch_test.go rename to p2p/switch_test.go diff --git a/types.go b/p2p/types.go similarity index 100% rename from types.go rename to p2p/types.go diff --git a/upnp/README.md b/p2p/upnp/README.md similarity index 100% rename from upnp/README.md rename to p2p/upnp/README.md diff --git a/upnp/log.go b/p2p/upnp/log.go similarity index 100% rename from upnp/log.go rename to p2p/upnp/log.go diff --git a/upnp/probe.go b/p2p/upnp/probe.go similarity index 100% rename from upnp/probe.go rename to p2p/upnp/probe.go diff --git a/upnp/upnp.go b/p2p/upnp/upnp.go similarity index 100% rename from upnp/upnp.go rename to p2p/upnp/upnp.go diff --git a/util.go b/p2p/util.go similarity index 100% rename from util.go rename to p2p/util.go diff --git a/version.go b/p2p/version.go similarity index 100% rename from version.go rename to p2p/version.go From 93c58d0b24b7aa702455dd4157a358733baaf3bf Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 21 Apr 2017 18:08:25 -0400 Subject: [PATCH 187/309] remove glide and license from rpc and p2p --- p2p/LICENSE | 193 ----------------------------------------------- p2p/glide.lock | 73 ------------------ p2p/glide.yaml | 29 ------- rpc/LICENSE | 201 ------------------------------------------------- 4 files changed, 496 deletions(-) delete mode 100644 p2p/LICENSE delete mode 100644 p2p/glide.lock delete mode 100644 p2p/glide.yaml delete mode 100644 rpc/LICENSE diff --git a/p2p/LICENSE b/p2p/LICENSE deleted file mode 100644 index e908e0f95..000000000 --- a/p2p/LICENSE +++ /dev/null @@ -1,193 +0,0 @@ -Tendermint Go-P2P -Copyright (C) 2015 Tendermint - - - - Apache License - Version 2.0, January 2004 - https://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - https://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/p2p/glide.lock b/p2p/glide.lock deleted file mode 100644 index 5da4e6230..000000000 --- a/p2p/glide.lock +++ /dev/null @@ -1,73 +0,0 @@ -hash: f3d76bef9548cc37ad6038cb55f0812bac7e64735a99995c9da85010eef27f50 -updated: 2017-04-19T00:00:50.949249104-04:00 -imports: -- name: github.com/btcsuite/btcd - version: b8df516b4b267acf2de46be593a9d948d1d2c420 - subpackages: - - btcec -- name: github.com/btcsuite/fastsha256 - version: 637e656429416087660c84436a2a035d69d54e2e -- name: github.com/BurntSushi/toml - version: 99064174e013895bbd9b025c31100bd1d9b590ca -- name: github.com/go-stack/stack - version: 100eb0c0a9c5b306ca2fb4f165df21d80ada4b82 -- name: github.com/mattn/go-colorable - version: 9fdad7c47650b7d2e1da50644c1f4ba7f172f252 -- name: github.com/mattn/go-isatty - version: 56b76bdf51f7708750eac80fa38b952bb9f32639 -- name: github.com/pkg/errors - version: 645ef00459ed84a119197bfb8d8205042c6df63d -- name: github.com/tendermint/ed25519 - version: 1f52c6f8b8a5c7908aff4497c186af344b428925 - subpackages: - - edwards25519 - - extra25519 -- name: github.com/tendermint/tmlibs/common - version: f9e3db037330c8a8d61d3966de8473eaf01154fa -- name: github.com/tendermint/go-config - version: 620dcbbd7d587cf3599dedbf329b64311b0c307a -- name: github.com/tendermint/go-crypto - version: 0ca2c6fdb0706001ca4c4b9b80c9f428e8cf39da -- name: github.com/tendermint/go-wire/data - version: e7fcc6d081ec8518912fcdc103188275f83a3ee5 -- name: github.com/tendermint/tmlibs/flowrate - version: a20c98e61957faa93b4014fbd902f20ab9317a6a - subpackages: - - flowrate -- name: github.com/tendermint/tmlibs/logger - version: cefb3a45c0bf3c493a04e9bcd9b1540528be59f2 -- name: github.com/tendermint/go-wire - version: c1c9a57ab8038448ddea1714c0698f8051e5748c -- name: github.com/tendermint/log15 - version: ae0f3d6450da9eac7074b439c8e1c3cabf0d5ce6 - subpackages: - - term -- name: golang.org/x/crypto - version: 1f22c0103821b9390939b6776727195525381532 - subpackages: - - curve25519 - - nacl/box - - nacl/secretbox - - openpgp/armor - - openpgp/errors - - poly1305 - - ripemd160 - - salsa20/salsa -- name: golang.org/x/sys - version: 50c6bc5e4292a1d4e65c6e9be5f53be28bcbe28e - subpackages: - - unix -testImports: -- name: github.com/davecgh/go-spew - version: 6d212800a42e8ab5c146b8ace3490ee17e5225f9 - subpackages: - - spew -- name: github.com/pmezard/go-difflib - version: d8ed2627bdf02c080bf22230dbb337003b7aba2d - subpackages: - - difflib -- name: github.com/stretchr/testify - version: 69483b4bd14f5845b5a1e55bca19e954e827f1d0 - subpackages: - - assert - - require diff --git a/p2p/glide.yaml b/p2p/glide.yaml deleted file mode 100644 index 5bf7a015e..000000000 --- a/p2p/glide.yaml +++ /dev/null @@ -1,29 +0,0 @@ -package: github.com/tendermint/go-p2p -import: -- package: github.com/tendermint/tmlibs/common - version: develop -- package: github.com/tendermint/go-config - version: develop -- package: github.com/tendermint/go-crypto - version: develop -- package: github.com/tendermint/go-wire/data - version: develop -- package: github.com/tendermint/tmlibs/flowrate - subpackages: - - flowrate -- package: github.com/tendermint/tmlibs/logger - version: develop -- package: github.com/tendermint/go-wire - version: develop -- package: github.com/tendermint/log15 -- package: golang.org/x/crypto - subpackages: - - nacl/box - - nacl/secretbox - - ripemd160 -- package: github.com/pkg/errors -testImport: -- package: github.com/stretchr/testify - subpackages: - - assert - - require diff --git a/rpc/LICENSE b/rpc/LICENSE deleted file mode 100644 index 8dada3eda..000000000 --- a/rpc/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "{}" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright {yyyy} {name of copyright owner} - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. From 5da9b3a80302a93fc9315a05ee6c7184a9f808f8 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 21 Apr 2017 18:09:47 -0400 Subject: [PATCH 188/309] postmerge --- premerge/CHANGELOG.md => CHANGELOG.md | 0 premerge/CONTRIBUTING.md => CONTRIBUTING.md | 0 premerge/INSTALL.md => INSTALL.md | 0 premerge/LICENSE => LICENSE | 0 premerge/Makefile => Makefile | 0 premerge/README.md => README.md | 0 premerge/Vagrantfile => Vagrantfile | 0 premerge/circle.yml => circle.yml | 0 premerge/glide.lock => glide.lock | 0 premerge/glide.yaml => glide.yaml | 0 {premerge/test => test}/README.md | 0 {premerge/test => test}/app/clean.sh | 0 {premerge/test => test}/app/counter_test.sh | 0 {premerge/test => test}/app/dummy_test.sh | 0 {premerge/test => test}/app/grpc_client.go | 0 {premerge/test => test}/app/test.sh | 0 {premerge/test => test}/docker/Dockerfile | 0 {premerge/test => test}/docker/build.sh | 0 {premerge/test => test}/docker/update.sh | 0 {premerge/test => test}/net/setup.sh | 0 {premerge/test => test}/net/start.sh | 0 {premerge/test => test}/net/test.sh | 0 {premerge/test => test}/p2p/README.md | 0 {premerge/test => test}/p2p/atomic_broadcast/test.sh | 0 {premerge/test => test}/p2p/basic/test.sh | 0 {premerge/test => test}/p2p/clean.sh | 0 {premerge/test => test}/p2p/client.sh | 0 {premerge/test => test}/p2p/data/app/init.sh | 0 {premerge/test => test}/p2p/data/chain_config.json | 0 {premerge/test => test}/p2p/data/core/init.sh | 0 {premerge/test => test}/p2p/data/data/init.sh | 0 {premerge/test => test}/p2p/data/mach1/core/genesis.json | 0 {premerge/test => test}/p2p/data/mach1/core/priv_validator.json | 0 {premerge/test => test}/p2p/data/mach2/core/genesis.json | 0 {premerge/test => test}/p2p/data/mach2/core/priv_validator.json | 0 {premerge/test => test}/p2p/data/mach3/core/genesis.json | 0 {premerge/test => test}/p2p/data/mach3/core/priv_validator.json | 0 {premerge/test => test}/p2p/data/mach4/core/genesis.json | 0 {premerge/test => test}/p2p/data/mach4/core/priv_validator.json | 0 {premerge/test => test}/p2p/fast_sync/check_peer.sh | 0 {premerge/test => test}/p2p/fast_sync/test.sh | 0 {premerge/test => test}/p2p/fast_sync/test_peer.sh | 0 {premerge/test => test}/p2p/ip.sh | 0 {premerge/test => test}/p2p/kill_all/check_peers.sh | 0 {premerge/test => test}/p2p/kill_all/test.sh | 0 {premerge/test => test}/p2p/local_testnet_start.sh | 0 {premerge/test => test}/p2p/local_testnet_stop.sh | 0 {premerge/test => test}/p2p/peer.sh | 0 {premerge/test => test}/p2p/pex/check_peer.sh | 0 {premerge/test => test}/p2p/pex/dial_seeds.sh | 0 {premerge/test => test}/p2p/pex/test.sh | 0 {premerge/test => test}/p2p/pex/test_addrbook.sh | 0 {premerge/test => test}/p2p/pex/test_dial_seeds.sh | 0 {premerge/test => test}/p2p/seeds.sh | 0 {premerge/test => test}/p2p/test.sh | 0 {premerge/test => test}/persist/test.sh | 0 {premerge/test => test}/persist/test_failure_indices.sh | 0 {premerge/test => test}/persist/test_simple.sh | 0 {premerge/test => test}/run_test.sh | 0 {premerge/test => test}/test.sh | 0 {premerge/test => test}/test_cover.sh | 0 {premerge/test => test}/test_libs.sh | 0 {premerge/test => test}/utils/txs.sh | 0 {premerge/types => types}/block.go | 0 {premerge/types => types}/block_meta.go | 0 {premerge/types => types}/canonical_json.go | 0 {premerge/types => types}/events.go | 0 {premerge/types => types}/genesis.go | 0 {premerge/types => types}/keys.go | 0 {premerge/types => types}/log.go | 0 {premerge/types => types}/part_set.go | 0 {premerge/types => types}/part_set_test.go | 0 {premerge/types => types}/priv_validator.go | 0 {premerge/types => types}/priv_validator_test.go | 0 {premerge/types => types}/proposal.go | 0 {premerge/types => types}/proposal_test.go | 0 {premerge/types => types}/protobuf.go | 0 {premerge/types => types}/services.go | 0 {premerge/types => types}/signable.go | 0 {premerge/types => types}/tx.go | 0 {premerge/types => types}/tx_test.go | 0 {premerge/types => types}/validator.go | 0 {premerge/types => types}/validator_set.go | 0 {premerge/types => types}/validator_set_test.go | 0 {premerge/types => types}/vote.go | 0 {premerge/types => types}/vote_set.go | 0 {premerge/types => types}/vote_set_test.go | 0 {premerge/types => types}/vote_test.go | 0 88 files changed, 0 insertions(+), 0 deletions(-) rename premerge/CHANGELOG.md => CHANGELOG.md (100%) rename premerge/CONTRIBUTING.md => CONTRIBUTING.md (100%) rename premerge/INSTALL.md => INSTALL.md (100%) rename premerge/LICENSE => LICENSE (100%) rename premerge/Makefile => Makefile (100%) rename premerge/README.md => README.md (100%) rename premerge/Vagrantfile => Vagrantfile (100%) rename premerge/circle.yml => circle.yml (100%) rename premerge/glide.lock => glide.lock (100%) rename premerge/glide.yaml => glide.yaml (100%) rename {premerge/test => test}/README.md (100%) rename {premerge/test => test}/app/clean.sh (100%) rename {premerge/test => test}/app/counter_test.sh (100%) rename {premerge/test => test}/app/dummy_test.sh (100%) rename {premerge/test => test}/app/grpc_client.go (100%) rename {premerge/test => test}/app/test.sh (100%) rename {premerge/test => test}/docker/Dockerfile (100%) rename {premerge/test => test}/docker/build.sh (100%) rename {premerge/test => test}/docker/update.sh (100%) rename {premerge/test => test}/net/setup.sh (100%) rename {premerge/test => test}/net/start.sh (100%) rename {premerge/test => test}/net/test.sh (100%) rename {premerge/test => test}/p2p/README.md (100%) rename {premerge/test => test}/p2p/atomic_broadcast/test.sh (100%) rename {premerge/test => test}/p2p/basic/test.sh (100%) rename {premerge/test => test}/p2p/clean.sh (100%) rename {premerge/test => test}/p2p/client.sh (100%) rename {premerge/test => test}/p2p/data/app/init.sh (100%) rename {premerge/test => test}/p2p/data/chain_config.json (100%) rename {premerge/test => test}/p2p/data/core/init.sh (100%) rename {premerge/test => test}/p2p/data/data/init.sh (100%) rename {premerge/test => test}/p2p/data/mach1/core/genesis.json (100%) rename {premerge/test => test}/p2p/data/mach1/core/priv_validator.json (100%) rename {premerge/test => test}/p2p/data/mach2/core/genesis.json (100%) rename {premerge/test => test}/p2p/data/mach2/core/priv_validator.json (100%) rename {premerge/test => test}/p2p/data/mach3/core/genesis.json (100%) rename {premerge/test => test}/p2p/data/mach3/core/priv_validator.json (100%) rename {premerge/test => test}/p2p/data/mach4/core/genesis.json (100%) rename {premerge/test => test}/p2p/data/mach4/core/priv_validator.json (100%) rename {premerge/test => test}/p2p/fast_sync/check_peer.sh (100%) rename {premerge/test => test}/p2p/fast_sync/test.sh (100%) rename {premerge/test => test}/p2p/fast_sync/test_peer.sh (100%) rename {premerge/test => test}/p2p/ip.sh (100%) rename {premerge/test => test}/p2p/kill_all/check_peers.sh (100%) rename {premerge/test => test}/p2p/kill_all/test.sh (100%) rename {premerge/test => test}/p2p/local_testnet_start.sh (100%) rename {premerge/test => test}/p2p/local_testnet_stop.sh (100%) rename {premerge/test => test}/p2p/peer.sh (100%) rename {premerge/test => test}/p2p/pex/check_peer.sh (100%) rename {premerge/test => test}/p2p/pex/dial_seeds.sh (100%) rename {premerge/test => test}/p2p/pex/test.sh (100%) rename {premerge/test => test}/p2p/pex/test_addrbook.sh (100%) rename {premerge/test => test}/p2p/pex/test_dial_seeds.sh (100%) rename {premerge/test => test}/p2p/seeds.sh (100%) rename {premerge/test => test}/p2p/test.sh (100%) rename {premerge/test => test}/persist/test.sh (100%) rename {premerge/test => test}/persist/test_failure_indices.sh (100%) rename {premerge/test => test}/persist/test_simple.sh (100%) rename {premerge/test => test}/run_test.sh (100%) rename {premerge/test => test}/test.sh (100%) rename {premerge/test => test}/test_cover.sh (100%) rename {premerge/test => test}/test_libs.sh (100%) rename {premerge/test => test}/utils/txs.sh (100%) rename {premerge/types => types}/block.go (100%) rename {premerge/types => types}/block_meta.go (100%) rename {premerge/types => types}/canonical_json.go (100%) rename {premerge/types => types}/events.go (100%) rename {premerge/types => types}/genesis.go (100%) rename {premerge/types => types}/keys.go (100%) rename {premerge/types => types}/log.go (100%) rename {premerge/types => types}/part_set.go (100%) rename {premerge/types => types}/part_set_test.go (100%) rename {premerge/types => types}/priv_validator.go (100%) rename {premerge/types => types}/priv_validator_test.go (100%) rename {premerge/types => types}/proposal.go (100%) rename {premerge/types => types}/proposal_test.go (100%) rename {premerge/types => types}/protobuf.go (100%) rename {premerge/types => types}/services.go (100%) rename {premerge/types => types}/signable.go (100%) rename {premerge/types => types}/tx.go (100%) rename {premerge/types => types}/tx_test.go (100%) rename {premerge/types => types}/validator.go (100%) rename {premerge/types => types}/validator_set.go (100%) rename {premerge/types => types}/validator_set_test.go (100%) rename {premerge/types => types}/vote.go (100%) rename {premerge/types => types}/vote_set.go (100%) rename {premerge/types => types}/vote_set_test.go (100%) rename {premerge/types => types}/vote_test.go (100%) diff --git a/premerge/CHANGELOG.md b/CHANGELOG.md similarity index 100% rename from premerge/CHANGELOG.md rename to CHANGELOG.md diff --git a/premerge/CONTRIBUTING.md b/CONTRIBUTING.md similarity index 100% rename from premerge/CONTRIBUTING.md rename to CONTRIBUTING.md diff --git a/premerge/INSTALL.md b/INSTALL.md similarity index 100% rename from premerge/INSTALL.md rename to INSTALL.md diff --git a/premerge/LICENSE b/LICENSE similarity index 100% rename from premerge/LICENSE rename to LICENSE diff --git a/premerge/Makefile b/Makefile similarity index 100% rename from premerge/Makefile rename to Makefile diff --git a/premerge/README.md b/README.md similarity index 100% rename from premerge/README.md rename to README.md diff --git a/premerge/Vagrantfile b/Vagrantfile similarity index 100% rename from premerge/Vagrantfile rename to Vagrantfile diff --git a/premerge/circle.yml b/circle.yml similarity index 100% rename from premerge/circle.yml rename to circle.yml diff --git a/premerge/glide.lock b/glide.lock similarity index 100% rename from premerge/glide.lock rename to glide.lock diff --git a/premerge/glide.yaml b/glide.yaml similarity index 100% rename from premerge/glide.yaml rename to glide.yaml diff --git a/premerge/test/README.md b/test/README.md similarity index 100% rename from premerge/test/README.md rename to test/README.md diff --git a/premerge/test/app/clean.sh b/test/app/clean.sh similarity index 100% rename from premerge/test/app/clean.sh rename to test/app/clean.sh diff --git a/premerge/test/app/counter_test.sh b/test/app/counter_test.sh similarity index 100% rename from premerge/test/app/counter_test.sh rename to test/app/counter_test.sh diff --git a/premerge/test/app/dummy_test.sh b/test/app/dummy_test.sh similarity index 100% rename from premerge/test/app/dummy_test.sh rename to test/app/dummy_test.sh diff --git a/premerge/test/app/grpc_client.go b/test/app/grpc_client.go similarity index 100% rename from premerge/test/app/grpc_client.go rename to test/app/grpc_client.go diff --git a/premerge/test/app/test.sh b/test/app/test.sh similarity index 100% rename from premerge/test/app/test.sh rename to test/app/test.sh diff --git a/premerge/test/docker/Dockerfile b/test/docker/Dockerfile similarity index 100% rename from premerge/test/docker/Dockerfile rename to test/docker/Dockerfile diff --git a/premerge/test/docker/build.sh b/test/docker/build.sh similarity index 100% rename from premerge/test/docker/build.sh rename to test/docker/build.sh diff --git a/premerge/test/docker/update.sh b/test/docker/update.sh similarity index 100% rename from premerge/test/docker/update.sh rename to test/docker/update.sh diff --git a/premerge/test/net/setup.sh b/test/net/setup.sh similarity index 100% rename from premerge/test/net/setup.sh rename to test/net/setup.sh diff --git a/premerge/test/net/start.sh b/test/net/start.sh similarity index 100% rename from premerge/test/net/start.sh rename to test/net/start.sh diff --git a/premerge/test/net/test.sh b/test/net/test.sh similarity index 100% rename from premerge/test/net/test.sh rename to test/net/test.sh diff --git a/premerge/test/p2p/README.md b/test/p2p/README.md similarity index 100% rename from premerge/test/p2p/README.md rename to test/p2p/README.md diff --git a/premerge/test/p2p/atomic_broadcast/test.sh b/test/p2p/atomic_broadcast/test.sh similarity index 100% rename from premerge/test/p2p/atomic_broadcast/test.sh rename to test/p2p/atomic_broadcast/test.sh diff --git a/premerge/test/p2p/basic/test.sh b/test/p2p/basic/test.sh similarity index 100% rename from premerge/test/p2p/basic/test.sh rename to test/p2p/basic/test.sh diff --git a/premerge/test/p2p/clean.sh b/test/p2p/clean.sh similarity index 100% rename from premerge/test/p2p/clean.sh rename to test/p2p/clean.sh diff --git a/premerge/test/p2p/client.sh b/test/p2p/client.sh similarity index 100% rename from premerge/test/p2p/client.sh rename to test/p2p/client.sh diff --git a/premerge/test/p2p/data/app/init.sh b/test/p2p/data/app/init.sh similarity index 100% rename from premerge/test/p2p/data/app/init.sh rename to test/p2p/data/app/init.sh diff --git a/premerge/test/p2p/data/chain_config.json b/test/p2p/data/chain_config.json similarity index 100% rename from premerge/test/p2p/data/chain_config.json rename to test/p2p/data/chain_config.json diff --git a/premerge/test/p2p/data/core/init.sh b/test/p2p/data/core/init.sh similarity index 100% rename from premerge/test/p2p/data/core/init.sh rename to test/p2p/data/core/init.sh diff --git a/premerge/test/p2p/data/data/init.sh b/test/p2p/data/data/init.sh similarity index 100% rename from premerge/test/p2p/data/data/init.sh rename to test/p2p/data/data/init.sh diff --git a/premerge/test/p2p/data/mach1/core/genesis.json b/test/p2p/data/mach1/core/genesis.json similarity index 100% rename from premerge/test/p2p/data/mach1/core/genesis.json rename to test/p2p/data/mach1/core/genesis.json diff --git a/premerge/test/p2p/data/mach1/core/priv_validator.json b/test/p2p/data/mach1/core/priv_validator.json similarity index 100% rename from premerge/test/p2p/data/mach1/core/priv_validator.json rename to test/p2p/data/mach1/core/priv_validator.json diff --git a/premerge/test/p2p/data/mach2/core/genesis.json b/test/p2p/data/mach2/core/genesis.json similarity index 100% rename from premerge/test/p2p/data/mach2/core/genesis.json rename to test/p2p/data/mach2/core/genesis.json diff --git a/premerge/test/p2p/data/mach2/core/priv_validator.json b/test/p2p/data/mach2/core/priv_validator.json similarity index 100% rename from premerge/test/p2p/data/mach2/core/priv_validator.json rename to test/p2p/data/mach2/core/priv_validator.json diff --git a/premerge/test/p2p/data/mach3/core/genesis.json b/test/p2p/data/mach3/core/genesis.json similarity index 100% rename from premerge/test/p2p/data/mach3/core/genesis.json rename to test/p2p/data/mach3/core/genesis.json diff --git a/premerge/test/p2p/data/mach3/core/priv_validator.json b/test/p2p/data/mach3/core/priv_validator.json similarity index 100% rename from premerge/test/p2p/data/mach3/core/priv_validator.json rename to test/p2p/data/mach3/core/priv_validator.json diff --git a/premerge/test/p2p/data/mach4/core/genesis.json b/test/p2p/data/mach4/core/genesis.json similarity index 100% rename from premerge/test/p2p/data/mach4/core/genesis.json rename to test/p2p/data/mach4/core/genesis.json diff --git a/premerge/test/p2p/data/mach4/core/priv_validator.json b/test/p2p/data/mach4/core/priv_validator.json similarity index 100% rename from premerge/test/p2p/data/mach4/core/priv_validator.json rename to test/p2p/data/mach4/core/priv_validator.json diff --git a/premerge/test/p2p/fast_sync/check_peer.sh b/test/p2p/fast_sync/check_peer.sh similarity index 100% rename from premerge/test/p2p/fast_sync/check_peer.sh rename to test/p2p/fast_sync/check_peer.sh diff --git a/premerge/test/p2p/fast_sync/test.sh b/test/p2p/fast_sync/test.sh similarity index 100% rename from premerge/test/p2p/fast_sync/test.sh rename to test/p2p/fast_sync/test.sh diff --git a/premerge/test/p2p/fast_sync/test_peer.sh b/test/p2p/fast_sync/test_peer.sh similarity index 100% rename from premerge/test/p2p/fast_sync/test_peer.sh rename to test/p2p/fast_sync/test_peer.sh diff --git a/premerge/test/p2p/ip.sh b/test/p2p/ip.sh similarity index 100% rename from premerge/test/p2p/ip.sh rename to test/p2p/ip.sh diff --git a/premerge/test/p2p/kill_all/check_peers.sh b/test/p2p/kill_all/check_peers.sh similarity index 100% rename from premerge/test/p2p/kill_all/check_peers.sh rename to test/p2p/kill_all/check_peers.sh diff --git a/premerge/test/p2p/kill_all/test.sh b/test/p2p/kill_all/test.sh similarity index 100% rename from premerge/test/p2p/kill_all/test.sh rename to test/p2p/kill_all/test.sh diff --git a/premerge/test/p2p/local_testnet_start.sh b/test/p2p/local_testnet_start.sh similarity index 100% rename from premerge/test/p2p/local_testnet_start.sh rename to test/p2p/local_testnet_start.sh diff --git a/premerge/test/p2p/local_testnet_stop.sh b/test/p2p/local_testnet_stop.sh similarity index 100% rename from premerge/test/p2p/local_testnet_stop.sh rename to test/p2p/local_testnet_stop.sh diff --git a/premerge/test/p2p/peer.sh b/test/p2p/peer.sh similarity index 100% rename from premerge/test/p2p/peer.sh rename to test/p2p/peer.sh diff --git a/premerge/test/p2p/pex/check_peer.sh b/test/p2p/pex/check_peer.sh similarity index 100% rename from premerge/test/p2p/pex/check_peer.sh rename to test/p2p/pex/check_peer.sh diff --git a/premerge/test/p2p/pex/dial_seeds.sh b/test/p2p/pex/dial_seeds.sh similarity index 100% rename from premerge/test/p2p/pex/dial_seeds.sh rename to test/p2p/pex/dial_seeds.sh diff --git a/premerge/test/p2p/pex/test.sh b/test/p2p/pex/test.sh similarity index 100% rename from premerge/test/p2p/pex/test.sh rename to test/p2p/pex/test.sh diff --git a/premerge/test/p2p/pex/test_addrbook.sh b/test/p2p/pex/test_addrbook.sh similarity index 100% rename from premerge/test/p2p/pex/test_addrbook.sh rename to test/p2p/pex/test_addrbook.sh diff --git a/premerge/test/p2p/pex/test_dial_seeds.sh b/test/p2p/pex/test_dial_seeds.sh similarity index 100% rename from premerge/test/p2p/pex/test_dial_seeds.sh rename to test/p2p/pex/test_dial_seeds.sh diff --git a/premerge/test/p2p/seeds.sh b/test/p2p/seeds.sh similarity index 100% rename from premerge/test/p2p/seeds.sh rename to test/p2p/seeds.sh diff --git a/premerge/test/p2p/test.sh b/test/p2p/test.sh similarity index 100% rename from premerge/test/p2p/test.sh rename to test/p2p/test.sh diff --git a/premerge/test/persist/test.sh b/test/persist/test.sh similarity index 100% rename from premerge/test/persist/test.sh rename to test/persist/test.sh diff --git a/premerge/test/persist/test_failure_indices.sh b/test/persist/test_failure_indices.sh similarity index 100% rename from premerge/test/persist/test_failure_indices.sh rename to test/persist/test_failure_indices.sh diff --git a/premerge/test/persist/test_simple.sh b/test/persist/test_simple.sh similarity index 100% rename from premerge/test/persist/test_simple.sh rename to test/persist/test_simple.sh diff --git a/premerge/test/run_test.sh b/test/run_test.sh similarity index 100% rename from premerge/test/run_test.sh rename to test/run_test.sh diff --git a/premerge/test/test.sh b/test/test.sh similarity index 100% rename from premerge/test/test.sh rename to test/test.sh diff --git a/premerge/test/test_cover.sh b/test/test_cover.sh similarity index 100% rename from premerge/test/test_cover.sh rename to test/test_cover.sh diff --git a/premerge/test/test_libs.sh b/test/test_libs.sh similarity index 100% rename from premerge/test/test_libs.sh rename to test/test_libs.sh diff --git a/premerge/test/utils/txs.sh b/test/utils/txs.sh similarity index 100% rename from premerge/test/utils/txs.sh rename to test/utils/txs.sh diff --git a/premerge/types/block.go b/types/block.go similarity index 100% rename from premerge/types/block.go rename to types/block.go diff --git a/premerge/types/block_meta.go b/types/block_meta.go similarity index 100% rename from premerge/types/block_meta.go rename to types/block_meta.go diff --git a/premerge/types/canonical_json.go b/types/canonical_json.go similarity index 100% rename from premerge/types/canonical_json.go rename to types/canonical_json.go diff --git a/premerge/types/events.go b/types/events.go similarity index 100% rename from premerge/types/events.go rename to types/events.go diff --git a/premerge/types/genesis.go b/types/genesis.go similarity index 100% rename from premerge/types/genesis.go rename to types/genesis.go diff --git a/premerge/types/keys.go b/types/keys.go similarity index 100% rename from premerge/types/keys.go rename to types/keys.go diff --git a/premerge/types/log.go b/types/log.go similarity index 100% rename from premerge/types/log.go rename to types/log.go diff --git a/premerge/types/part_set.go b/types/part_set.go similarity index 100% rename from premerge/types/part_set.go rename to types/part_set.go diff --git a/premerge/types/part_set_test.go b/types/part_set_test.go similarity index 100% rename from premerge/types/part_set_test.go rename to types/part_set_test.go diff --git a/premerge/types/priv_validator.go b/types/priv_validator.go similarity index 100% rename from premerge/types/priv_validator.go rename to types/priv_validator.go diff --git a/premerge/types/priv_validator_test.go b/types/priv_validator_test.go similarity index 100% rename from premerge/types/priv_validator_test.go rename to types/priv_validator_test.go diff --git a/premerge/types/proposal.go b/types/proposal.go similarity index 100% rename from premerge/types/proposal.go rename to types/proposal.go diff --git a/premerge/types/proposal_test.go b/types/proposal_test.go similarity index 100% rename from premerge/types/proposal_test.go rename to types/proposal_test.go diff --git a/premerge/types/protobuf.go b/types/protobuf.go similarity index 100% rename from premerge/types/protobuf.go rename to types/protobuf.go diff --git a/premerge/types/services.go b/types/services.go similarity index 100% rename from premerge/types/services.go rename to types/services.go diff --git a/premerge/types/signable.go b/types/signable.go similarity index 100% rename from premerge/types/signable.go rename to types/signable.go diff --git a/premerge/types/tx.go b/types/tx.go similarity index 100% rename from premerge/types/tx.go rename to types/tx.go diff --git a/premerge/types/tx_test.go b/types/tx_test.go similarity index 100% rename from premerge/types/tx_test.go rename to types/tx_test.go diff --git a/premerge/types/validator.go b/types/validator.go similarity index 100% rename from premerge/types/validator.go rename to types/validator.go diff --git a/premerge/types/validator_set.go b/types/validator_set.go similarity index 100% rename from premerge/types/validator_set.go rename to types/validator_set.go diff --git a/premerge/types/validator_set_test.go b/types/validator_set_test.go similarity index 100% rename from premerge/types/validator_set_test.go rename to types/validator_set_test.go diff --git a/premerge/types/vote.go b/types/vote.go similarity index 100% rename from premerge/types/vote.go rename to types/vote.go diff --git a/premerge/types/vote_set.go b/types/vote_set.go similarity index 100% rename from premerge/types/vote_set.go rename to types/vote_set.go diff --git a/premerge/types/vote_set_test.go b/types/vote_set_test.go similarity index 100% rename from premerge/types/vote_set_test.go rename to types/vote_set_test.go diff --git a/premerge/types/vote_test.go b/types/vote_test.go similarity index 100% rename from premerge/types/vote_test.go rename to types/vote_test.go From fa451fc55cabd90fe63042f747c7798b301fdc9f Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 21 Apr 2017 18:10:41 -0400 Subject: [PATCH 189/309] tendermint/rpc -> tendermint/rpc/tendermint --- benchmarks/codec_test.go | 2 +- benchmarks/simu/counter.go | 2 +- node/node.go | 4 ++-- rpc/tendermint/client/event_test.go | 2 +- rpc/tendermint/client/helpers_test.go | 6 +++--- rpc/tendermint/client/httpclient.go | 2 +- rpc/tendermint/client/interface.go | 2 +- rpc/tendermint/client/localclient.go | 4 ++-- rpc/tendermint/client/main_test.go | 2 +- rpc/tendermint/client/mock/abci.go | 4 ++-- rpc/tendermint/client/mock/abci_test.go | 4 ++-- rpc/tendermint/client/mock/client.go | 6 +++--- rpc/tendermint/client/mock/status.go | 4 ++-- rpc/tendermint/client/mock/status_test.go | 4 ++-- rpc/tendermint/client/rpc_test.go | 4 ++-- rpc/tendermint/core/abci.go | 2 +- rpc/tendermint/core/blocks.go | 2 +- rpc/tendermint/core/consensus.go | 2 +- rpc/tendermint/core/dev.go | 2 +- rpc/tendermint/core/events.go | 2 +- rpc/tendermint/core/mempool.go | 2 +- rpc/tendermint/core/net.go | 2 +- rpc/tendermint/core/routes.go | 2 +- rpc/tendermint/core/status.go | 2 +- rpc/tendermint/core/tx.go | 2 +- rpc/tendermint/grpc/api.go | 2 +- rpc/tendermint/test/client_test.go | 4 ++-- rpc/tendermint/test/grpc_test.go | 2 +- rpc/tendermint/test/helpers.go | 4 ++-- test/app/grpc_client.go | 2 +- 30 files changed, 43 insertions(+), 43 deletions(-) diff --git a/benchmarks/codec_test.go b/benchmarks/codec_test.go index 0e77156cf..218b3fd04 100644 --- a/benchmarks/codec_test.go +++ b/benchmarks/codec_test.go @@ -7,7 +7,7 @@ import ( "github.com/tendermint/go-p2p" "github.com/tendermint/go-wire" proto "github.com/tendermint/tendermint/benchmarks/proto" - ctypes "github.com/tendermint/tendermint/rpc/core/types" + ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" ) func BenchmarkEncodeStatusWire(b *testing.B) { diff --git a/benchmarks/simu/counter.go b/benchmarks/simu/counter.go index 36d1e35df..e50447669 100644 --- a/benchmarks/simu/counter.go +++ b/benchmarks/simu/counter.go @@ -11,7 +11,7 @@ import ( "github.com/tendermint/go-rpc/client" "github.com/tendermint/go-rpc/types" "github.com/tendermint/go-wire" - _ "github.com/tendermint/tendermint/rpc/core/types" // Register RPCResponse > Result types + _ "github.com/tendermint/tendermint/rpc/tendermint/core/types" // Register RPCResponse > Result types ) func main() { diff --git a/node/node.go b/node/node.go index 96440e910..84841d5d3 100644 --- a/node/node.go +++ b/node/node.go @@ -20,8 +20,8 @@ import ( "github.com/tendermint/tendermint/consensus" mempl "github.com/tendermint/tendermint/mempool" "github.com/tendermint/tendermint/proxy" - rpccore "github.com/tendermint/tendermint/rpc/core" - grpccore "github.com/tendermint/tendermint/rpc/grpc" + rpccore "github.com/tendermint/tendermint/rpc/tendermint/core" + grpccore "github.com/tendermint/tendermint/rpc/tendermint/grpc" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/state/txindex" "github.com/tendermint/tendermint/state/txindex/kv" diff --git a/rpc/tendermint/client/event_test.go b/rpc/tendermint/client/event_test.go index cc421ad90..a82a284f6 100644 --- a/rpc/tendermint/client/event_test.go +++ b/rpc/tendermint/client/event_test.go @@ -6,7 +6,7 @@ import ( "github.com/stretchr/testify/require" merktest "github.com/tendermint/merkleeyes/testutil" - "github.com/tendermint/tendermint/rpc/client" + "github.com/tendermint/tendermint/rpc/tendermint/client" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/client/helpers_test.go b/rpc/tendermint/client/helpers_test.go index fe1861224..1057a21bd 100644 --- a/rpc/tendermint/client/helpers_test.go +++ b/rpc/tendermint/client/helpers_test.go @@ -7,9 +7,9 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/rpc/client" - "github.com/tendermint/tendermint/rpc/client/mock" - ctypes "github.com/tendermint/tendermint/rpc/core/types" + "github.com/tendermint/tendermint/rpc/tendermint/client" + "github.com/tendermint/tendermint/rpc/tendermint/client/mock" + ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" ) func TestWaitForHeight(t *testing.T) { diff --git a/rpc/tendermint/client/httpclient.go b/rpc/tendermint/client/httpclient.go index 88a592348..cfcd9299f 100644 --- a/rpc/tendermint/client/httpclient.go +++ b/rpc/tendermint/client/httpclient.go @@ -8,7 +8,7 @@ import ( events "github.com/tendermint/go-events" "github.com/tendermint/go-rpc/client" wire "github.com/tendermint/go-wire" - ctypes "github.com/tendermint/tendermint/rpc/core/types" + ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/client/interface.go b/rpc/tendermint/client/interface.go index eb79db8b1..8040d5d99 100644 --- a/rpc/tendermint/client/interface.go +++ b/rpc/tendermint/client/interface.go @@ -21,7 +21,7 @@ package client import ( data "github.com/tendermint/go-data" - ctypes "github.com/tendermint/tendermint/rpc/core/types" + ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/client/localclient.go b/rpc/tendermint/client/localclient.go index 74051d8c9..34242866f 100644 --- a/rpc/tendermint/client/localclient.go +++ b/rpc/tendermint/client/localclient.go @@ -3,8 +3,8 @@ package client import ( data "github.com/tendermint/go-data" nm "github.com/tendermint/tendermint/node" - "github.com/tendermint/tendermint/rpc/core" - ctypes "github.com/tendermint/tendermint/rpc/core/types" + "github.com/tendermint/tendermint/rpc/tendermint/core" + ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/client/main_test.go b/rpc/tendermint/client/main_test.go index 5ec911e5d..494b565ae 100644 --- a/rpc/tendermint/client/main_test.go +++ b/rpc/tendermint/client/main_test.go @@ -6,7 +6,7 @@ import ( meapp "github.com/tendermint/merkleeyes/app" nm "github.com/tendermint/tendermint/node" - rpctest "github.com/tendermint/tendermint/rpc/test" + rpctest "github.com/tendermint/tendermint/rpc/tendermint/test" ) var node *nm.Node diff --git a/rpc/tendermint/client/mock/abci.go b/rpc/tendermint/client/mock/abci.go index 6a9fe6bdf..962744df7 100644 --- a/rpc/tendermint/client/mock/abci.go +++ b/rpc/tendermint/client/mock/abci.go @@ -3,8 +3,8 @@ package mock import ( abci "github.com/tendermint/abci/types" data "github.com/tendermint/go-data" - "github.com/tendermint/tendermint/rpc/client" - ctypes "github.com/tendermint/tendermint/rpc/core/types" + "github.com/tendermint/tendermint/rpc/tendermint/client" + ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/client/mock/abci_test.go b/rpc/tendermint/client/mock/abci_test.go index bb3a734a7..267d19dfc 100644 --- a/rpc/tendermint/client/mock/abci_test.go +++ b/rpc/tendermint/client/mock/abci_test.go @@ -11,10 +11,10 @@ import ( "github.com/tendermint/abci/example/dummy" abci "github.com/tendermint/abci/types" data "github.com/tendermint/go-data" - ctypes "github.com/tendermint/tendermint/rpc/core/types" + ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" "github.com/tendermint/tendermint/types" - "github.com/tendermint/tendermint/rpc/client/mock" + "github.com/tendermint/tendermint/rpc/tendermint/client/mock" ) func TestABCIMock(t *testing.T) { diff --git a/rpc/tendermint/client/mock/client.go b/rpc/tendermint/client/mock/client.go index 478862380..f43346591 100644 --- a/rpc/tendermint/client/mock/client.go +++ b/rpc/tendermint/client/mock/client.go @@ -17,9 +17,9 @@ import ( "reflect" data "github.com/tendermint/go-data" - "github.com/tendermint/tendermint/rpc/client" - "github.com/tendermint/tendermint/rpc/core" - ctypes "github.com/tendermint/tendermint/rpc/core/types" + "github.com/tendermint/tendermint/rpc/tendermint/client" + "github.com/tendermint/tendermint/rpc/tendermint/core" + ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/client/mock/status.go b/rpc/tendermint/client/mock/status.go index af0f5335d..82ec40987 100644 --- a/rpc/tendermint/client/mock/status.go +++ b/rpc/tendermint/client/mock/status.go @@ -1,8 +1,8 @@ package mock import ( - "github.com/tendermint/tendermint/rpc/client" - ctypes "github.com/tendermint/tendermint/rpc/core/types" + "github.com/tendermint/tendermint/rpc/tendermint/client" + ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" ) // StatusMock returns the result specified by the Call diff --git a/rpc/tendermint/client/mock/status_test.go b/rpc/tendermint/client/mock/status_test.go index 12edc8af0..55576fb11 100644 --- a/rpc/tendermint/client/mock/status_test.go +++ b/rpc/tendermint/client/mock/status_test.go @@ -6,9 +6,9 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" data "github.com/tendermint/go-data" - ctypes "github.com/tendermint/tendermint/rpc/core/types" + ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" - "github.com/tendermint/tendermint/rpc/client/mock" + "github.com/tendermint/tendermint/rpc/tendermint/client/mock" ) func TestStatus(t *testing.T) { diff --git a/rpc/tendermint/client/rpc_test.go b/rpc/tendermint/client/rpc_test.go index d9f5d3796..3ead008dc 100644 --- a/rpc/tendermint/client/rpc_test.go +++ b/rpc/tendermint/client/rpc_test.go @@ -8,8 +8,8 @@ import ( "github.com/stretchr/testify/require" merkle "github.com/tendermint/go-merkle" merktest "github.com/tendermint/merkleeyes/testutil" - "github.com/tendermint/tendermint/rpc/client" - rpctest "github.com/tendermint/tendermint/rpc/test" + "github.com/tendermint/tendermint/rpc/tendermint/client" + rpctest "github.com/tendermint/tendermint/rpc/tendermint/test" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/core/abci.go b/rpc/tendermint/core/abci.go index 47b599ada..519c18822 100644 --- a/rpc/tendermint/core/abci.go +++ b/rpc/tendermint/core/abci.go @@ -3,7 +3,7 @@ package core import ( abci "github.com/tendermint/abci/types" data "github.com/tendermint/go-data" - ctypes "github.com/tendermint/tendermint/rpc/core/types" + ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" ) //----------------------------------------------------------------------------- diff --git a/rpc/tendermint/core/blocks.go b/rpc/tendermint/core/blocks.go index 65e47d125..39e185864 100644 --- a/rpc/tendermint/core/blocks.go +++ b/rpc/tendermint/core/blocks.go @@ -3,7 +3,7 @@ package core import ( "fmt" . "github.com/tendermint/go-common" - ctypes "github.com/tendermint/tendermint/rpc/core/types" + ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/core/consensus.go b/rpc/tendermint/core/consensus.go index e2ccce442..e62e61a0c 100644 --- a/rpc/tendermint/core/consensus.go +++ b/rpc/tendermint/core/consensus.go @@ -3,7 +3,7 @@ package core import ( "github.com/tendermint/go-wire" cm "github.com/tendermint/tendermint/consensus" - ctypes "github.com/tendermint/tendermint/rpc/core/types" + ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/core/dev.go b/rpc/tendermint/core/dev.go index 43a989534..2053d7363 100644 --- a/rpc/tendermint/core/dev.go +++ b/rpc/tendermint/core/dev.go @@ -6,7 +6,7 @@ import ( "runtime/pprof" "strconv" - ctypes "github.com/tendermint/tendermint/rpc/core/types" + ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" ) func UnsafeFlushMempool() (*ctypes.ResultUnsafeFlushMempool, error) { diff --git a/rpc/tendermint/core/events.go b/rpc/tendermint/core/events.go index 7dc3c7c31..a92eda3d7 100644 --- a/rpc/tendermint/core/events.go +++ b/rpc/tendermint/core/events.go @@ -2,7 +2,7 @@ package core import ( "github.com/tendermint/go-rpc/types" - ctypes "github.com/tendermint/tendermint/rpc/core/types" + ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/core/mempool.go b/rpc/tendermint/core/mempool.go index 358671635..df5ea8b64 100644 --- a/rpc/tendermint/core/mempool.go +++ b/rpc/tendermint/core/mempool.go @@ -6,7 +6,7 @@ import ( abci "github.com/tendermint/abci/types" data "github.com/tendermint/go-data" - ctypes "github.com/tendermint/tendermint/rpc/core/types" + ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/core/net.go b/rpc/tendermint/core/net.go index 31d9c34ea..499458230 100644 --- a/rpc/tendermint/core/net.go +++ b/rpc/tendermint/core/net.go @@ -3,7 +3,7 @@ package core import ( "fmt" - ctypes "github.com/tendermint/tendermint/rpc/core/types" + ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" ) //----------------------------------------------------------------------------- diff --git a/rpc/tendermint/core/routes.go b/rpc/tendermint/core/routes.go index 58b464208..1b426d1dd 100644 --- a/rpc/tendermint/core/routes.go +++ b/rpc/tendermint/core/routes.go @@ -4,7 +4,7 @@ import ( data "github.com/tendermint/go-data" rpc "github.com/tendermint/go-rpc/server" "github.com/tendermint/go-rpc/types" - ctypes "github.com/tendermint/tendermint/rpc/core/types" + ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/core/status.go b/rpc/tendermint/core/status.go index d7d503802..1a90945b5 100644 --- a/rpc/tendermint/core/status.go +++ b/rpc/tendermint/core/status.go @@ -2,7 +2,7 @@ package core import ( data "github.com/tendermint/go-data" - ctypes "github.com/tendermint/tendermint/rpc/core/types" + ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/core/tx.go b/rpc/tendermint/core/tx.go index 7f3cdd037..7d6a2deb8 100644 --- a/rpc/tendermint/core/tx.go +++ b/rpc/tendermint/core/tx.go @@ -3,7 +3,7 @@ package core import ( "fmt" - ctypes "github.com/tendermint/tendermint/rpc/core/types" + ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" "github.com/tendermint/tendermint/state/txindex/null" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/grpc/api.go b/rpc/tendermint/grpc/api.go index fab811c2e..f28169398 100644 --- a/rpc/tendermint/grpc/api.go +++ b/rpc/tendermint/grpc/api.go @@ -1,7 +1,7 @@ package core_grpc import ( - core "github.com/tendermint/tendermint/rpc/core" + core "github.com/tendermint/tendermint/rpc/tendermint/core" context "golang.org/x/net/context" ) diff --git a/rpc/tendermint/test/client_test.go b/rpc/tendermint/test/client_test.go index 747c5c3cb..390d652e5 100644 --- a/rpc/tendermint/test/client_test.go +++ b/rpc/tendermint/test/client_test.go @@ -13,8 +13,8 @@ import ( abci "github.com/tendermint/abci/types" . "github.com/tendermint/go-common" rpc "github.com/tendermint/go-rpc/client" - "github.com/tendermint/tendermint/rpc/core" - ctypes "github.com/tendermint/tendermint/rpc/core/types" + "github.com/tendermint/tendermint/rpc/tendermint/core" + ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" "github.com/tendermint/tendermint/state/txindex/null" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/test/grpc_test.go b/rpc/tendermint/test/grpc_test.go index 4935a09d9..4fcc3e856 100644 --- a/rpc/tendermint/test/grpc_test.go +++ b/rpc/tendermint/test/grpc_test.go @@ -6,7 +6,7 @@ import ( "golang.org/x/net/context" "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/rpc/grpc" + "github.com/tendermint/tendermint/rpc/tendermint/grpc" ) //------------------------------------------- diff --git a/rpc/tendermint/test/helpers.go b/rpc/tendermint/test/helpers.go index 349980e9c..dbbcebbf8 100644 --- a/rpc/tendermint/test/helpers.go +++ b/rpc/tendermint/test/helpers.go @@ -19,8 +19,8 @@ import ( "github.com/tendermint/tendermint/config/tendermint_test" nm "github.com/tendermint/tendermint/node" "github.com/tendermint/tendermint/proxy" - ctypes "github.com/tendermint/tendermint/rpc/core/types" - core_grpc "github.com/tendermint/tendermint/rpc/grpc" + ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" + core_grpc "github.com/tendermint/tendermint/rpc/tendermint/grpc" "github.com/tendermint/tendermint/types" ) diff --git a/test/app/grpc_client.go b/test/app/grpc_client.go index e43b8ae39..7d55dcd71 100644 --- a/test/app/grpc_client.go +++ b/test/app/grpc_client.go @@ -8,7 +8,7 @@ import ( "golang.org/x/net/context" "github.com/tendermint/go-wire" - "github.com/tendermint/tendermint/rpc/grpc" + "github.com/tendermint/tendermint/rpc/tendermint/grpc" ) var grpcAddr = "tcp://localhost:36656" From d1926bcad178bc3ae99ba879b42ca003f126398d Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 21 Apr 2017 18:12:54 -0400 Subject: [PATCH 190/309] use tmlibs --- CHANGELOG.md | 2 +- benchmarks/map_test.go | 2 +- benchmarks/os_test.go | 2 +- benchmarks/simu/counter.go | 2 +- blockchain/log.go | 2 +- blockchain/pool.go | 4 ++-- blockchain/pool_test.go | 2 +- blockchain/reactor.go | 2 +- blockchain/store.go | 4 ++-- cmd/tendermint/commands/init.go | 2 +- cmd/tendermint/commands/root.go | 2 +- cmd/tendermint/commands/run_node.go | 2 +- cmd/tendermint/commands/testnet.go | 2 +- config/tendermint/config.go | 2 +- config/tendermint_test/config.go | 4 ++-- consensus/byzantine_test.go | 4 ++-- consensus/common_test.go | 4 ++-- consensus/height_vote_set.go | 2 +- consensus/height_vote_set_test.go | 2 +- consensus/log.go | 2 +- consensus/mempool_test.go | 2 +- consensus/reactor.go | 2 +- consensus/reactor_test.go | 2 +- consensus/replay.go | 4 ++-- consensus/replay_file.go | 4 ++-- consensus/replay_test.go | 4 ++-- consensus/state.go | 2 +- consensus/state_test.go | 2 +- consensus/ticker.go | 2 +- consensus/version.go | 2 +- consensus/wal.go | 4 ++-- docs/architecture/merkle.md | 2 +- glide.lock | 12 ++++++------ glide.yaml | 12 ++++++------ mempool/log.go | 2 +- mempool/mempool.go | 6 +++--- mempool/reactor.go | 2 +- node/log.go | 2 +- node/node.go | 4 ++-- proxy/app_conn_test.go | 2 +- proxy/log.go | 2 +- proxy/multi_app_conn.go | 2 +- rpc/tendermint/client/helpers.go | 4 ++-- rpc/tendermint/client/httpclient.go | 4 ++-- rpc/tendermint/core/blocks.go | 2 +- rpc/tendermint/grpc/client_server.go | 2 +- rpc/tendermint/test/client_test.go | 2 +- rpc/tendermint/test/helpers.go | 2 +- state/errors.go | 2 +- state/execution.go | 2 +- state/execution_test.go | 2 +- state/log.go | 2 +- state/state.go | 4 ++-- state/state_test.go | 2 +- state/txindex/kv/kv.go | 2 +- state/txindex/kv/kv_test.go | 2 +- test/test_libs.sh | 2 +- types/block.go | 2 +- types/events.go | 4 ++-- types/genesis.go | 2 +- types/log.go | 2 +- types/part_set.go | 2 +- types/part_set_test.go | 2 +- types/priv_validator.go | 2 +- types/proposal.go | 2 +- types/signable.go | 2 +- types/tx_test.go | 4 ++-- types/validator.go | 2 +- types/validator_set.go | 2 +- types/validator_set_test.go | 2 +- types/vote.go | 2 +- types/vote_set.go | 2 +- types/vote_set_test.go | 4 ++-- 73 files changed, 101 insertions(+), 101 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b1eec2f8e..b7b54bdad 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -144,7 +144,7 @@ IMPROVEMENTS: - Less verbose logging - Better test coverage (37% -> 49%) - Canonical SignBytes for signable types -- Write-Ahead Log for Mempool and Consensus via go-autofile +- Write-Ahead Log for Mempool and Consensus via tmlibs/autofile - Better in-process testing for the consensus reactor and byzantine faults - Better crash/restart testing for individual nodes at preset failure points, and of networks at arbitrary points - Better abstraction over timeout mechanics diff --git a/benchmarks/map_test.go b/benchmarks/map_test.go index ee538e0f3..80edaff7c 100644 --- a/benchmarks/map_test.go +++ b/benchmarks/map_test.go @@ -1,7 +1,7 @@ package benchmarks import ( - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" "testing" ) diff --git a/benchmarks/os_test.go b/benchmarks/os_test.go index 49a160cd0..2c4611c84 100644 --- a/benchmarks/os_test.go +++ b/benchmarks/os_test.go @@ -4,7 +4,7 @@ import ( "os" "testing" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" ) func BenchmarkFileWrite(b *testing.B) { diff --git a/benchmarks/simu/counter.go b/benchmarks/simu/counter.go index e50447669..9a6db3f4c 100644 --- a/benchmarks/simu/counter.go +++ b/benchmarks/simu/counter.go @@ -7,7 +7,7 @@ import ( "fmt" "github.com/gorilla/websocket" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" "github.com/tendermint/go-rpc/client" "github.com/tendermint/go-rpc/types" "github.com/tendermint/go-wire" diff --git a/blockchain/log.go b/blockchain/log.go index 29dc03f6a..9ffee7295 100644 --- a/blockchain/log.go +++ b/blockchain/log.go @@ -1,7 +1,7 @@ package blockchain import ( - "github.com/tendermint/go-logger" + "github.com/tendermint/tmlibs/logger" ) var log = logger.New("module", "blockchain") diff --git a/blockchain/pool.go b/blockchain/pool.go index 0deacd263..6422ef2dc 100644 --- a/blockchain/pool.go +++ b/blockchain/pool.go @@ -5,8 +5,8 @@ import ( "sync" "time" - . "github.com/tendermint/go-common" - flow "github.com/tendermint/go-flowrate/flowrate" + . "github.com/tendermint/tmlibs/common" + flow "github.com/tendermint/tmlibs/flowrate" "github.com/tendermint/tendermint/types" ) diff --git a/blockchain/pool_test.go b/blockchain/pool_test.go index 220bc5ce5..a2eb83a38 100644 --- a/blockchain/pool_test.go +++ b/blockchain/pool_test.go @@ -5,7 +5,7 @@ import ( "testing" "time" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" "github.com/tendermint/tendermint/types" ) diff --git a/blockchain/reactor.go b/blockchain/reactor.go index f88bccc3d..122f03ae2 100644 --- a/blockchain/reactor.go +++ b/blockchain/reactor.go @@ -6,7 +6,7 @@ import ( "reflect" "time" - cmn "github.com/tendermint/go-common" + cmn "github.com/tendermint/tmlibs/common" cfg "github.com/tendermint/go-config" "github.com/tendermint/go-p2p" "github.com/tendermint/go-wire" diff --git a/blockchain/store.go b/blockchain/store.go index ac7cfdafc..a96aa0fb7 100644 --- a/blockchain/store.go +++ b/blockchain/store.go @@ -7,8 +7,8 @@ import ( "io" "sync" - . "github.com/tendermint/go-common" - dbm "github.com/tendermint/go-db" + . "github.com/tendermint/tmlibs/common" + dbm "github.com/tendermint/tmlibs/db" "github.com/tendermint/go-wire" "github.com/tendermint/tendermint/types" ) diff --git a/cmd/tendermint/commands/init.go b/cmd/tendermint/commands/init.go index 366ca4e84..75bc2bf95 100644 --- a/cmd/tendermint/commands/init.go +++ b/cmd/tendermint/commands/init.go @@ -5,7 +5,7 @@ import ( "github.com/spf13/cobra" - cmn "github.com/tendermint/go-common" + cmn "github.com/tendermint/tmlibs/common" "github.com/tendermint/tendermint/types" ) diff --git a/cmd/tendermint/commands/root.go b/cmd/tendermint/commands/root.go index 0cbaa289f..120d53c04 100644 --- a/cmd/tendermint/commands/root.go +++ b/cmd/tendermint/commands/root.go @@ -3,7 +3,7 @@ package commands import ( "github.com/spf13/cobra" - "github.com/tendermint/go-logger" + "github.com/tendermint/tmlibs/logger" tmcfg "github.com/tendermint/tendermint/config/tendermint" ) diff --git a/cmd/tendermint/commands/run_node.go b/cmd/tendermint/commands/run_node.go index a04b52d09..5e0fef32c 100644 --- a/cmd/tendermint/commands/run_node.go +++ b/cmd/tendermint/commands/run_node.go @@ -6,7 +6,7 @@ import ( "github.com/spf13/cobra" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" "github.com/tendermint/tendermint/node" "github.com/tendermint/tendermint/types" ) diff --git a/cmd/tendermint/commands/testnet.go b/cmd/tendermint/commands/testnet.go index 0a2e00ad0..58767eb05 100644 --- a/cmd/tendermint/commands/testnet.go +++ b/cmd/tendermint/commands/testnet.go @@ -7,7 +7,7 @@ import ( "github.com/spf13/cobra" - cmn "github.com/tendermint/go-common" + cmn "github.com/tendermint/tmlibs/common" "github.com/tendermint/tendermint/types" ) diff --git a/config/tendermint/config.go b/config/tendermint/config.go index 5ddde460d..93650eaef 100644 --- a/config/tendermint/config.go +++ b/config/tendermint/config.go @@ -5,7 +5,7 @@ import ( "path" "strings" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" cfg "github.com/tendermint/go-config" ) diff --git a/config/tendermint_test/config.go b/config/tendermint_test/config.go index 78c3bb337..fcdc572b9 100644 --- a/config/tendermint_test/config.go +++ b/config/tendermint_test/config.go @@ -7,9 +7,9 @@ import ( "path" "strings" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" cfg "github.com/tendermint/go-config" - "github.com/tendermint/go-logger" + "github.com/tendermint/tmlibs/logger" ) func init() { diff --git a/consensus/byzantine_test.go b/consensus/byzantine_test.go index cd62f3f08..fabf4e3c7 100644 --- a/consensus/byzantine_test.go +++ b/consensus/byzantine_test.go @@ -7,9 +7,9 @@ import ( "github.com/tendermint/tendermint/config/tendermint_test" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" cfg "github.com/tendermint/go-config" - "github.com/tendermint/go-events" + "github.com/tendermint/tmlibs/events" "github.com/tendermint/go-p2p" "github.com/tendermint/tendermint/types" ) diff --git a/consensus/common_test.go b/consensus/common_test.go index 334c66dc6..6effddb2e 100644 --- a/consensus/common_test.go +++ b/consensus/common_test.go @@ -13,9 +13,9 @@ import ( abcicli "github.com/tendermint/abci/client" abci "github.com/tendermint/abci/types" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" cfg "github.com/tendermint/go-config" - dbm "github.com/tendermint/go-db" + dbm "github.com/tendermint/tmlibs/db" "github.com/tendermint/go-p2p" bc "github.com/tendermint/tendermint/blockchain" "github.com/tendermint/tendermint/config/tendermint_test" diff --git a/consensus/height_vote_set.go b/consensus/height_vote_set.go index e7f4be3b9..b2aebb095 100644 --- a/consensus/height_vote_set.go +++ b/consensus/height_vote_set.go @@ -4,7 +4,7 @@ import ( "strings" "sync" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" "github.com/tendermint/tendermint/types" ) diff --git a/consensus/height_vote_set_test.go b/consensus/height_vote_set_test.go index 3bede25ca..a86cba4f2 100644 --- a/consensus/height_vote_set_test.go +++ b/consensus/height_vote_set_test.go @@ -3,7 +3,7 @@ package consensus import ( "testing" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" "github.com/tendermint/tendermint/config/tendermint_test" "github.com/tendermint/tendermint/types" ) diff --git a/consensus/log.go b/consensus/log.go index edf7a0a8c..3e46c5eea 100644 --- a/consensus/log.go +++ b/consensus/log.go @@ -1,7 +1,7 @@ package consensus import ( - "github.com/tendermint/go-logger" + "github.com/tendermint/tmlibs/logger" ) var log = logger.New("module", "consensus") diff --git a/consensus/mempool_test.go b/consensus/mempool_test.go index 6bfdfda9f..8808185da 100644 --- a/consensus/mempool_test.go +++ b/consensus/mempool_test.go @@ -9,7 +9,7 @@ import ( "github.com/tendermint/tendermint/config/tendermint_test" "github.com/tendermint/tendermint/types" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" ) func init() { diff --git a/consensus/reactor.go b/consensus/reactor.go index c3b1c590f..cd0c069ff 100644 --- a/consensus/reactor.go +++ b/consensus/reactor.go @@ -8,7 +8,7 @@ import ( "sync" "time" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" "github.com/tendermint/go-p2p" "github.com/tendermint/go-wire" sm "github.com/tendermint/tendermint/state" diff --git a/consensus/reactor_test.go b/consensus/reactor_test.go index bc26ffc05..1ebbf8a5b 100644 --- a/consensus/reactor_test.go +++ b/consensus/reactor_test.go @@ -8,7 +8,7 @@ import ( "github.com/tendermint/tendermint/config/tendermint_test" - "github.com/tendermint/go-events" + "github.com/tendermint/tmlibs/events" "github.com/tendermint/go-p2p" "github.com/tendermint/tendermint/types" "github.com/tendermint/abci/example/dummy" diff --git a/consensus/replay.go b/consensus/replay.go index bd0975f4d..931e8893d 100644 --- a/consensus/replay.go +++ b/consensus/replay.go @@ -11,8 +11,8 @@ import ( "time" abci "github.com/tendermint/abci/types" - auto "github.com/tendermint/go-autofile" - . "github.com/tendermint/go-common" + auto "github.com/tendermint/tmlibs/autofile" + . "github.com/tendermint/tmlibs/common" cfg "github.com/tendermint/go-config" "github.com/tendermint/go-wire" diff --git a/consensus/replay_file.go b/consensus/replay_file.go index 5ad1b9457..3de0e3d10 100644 --- a/consensus/replay_file.go +++ b/consensus/replay_file.go @@ -8,9 +8,9 @@ import ( "strconv" "strings" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" cfg "github.com/tendermint/go-config" - dbm "github.com/tendermint/go-db" + dbm "github.com/tendermint/tmlibs/db" bc "github.com/tendermint/tendermint/blockchain" mempl "github.com/tendermint/tendermint/mempool" "github.com/tendermint/tendermint/proxy" diff --git a/consensus/replay_test.go b/consensus/replay_test.go index 9368df99d..32415d6e3 100644 --- a/consensus/replay_test.go +++ b/consensus/replay_test.go @@ -15,10 +15,10 @@ import ( "github.com/tendermint/tendermint/config/tendermint_test" "github.com/tendermint/abci/example/dummy" - cmn "github.com/tendermint/go-common" + cmn "github.com/tendermint/tmlibs/common" cfg "github.com/tendermint/go-config" "github.com/tendermint/go-crypto" - dbm "github.com/tendermint/go-db" + dbm "github.com/tendermint/tmlibs/db" "github.com/tendermint/go-wire" "github.com/tendermint/tendermint/proxy" sm "github.com/tendermint/tendermint/state" diff --git a/consensus/state.go b/consensus/state.go index 6ff97ddc8..8077dcec1 100644 --- a/consensus/state.go +++ b/consensus/state.go @@ -11,7 +11,7 @@ import ( "github.com/ebuchman/fail-test" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" cfg "github.com/tendermint/go-config" "github.com/tendermint/go-wire" "github.com/tendermint/tendermint/proxy" diff --git a/consensus/state_test.go b/consensus/state_test.go index b7d9a42d1..d2d34e3ad 100644 --- a/consensus/state_test.go +++ b/consensus/state_test.go @@ -6,7 +6,7 @@ import ( "testing" "time" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" "github.com/tendermint/tendermint/config/tendermint_test" "github.com/tendermint/tendermint/types" ) diff --git a/consensus/ticker.go b/consensus/ticker.go index b318597d3..f8031e57c 100644 --- a/consensus/ticker.go +++ b/consensus/ticker.go @@ -3,7 +3,7 @@ package consensus import ( "time" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" ) var ( diff --git a/consensus/version.go b/consensus/version.go index 34886db3c..84f1ec81f 100644 --- a/consensus/version.go +++ b/consensus/version.go @@ -1,7 +1,7 @@ package consensus import ( - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" ) // kind of arbitrary diff --git a/consensus/wal.go b/consensus/wal.go index a89eff5e4..e855694a0 100644 --- a/consensus/wal.go +++ b/consensus/wal.go @@ -3,8 +3,8 @@ package consensus import ( "time" - auto "github.com/tendermint/go-autofile" - . "github.com/tendermint/go-common" + auto "github.com/tendermint/tmlibs/autofile" + . "github.com/tendermint/tmlibs/common" "github.com/tendermint/go-wire" "github.com/tendermint/tendermint/types" ) diff --git a/docs/architecture/merkle.md b/docs/architecture/merkle.md index 72998db88..4e769aed6 100644 --- a/docs/architecture/merkle.md +++ b/docs/architecture/merkle.md @@ -2,7 +2,7 @@ To allow the efficient creation of an ABCi app, tendermint wishes to provide a reference implemention of a key-value store that provides merkle proofs of the data. These proofs then quickly allow the ABCi app to provide an apphash to the consensus engine, as well as a full proof to any client. -This engine is currently implemented in `go-merkle` with `merkleeyes` providing a language-agnostic binding via ABCi. It uses `go-db` bindings internally to persist data to leveldb. +This engine is currently implemented in `go-merkle` with `merkleeyes` providing a language-agnostic binding via ABCi. It uses `tmlibs/db` bindings internally to persist data to leveldb. What are some of the requirements of this store: diff --git a/glide.lock b/glide.lock index 9e59179b3..de6470210 100644 --- a/glide.lock +++ b/glide.lock @@ -78,11 +78,11 @@ imports: subpackages: - edwards25519 - extra25519 -- name: github.com/tendermint/go-autofile +- name: github.com/tendermint/tmlibs/autofile version: 48b17de82914e1ec2f134ce823ba426337d2c518 -- name: github.com/tendermint/go-clist +- name: github.com/tendermint/tmlibs/clist version: 3baa390bbaf7634251c42ad69a8682e7e3990552 -- name: github.com/tendermint/go-common +- name: github.com/tendermint/tmlibs/common version: f9e3db037330c8a8d61d3966de8473eaf01154fa subpackages: - test @@ -92,15 +92,15 @@ imports: version: 9b95da8fa4187f6799558d89b271dc8ab6485615 - name: github.com/tendermint/go-data version: e7fcc6d081ec8518912fcdc103188275f83a3ee5 -- name: github.com/tendermint/go-db +- name: github.com/tendermint/tmlibs/db version: 9643f60bc2578693844aacf380a7c32e4c029fee -- name: github.com/tendermint/go-events +- name: github.com/tendermint/tmlibs/events version: f8ffbfb2be3483e9e7927495590a727f51c0c11f - name: github.com/tendermint/go-flowrate version: a20c98e61957faa93b4014fbd902f20ab9317a6a subpackages: - flowrate -- name: github.com/tendermint/go-logger +- name: github.com/tendermint/tmlibs/logger version: cefb3a45c0bf3c493a04e9bcd9b1540528be59f2 - name: github.com/tendermint/go-merkle version: 714d4d04557fd068a7c2a1748241ce8428015a96 diff --git a/glide.yaml b/glide.yaml index 03f328722..6225dff21 100644 --- a/glide.yaml +++ b/glide.yaml @@ -1,10 +1,10 @@ package: github.com/tendermint/tendermint import: -- package: github.com/tendermint/go-autofile +- package: github.com/tendermint/tmlibs/autofile version: develop -- package: github.com/tendermint/go-clist +- package: github.com/tendermint/tmlibs/clist version: develop -- package: github.com/tendermint/go-common +- package: github.com/tendermint/tmlibs/common version: develop - package: github.com/tendermint/go-config version: develop @@ -12,11 +12,11 @@ import: version: develop - package: github.com/tendermint/go-data version: develop -- package: github.com/tendermint/go-db +- package: github.com/tendermint/tmlibs/db version: develop -- package: github.com/tendermint/go-events +- package: github.com/tendermint/tmlibs/events version: develop -- package: github.com/tendermint/go-logger +- package: github.com/tendermint/tmlibs/logger version: develop - package: github.com/tendermint/go-merkle version: develop diff --git a/mempool/log.go b/mempool/log.go index 90eb8703f..ac9596d5e 100644 --- a/mempool/log.go +++ b/mempool/log.go @@ -1,7 +1,7 @@ package mempool import ( - "github.com/tendermint/go-logger" + "github.com/tendermint/tmlibs/logger" ) var log = logger.New("module", "mempool") diff --git a/mempool/mempool.go b/mempool/mempool.go index e960f520f..eedf6fb9c 100644 --- a/mempool/mempool.go +++ b/mempool/mempool.go @@ -8,9 +8,9 @@ import ( "time" abci "github.com/tendermint/abci/types" - auto "github.com/tendermint/go-autofile" - "github.com/tendermint/go-clist" - . "github.com/tendermint/go-common" + auto "github.com/tendermint/tmlibs/autofile" + "github.com/tendermint/tmlibs/clist" + . "github.com/tendermint/tmlibs/common" cfg "github.com/tendermint/go-config" "github.com/tendermint/tendermint/proxy" "github.com/tendermint/tendermint/types" diff --git a/mempool/reactor.go b/mempool/reactor.go index 4531edee0..4b30dd4c8 100644 --- a/mempool/reactor.go +++ b/mempool/reactor.go @@ -7,7 +7,7 @@ import ( "time" abci "github.com/tendermint/abci/types" - "github.com/tendermint/go-clist" + "github.com/tendermint/tmlibs/clist" cfg "github.com/tendermint/go-config" "github.com/tendermint/go-p2p" "github.com/tendermint/go-wire" diff --git a/node/log.go b/node/log.go index 36b451493..946d963cf 100644 --- a/node/log.go +++ b/node/log.go @@ -1,7 +1,7 @@ package node import ( - "github.com/tendermint/go-logger" + "github.com/tendermint/tmlibs/logger" ) var log = logger.New("module", "node") diff --git a/node/node.go b/node/node.go index 84841d5d3..e63e0db3e 100644 --- a/node/node.go +++ b/node/node.go @@ -8,10 +8,10 @@ import ( "strings" abci "github.com/tendermint/abci/types" - cmn "github.com/tendermint/go-common" + cmn "github.com/tendermint/tmlibs/common" cfg "github.com/tendermint/go-config" crypto "github.com/tendermint/go-crypto" - dbm "github.com/tendermint/go-db" + dbm "github.com/tendermint/tmlibs/db" p2p "github.com/tendermint/go-p2p" rpc "github.com/tendermint/go-rpc" rpcserver "github.com/tendermint/go-rpc/server" diff --git a/proxy/app_conn_test.go b/proxy/app_conn_test.go index 2054175eb..7c072625a 100644 --- a/proxy/app_conn_test.go +++ b/proxy/app_conn_test.go @@ -4,7 +4,7 @@ import ( "strings" "testing" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" abcicli "github.com/tendermint/abci/client" "github.com/tendermint/abci/example/dummy" "github.com/tendermint/abci/server" diff --git a/proxy/log.go b/proxy/log.go index 45d31b879..d1d241bf1 100644 --- a/proxy/log.go +++ b/proxy/log.go @@ -1,7 +1,7 @@ package proxy import ( - "github.com/tendermint/go-logger" + "github.com/tendermint/tmlibs/logger" ) var log = logger.New("module", "proxy") diff --git a/proxy/multi_app_conn.go b/proxy/multi_app_conn.go index 81e01aa29..b70a0baf0 100644 --- a/proxy/multi_app_conn.go +++ b/proxy/multi_app_conn.go @@ -1,7 +1,7 @@ package proxy import ( - cmn "github.com/tendermint/go-common" + cmn "github.com/tendermint/tmlibs/common" cfg "github.com/tendermint/go-config" ) diff --git a/rpc/tendermint/client/helpers.go b/rpc/tendermint/client/helpers.go index bd00c1438..330bcd199 100644 --- a/rpc/tendermint/client/helpers.go +++ b/rpc/tendermint/client/helpers.go @@ -4,8 +4,8 @@ import ( "time" "github.com/pkg/errors" - cmn "github.com/tendermint/go-common" - events "github.com/tendermint/go-events" + cmn "github.com/tendermint/tmlibs/common" + events "github.com/tendermint/tmlibs/events" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/client/httpclient.go b/rpc/tendermint/client/httpclient.go index cfcd9299f..494f4413c 100644 --- a/rpc/tendermint/client/httpclient.go +++ b/rpc/tendermint/client/httpclient.go @@ -5,7 +5,7 @@ import ( "github.com/pkg/errors" data "github.com/tendermint/go-data" - events "github.com/tendermint/go-events" + events "github.com/tendermint/tmlibs/events" "github.com/tendermint/go-rpc/client" wire "github.com/tendermint/go-wire" ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" @@ -198,7 +198,7 @@ type WSEvents struct { // used to maintain counts of actively listened events // so we can properly subscribe/unsubscribe // FIXME: thread-safety??? - // FIXME: reuse code from go-events??? + // FIXME: reuse code from tmlibs/events??? evtCount map[string]int // count how many time each event is subscribed listeners map[string][]string // keep track of which events each listener is listening to } diff --git a/rpc/tendermint/core/blocks.go b/rpc/tendermint/core/blocks.go index 39e185864..aa102255f 100644 --- a/rpc/tendermint/core/blocks.go +++ b/rpc/tendermint/core/blocks.go @@ -2,7 +2,7 @@ package core import ( "fmt" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/grpc/client_server.go b/rpc/tendermint/grpc/client_server.go index d760bf254..e6055ede3 100644 --- a/rpc/tendermint/grpc/client_server.go +++ b/rpc/tendermint/grpc/client_server.go @@ -8,7 +8,7 @@ import ( "google.golang.org/grpc" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" ) // Start the grpcServer in a go routine diff --git a/rpc/tendermint/test/client_test.go b/rpc/tendermint/test/client_test.go index 390d652e5..9c1bbd8d7 100644 --- a/rpc/tendermint/test/client_test.go +++ b/rpc/tendermint/test/client_test.go @@ -11,7 +11,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" abci "github.com/tendermint/abci/types" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" rpc "github.com/tendermint/go-rpc/client" "github.com/tendermint/tendermint/rpc/tendermint/core" ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" diff --git a/rpc/tendermint/test/helpers.go b/rpc/tendermint/test/helpers.go index dbbcebbf8..6f7050f8b 100644 --- a/rpc/tendermint/test/helpers.go +++ b/rpc/tendermint/test/helpers.go @@ -10,7 +10,7 @@ import ( "time" "github.com/stretchr/testify/require" - logger "github.com/tendermint/go-logger" + logger "github.com/tendermint/tmlibs/logger" wire "github.com/tendermint/go-wire" abci "github.com/tendermint/abci/types" diff --git a/state/errors.go b/state/errors.go index 32a9351ce..1ea7ed3d9 100644 --- a/state/errors.go +++ b/state/errors.go @@ -1,7 +1,7 @@ package state import ( - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" ) type ( diff --git a/state/execution.go b/state/execution.go index 0b1aff699..643dd4d05 100644 --- a/state/execution.go +++ b/state/execution.go @@ -6,7 +6,7 @@ import ( fail "github.com/ebuchman/fail-test" abci "github.com/tendermint/abci/types" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" crypto "github.com/tendermint/go-crypto" "github.com/tendermint/tendermint/proxy" "github.com/tendermint/tendermint/state/txindex" diff --git a/state/execution_test.go b/state/execution_test.go index 299c6baa2..40e4044a4 100644 --- a/state/execution_test.go +++ b/state/execution_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/require" "github.com/tendermint/abci/example/dummy" crypto "github.com/tendermint/go-crypto" - dbm "github.com/tendermint/go-db" + dbm "github.com/tendermint/tmlibs/db" cfg "github.com/tendermint/tendermint/config/tendermint_test" "github.com/tendermint/tendermint/mempool" "github.com/tendermint/tendermint/proxy" diff --git a/state/log.go b/state/log.go index 5b102b570..0a2351324 100644 --- a/state/log.go +++ b/state/log.go @@ -1,7 +1,7 @@ package state import ( - "github.com/tendermint/go-logger" + "github.com/tendermint/tmlibs/logger" ) var log = logger.New("module", "state") diff --git a/state/state.go b/state/state.go index 086b0e710..ccdf508ac 100644 --- a/state/state.go +++ b/state/state.go @@ -7,9 +7,9 @@ import ( "time" abci "github.com/tendermint/abci/types" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" cfg "github.com/tendermint/go-config" - dbm "github.com/tendermint/go-db" + dbm "github.com/tendermint/tmlibs/db" "github.com/tendermint/go-wire" "github.com/tendermint/tendermint/state/txindex" "github.com/tendermint/tendermint/state/txindex/null" diff --git a/state/state_test.go b/state/state_test.go index dca83e801..f80c08fe5 100644 --- a/state/state_test.go +++ b/state/state_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/assert" abci "github.com/tendermint/abci/types" "github.com/tendermint/go-crypto" - dbm "github.com/tendermint/go-db" + dbm "github.com/tendermint/tmlibs/db" "github.com/tendermint/tendermint/config/tendermint_test" ) diff --git a/state/txindex/kv/kv.go b/state/txindex/kv/kv.go index 03acc8dae..8f684c4a9 100644 --- a/state/txindex/kv/kv.go +++ b/state/txindex/kv/kv.go @@ -4,7 +4,7 @@ import ( "bytes" "fmt" - db "github.com/tendermint/go-db" + db "github.com/tendermint/tmlibs/db" "github.com/tendermint/go-wire" "github.com/tendermint/tendermint/state/txindex" "github.com/tendermint/tendermint/types" diff --git a/state/txindex/kv/kv_test.go b/state/txindex/kv/kv_test.go index 9a1898d7e..8de9b8cda 100644 --- a/state/txindex/kv/kv_test.go +++ b/state/txindex/kv/kv_test.go @@ -8,7 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" abci "github.com/tendermint/abci/types" - db "github.com/tendermint/go-db" + db "github.com/tendermint/tmlibs/db" "github.com/tendermint/tendermint/state/txindex" "github.com/tendermint/tendermint/types" ) diff --git a/test/test_libs.sh b/test/test_libs.sh index d08a4659c..bf1b0096c 100644 --- a/test/test_libs.sh +++ b/test/test_libs.sh @@ -14,7 +14,7 @@ fi # some libs are tested with go, others with make # TODO: should be all make (post repo merge) -LIBS_GO_TEST=(go-clist go-common go-config go-crypto go-db go-events go-merkle go-p2p) +LIBS_GO_TEST=(tmlibs/clist tmlibs/common go-config go-crypto tmlibs/db tmlibs/events go-merkle go-p2p) LIBS_MAKE_TEST=(go-rpc go-wire abci) for lib in "${LIBS_GO_TEST[@]}"; do diff --git a/types/block.go b/types/block.go index 61d25f6e4..d4cf5a9c7 100644 --- a/types/block.go +++ b/types/block.go @@ -8,7 +8,7 @@ import ( "strings" "time" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" "github.com/tendermint/go-merkle" "github.com/tendermint/go-wire" ) diff --git a/types/events.go b/types/events.go index 114979047..17f6fc6e4 100644 --- a/types/events.go +++ b/types/events.go @@ -3,8 +3,8 @@ package types import ( // for registering TMEventData as events.EventData abci "github.com/tendermint/abci/types" - . "github.com/tendermint/go-common" - "github.com/tendermint/go-events" + . "github.com/tendermint/tmlibs/common" + "github.com/tendermint/tmlibs/events" "github.com/tendermint/go-wire" ) diff --git a/types/genesis.go b/types/genesis.go index 2e1ebb649..6a5006648 100644 --- a/types/genesis.go +++ b/types/genesis.go @@ -4,7 +4,7 @@ import ( "encoding/json" "time" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" "github.com/tendermint/go-crypto" ) diff --git a/types/log.go b/types/log.go index dbe8a6782..5a4b363ba 100644 --- a/types/log.go +++ b/types/log.go @@ -1,7 +1,7 @@ package types import ( - "github.com/tendermint/go-logger" + "github.com/tendermint/tmlibs/logger" ) var log = logger.New("module", "types") diff --git a/types/part_set.go b/types/part_set.go index 3a5ee26ad..2377b2937 100644 --- a/types/part_set.go +++ b/types/part_set.go @@ -9,7 +9,7 @@ import ( "golang.org/x/crypto/ripemd160" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" "github.com/tendermint/go-merkle" "github.com/tendermint/go-wire" ) diff --git a/types/part_set_test.go b/types/part_set_test.go index 6e25752da..7088ef317 100644 --- a/types/part_set_test.go +++ b/types/part_set_test.go @@ -5,7 +5,7 @@ import ( "io/ioutil" "testing" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" ) const ( diff --git a/types/priv_validator.go b/types/priv_validator.go index 6798f64be..46d64acb1 100644 --- a/types/priv_validator.go +++ b/types/priv_validator.go @@ -9,7 +9,7 @@ import ( "os" "sync" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" "github.com/tendermint/go-crypto" data "github.com/tendermint/go-data" ) diff --git a/types/proposal.go b/types/proposal.go index 9852011f3..8406403c1 100644 --- a/types/proposal.go +++ b/types/proposal.go @@ -5,7 +5,7 @@ import ( "fmt" "io" - //. "github.com/tendermint/go-common" + //. "github.com/tendermint/tmlibs/common" "github.com/tendermint/go-crypto" "github.com/tendermint/go-wire" ) diff --git a/types/signable.go b/types/signable.go index df94e43b4..c843eeedc 100644 --- a/types/signable.go +++ b/types/signable.go @@ -4,7 +4,7 @@ import ( "bytes" "io" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" "github.com/tendermint/go-merkle" ) diff --git a/types/tx_test.go b/types/tx_test.go index 7688a9bf1..866357e33 100644 --- a/types/tx_test.go +++ b/types/tx_test.go @@ -5,8 +5,8 @@ import ( "testing" "github.com/stretchr/testify/assert" - cmn "github.com/tendermint/go-common" - ctest "github.com/tendermint/go-common/test" + cmn "github.com/tendermint/tmlibs/common" + ctest "github.com/tendermint/tmlibs/common/test" wire "github.com/tendermint/go-wire" ) diff --git a/types/validator.go b/types/validator.go index c4ecef56e..2a8795bf3 100644 --- a/types/validator.go +++ b/types/validator.go @@ -5,7 +5,7 @@ import ( "fmt" "io" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" "github.com/tendermint/go-crypto" "github.com/tendermint/go-wire" ) diff --git a/types/validator_set.go b/types/validator_set.go index b997b4713..1daf2ef61 100644 --- a/types/validator_set.go +++ b/types/validator_set.go @@ -6,7 +6,7 @@ import ( "sort" "strings" - cmn "github.com/tendermint/go-common" + cmn "github.com/tendermint/tmlibs/common" "github.com/tendermint/go-merkle" "github.com/tendermint/go-wire" ) diff --git a/types/validator_set_test.go b/types/validator_set_test.go index 6cd048cc3..71a1993e7 100644 --- a/types/validator_set_test.go +++ b/types/validator_set_test.go @@ -5,7 +5,7 @@ import ( "strings" "testing" - cmn "github.com/tendermint/go-common" + cmn "github.com/tendermint/tmlibs/common" "github.com/tendermint/go-crypto" ) diff --git a/types/vote.go b/types/vote.go index af4f60fc5..2ad9df0ad 100644 --- a/types/vote.go +++ b/types/vote.go @@ -5,7 +5,7 @@ import ( "fmt" "io" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" "github.com/tendermint/go-crypto" "github.com/tendermint/go-wire" ) diff --git a/types/vote_set.go b/types/vote_set.go index de853a5e7..938dbcb61 100644 --- a/types/vote_set.go +++ b/types/vote_set.go @@ -6,7 +6,7 @@ import ( "strings" "sync" - . "github.com/tendermint/go-common" + . "github.com/tendermint/tmlibs/common" ) /* diff --git a/types/vote_set_test.go b/types/vote_set_test.go index 500daadff..672b21a0a 100644 --- a/types/vote_set_test.go +++ b/types/vote_set_test.go @@ -3,8 +3,8 @@ package types import ( "bytes" - . "github.com/tendermint/go-common" - . "github.com/tendermint/go-common/test" + . "github.com/tendermint/tmlibs/common" + . "github.com/tendermint/tmlibs/common/test" "github.com/tendermint/go-crypto" "testing" From e6fe6b5b76c730a9694b649b1d899651141cb39c Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 21 Apr 2017 18:13:25 -0400 Subject: [PATCH 191/309] go-data -> go-wire/data --- cmd/tendermint/commands/show_validator.go | 2 +- glide.lock | 2 +- glide.yaml | 2 +- rpc/tendermint/client/httpclient.go | 2 +- rpc/tendermint/client/interface.go | 2 +- rpc/tendermint/client/localclient.go | 2 +- rpc/tendermint/client/mock/abci.go | 2 +- rpc/tendermint/client/mock/abci_test.go | 2 +- rpc/tendermint/client/mock/client.go | 2 +- rpc/tendermint/client/mock/status_test.go | 2 +- rpc/tendermint/core/abci.go | 2 +- rpc/tendermint/core/mempool.go | 2 +- rpc/tendermint/core/routes.go | 2 +- rpc/tendermint/core/status.go | 2 +- rpc/tendermint/core/types/responses.go | 2 +- types/priv_validator.go | 2 +- 16 files changed, 16 insertions(+), 16 deletions(-) diff --git a/cmd/tendermint/commands/show_validator.go b/cmd/tendermint/commands/show_validator.go index 0b349f98c..951fd5a8c 100644 --- a/cmd/tendermint/commands/show_validator.go +++ b/cmd/tendermint/commands/show_validator.go @@ -5,7 +5,7 @@ import ( "github.com/spf13/cobra" - data "github.com/tendermint/go-data" + data "github.com/tendermint/go-wire/data" "github.com/tendermint/tendermint/types" ) diff --git a/glide.lock b/glide.lock index de6470210..42a261c10 100644 --- a/glide.lock +++ b/glide.lock @@ -90,7 +90,7 @@ imports: version: 620dcbbd7d587cf3599dedbf329b64311b0c307a - name: github.com/tendermint/go-crypto version: 9b95da8fa4187f6799558d89b271dc8ab6485615 -- name: github.com/tendermint/go-data +- name: github.com/tendermint/go-wire/data version: e7fcc6d081ec8518912fcdc103188275f83a3ee5 - name: github.com/tendermint/tmlibs/db version: 9643f60bc2578693844aacf380a7c32e4c029fee diff --git a/glide.yaml b/glide.yaml index 6225dff21..b7d8de242 100644 --- a/glide.yaml +++ b/glide.yaml @@ -10,7 +10,7 @@ import: version: develop - package: github.com/tendermint/go-crypto version: develop -- package: github.com/tendermint/go-data +- package: github.com/tendermint/go-wire/data version: develop - package: github.com/tendermint/tmlibs/db version: develop diff --git a/rpc/tendermint/client/httpclient.go b/rpc/tendermint/client/httpclient.go index 494f4413c..8e661443f 100644 --- a/rpc/tendermint/client/httpclient.go +++ b/rpc/tendermint/client/httpclient.go @@ -4,7 +4,7 @@ import ( "fmt" "github.com/pkg/errors" - data "github.com/tendermint/go-data" + data "github.com/tendermint/go-wire/data" events "github.com/tendermint/tmlibs/events" "github.com/tendermint/go-rpc/client" wire "github.com/tendermint/go-wire" diff --git a/rpc/tendermint/client/interface.go b/rpc/tendermint/client/interface.go index 8040d5d99..4726e00d9 100644 --- a/rpc/tendermint/client/interface.go +++ b/rpc/tendermint/client/interface.go @@ -20,7 +20,7 @@ implementation. package client import ( - data "github.com/tendermint/go-data" + data "github.com/tendermint/go-wire/data" ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/client/localclient.go b/rpc/tendermint/client/localclient.go index 34242866f..146d96597 100644 --- a/rpc/tendermint/client/localclient.go +++ b/rpc/tendermint/client/localclient.go @@ -1,7 +1,7 @@ package client import ( - data "github.com/tendermint/go-data" + data "github.com/tendermint/go-wire/data" nm "github.com/tendermint/tendermint/node" "github.com/tendermint/tendermint/rpc/tendermint/core" ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" diff --git a/rpc/tendermint/client/mock/abci.go b/rpc/tendermint/client/mock/abci.go index 962744df7..d03728dbe 100644 --- a/rpc/tendermint/client/mock/abci.go +++ b/rpc/tendermint/client/mock/abci.go @@ -2,7 +2,7 @@ package mock import ( abci "github.com/tendermint/abci/types" - data "github.com/tendermint/go-data" + data "github.com/tendermint/go-wire/data" "github.com/tendermint/tendermint/rpc/tendermint/client" ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" "github.com/tendermint/tendermint/types" diff --git a/rpc/tendermint/client/mock/abci_test.go b/rpc/tendermint/client/mock/abci_test.go index 267d19dfc..3fcca9692 100644 --- a/rpc/tendermint/client/mock/abci_test.go +++ b/rpc/tendermint/client/mock/abci_test.go @@ -10,7 +10,7 @@ import ( "github.com/stretchr/testify/require" "github.com/tendermint/abci/example/dummy" abci "github.com/tendermint/abci/types" - data "github.com/tendermint/go-data" + data "github.com/tendermint/go-wire/data" ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" "github.com/tendermint/tendermint/types" diff --git a/rpc/tendermint/client/mock/client.go b/rpc/tendermint/client/mock/client.go index f43346591..b2a91b743 100644 --- a/rpc/tendermint/client/mock/client.go +++ b/rpc/tendermint/client/mock/client.go @@ -16,7 +16,7 @@ package mock import ( "reflect" - data "github.com/tendermint/go-data" + data "github.com/tendermint/go-wire/data" "github.com/tendermint/tendermint/rpc/tendermint/client" "github.com/tendermint/tendermint/rpc/tendermint/core" ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" diff --git a/rpc/tendermint/client/mock/status_test.go b/rpc/tendermint/client/mock/status_test.go index 55576fb11..f5a2bc7f8 100644 --- a/rpc/tendermint/client/mock/status_test.go +++ b/rpc/tendermint/client/mock/status_test.go @@ -5,7 +5,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - data "github.com/tendermint/go-data" + data "github.com/tendermint/go-wire/data" ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" "github.com/tendermint/tendermint/rpc/tendermint/client/mock" diff --git a/rpc/tendermint/core/abci.go b/rpc/tendermint/core/abci.go index 519c18822..e56b92d70 100644 --- a/rpc/tendermint/core/abci.go +++ b/rpc/tendermint/core/abci.go @@ -2,7 +2,7 @@ package core import ( abci "github.com/tendermint/abci/types" - data "github.com/tendermint/go-data" + data "github.com/tendermint/go-wire/data" ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" ) diff --git a/rpc/tendermint/core/mempool.go b/rpc/tendermint/core/mempool.go index df5ea8b64..e3d82bf87 100644 --- a/rpc/tendermint/core/mempool.go +++ b/rpc/tendermint/core/mempool.go @@ -5,7 +5,7 @@ import ( "time" abci "github.com/tendermint/abci/types" - data "github.com/tendermint/go-data" + data "github.com/tendermint/go-wire/data" ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/core/routes.go b/rpc/tendermint/core/routes.go index 1b426d1dd..d50968eee 100644 --- a/rpc/tendermint/core/routes.go +++ b/rpc/tendermint/core/routes.go @@ -1,7 +1,7 @@ package core import ( - data "github.com/tendermint/go-data" + data "github.com/tendermint/go-wire/data" rpc "github.com/tendermint/go-rpc/server" "github.com/tendermint/go-rpc/types" ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" diff --git a/rpc/tendermint/core/status.go b/rpc/tendermint/core/status.go index 1a90945b5..9dbfff86d 100644 --- a/rpc/tendermint/core/status.go +++ b/rpc/tendermint/core/status.go @@ -1,7 +1,7 @@ package core import ( - data "github.com/tendermint/go-data" + data "github.com/tendermint/go-wire/data" ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/core/types/responses.go b/rpc/tendermint/core/types/responses.go index 59fa09aa0..ba4584830 100644 --- a/rpc/tendermint/core/types/responses.go +++ b/rpc/tendermint/core/types/responses.go @@ -5,7 +5,7 @@ import ( abci "github.com/tendermint/abci/types" "github.com/tendermint/go-crypto" - data "github.com/tendermint/go-data" + data "github.com/tendermint/go-wire/data" "github.com/tendermint/go-p2p" "github.com/tendermint/go-rpc/types" "github.com/tendermint/go-wire" diff --git a/types/priv_validator.go b/types/priv_validator.go index 46d64acb1..b73591ddc 100644 --- a/types/priv_validator.go +++ b/types/priv_validator.go @@ -11,7 +11,7 @@ import ( . "github.com/tendermint/tmlibs/common" "github.com/tendermint/go-crypto" - data "github.com/tendermint/go-data" + data "github.com/tendermint/go-wire/data" ) const ( From d5b524e30944ae28213940916380363b65688b84 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 21 Apr 2017 18:16:05 -0400 Subject: [PATCH 192/309] go-merkle -> merkleeyes/iavl and tmlibs/merkle --- rpc/tendermint/client/rpc_test.go | 4 ++-- types/block.go | 2 +- types/part_set.go | 2 +- types/signable.go | 2 +- types/tx.go | 4 ++-- types/validator_set.go | 2 +- 6 files changed, 8 insertions(+), 8 deletions(-) diff --git a/rpc/tendermint/client/rpc_test.go b/rpc/tendermint/client/rpc_test.go index 3ead008dc..95c583c97 100644 --- a/rpc/tendermint/client/rpc_test.go +++ b/rpc/tendermint/client/rpc_test.go @@ -6,7 +6,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - merkle "github.com/tendermint/go-merkle" + "github.com/tendermint/merkleeyes/iavl" merktest "github.com/tendermint/merkleeyes/testutil" "github.com/tendermint/tendermint/rpc/tendermint/client" rpctest "github.com/tendermint/tendermint/rpc/tendermint/test" @@ -175,7 +175,7 @@ func TestAppCalls(t *testing.T) { // and we got a proof that works! pres, err := c.ABCIQuery("/key", k, true) if assert.Nil(err) && assert.True(pres.Response.Code.IsOK()) { - proof, err := merkle.ReadProof(pres.Response.GetProof()) + proof, err := iavl.ReadProof(pres.Response.GetProof()) if assert.Nil(err) { key := pres.Response.GetKey() value := pres.Response.GetValue() diff --git a/types/block.go b/types/block.go index d4cf5a9c7..88288a2bd 100644 --- a/types/block.go +++ b/types/block.go @@ -9,7 +9,7 @@ import ( "time" . "github.com/tendermint/tmlibs/common" - "github.com/tendermint/go-merkle" + "github.com/tendermint/tmlibs/merkle" "github.com/tendermint/go-wire" ) diff --git a/types/part_set.go b/types/part_set.go index 2377b2937..96907aa5f 100644 --- a/types/part_set.go +++ b/types/part_set.go @@ -10,7 +10,7 @@ import ( "golang.org/x/crypto/ripemd160" . "github.com/tendermint/tmlibs/common" - "github.com/tendermint/go-merkle" + "github.com/tendermint/tmlibs/merkle" "github.com/tendermint/go-wire" ) diff --git a/types/signable.go b/types/signable.go index c843eeedc..13389fef7 100644 --- a/types/signable.go +++ b/types/signable.go @@ -5,7 +5,7 @@ import ( "io" . "github.com/tendermint/tmlibs/common" - "github.com/tendermint/go-merkle" + "github.com/tendermint/tmlibs/merkle" ) // Signable is an interface for all signable things. diff --git a/types/tx.go b/types/tx.go index df7f0e71a..e62b5f666 100644 --- a/types/tx.go +++ b/types/tx.go @@ -5,7 +5,7 @@ import ( "errors" abci "github.com/tendermint/abci/types" - "github.com/tendermint/go-merkle" + "github.com/tendermint/tmlibs/merkle" ) type Tx []byte @@ -22,7 +22,7 @@ type Txs []Tx func (txs Txs) Hash() []byte { // Recursive impl. - // Copied from go-merkle to avoid allocations + // Copied from tmlibs/merkle to avoid allocations switch len(txs) { case 0: return nil diff --git a/types/validator_set.go b/types/validator_set.go index 1daf2ef61..f6a8faf46 100644 --- a/types/validator_set.go +++ b/types/validator_set.go @@ -7,7 +7,7 @@ import ( "strings" cmn "github.com/tendermint/tmlibs/common" - "github.com/tendermint/go-merkle" + "github.com/tendermint/tmlibs/merkle" "github.com/tendermint/go-wire" ) From a70c95b79e4cb7ed4f3eaf7407d9f30cfb38f205 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 21 Apr 2017 18:18:22 -0400 Subject: [PATCH 193/309] tmlibs/common/test -> tmlibs/test --- types/tx_test.go | 4 ++-- types/vote_set_test.go | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/types/tx_test.go b/types/tx_test.go index 866357e33..3ed59e3cb 100644 --- a/types/tx_test.go +++ b/types/tx_test.go @@ -5,9 +5,9 @@ import ( "testing" "github.com/stretchr/testify/assert" - cmn "github.com/tendermint/tmlibs/common" - ctest "github.com/tendermint/tmlibs/common/test" wire "github.com/tendermint/go-wire" + cmn "github.com/tendermint/tmlibs/common" + ctest "github.com/tendermint/tmlibs/test" ) func makeTxs(cnt, size int) Txs { diff --git a/types/vote_set_test.go b/types/vote_set_test.go index 672b21a0a..6ef075927 100644 --- a/types/vote_set_test.go +++ b/types/vote_set_test.go @@ -3,9 +3,9 @@ package types import ( "bytes" - . "github.com/tendermint/tmlibs/common" - . "github.com/tendermint/tmlibs/common/test" "github.com/tendermint/go-crypto" + . "github.com/tendermint/tmlibs/common" + . "github.com/tendermint/tmlibs/test" "testing" ) From 9e82d132ce3ec46041ab53331335ad1f3689f052 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 21 Apr 2017 18:19:29 -0400 Subject: [PATCH 194/309] go-rpc -> tendermint/rpc --- benchmarks/simu/counter.go | 4 ++-- glide.lock | 2 +- glide.yaml | 2 +- node/node.go | 4 ++-- rpc/Dockerfile | 12 ++++++------ rpc/README.md | 4 ++-- rpc/client/http_client.go | 4 ++-- rpc/client/ws_client.go | 2 +- rpc/rpc_test.go | 10 +++++----- rpc/server/handlers.go | 2 +- rpc/server/http_server.go | 4 ++-- rpc/tendermint/client/httpclient.go | 2 +- rpc/tendermint/core/events.go | 2 +- rpc/tendermint/core/routes.go | 4 ++-- rpc/tendermint/core/types/responses.go | 2 +- rpc/tendermint/test/client_test.go | 2 +- rpc/tendermint/test/helpers.go | 2 +- rpc/test/main.go | 2 +- test/test_libs.sh | 2 +- 19 files changed, 34 insertions(+), 34 deletions(-) diff --git a/benchmarks/simu/counter.go b/benchmarks/simu/counter.go index 9a6db3f4c..f384d3579 100644 --- a/benchmarks/simu/counter.go +++ b/benchmarks/simu/counter.go @@ -8,8 +8,8 @@ import ( "github.com/gorilla/websocket" . "github.com/tendermint/tmlibs/common" - "github.com/tendermint/go-rpc/client" - "github.com/tendermint/go-rpc/types" + "github.com/tendermint/tendermint/rpc/client" + "github.com/tendermint/tendermint/rpc/types" "github.com/tendermint/go-wire" _ "github.com/tendermint/tendermint/rpc/tendermint/core/types" // Register RPCResponse > Result types ) diff --git a/glide.lock b/glide.lock index 42a261c10..c7c4649e9 100644 --- a/glide.lock +++ b/glide.lock @@ -108,7 +108,7 @@ imports: version: b5f314ffed65c81bd019ba1dd2bae0e95f3937f3 subpackages: - upnp -- name: github.com/tendermint/go-rpc +- name: github.com/tendermint/tendermint/rpc version: 2c8df0ee6b60d8ac33662df13a4e358c679e02bf subpackages: - client diff --git a/glide.yaml b/glide.yaml index b7d8de242..a1013eb90 100644 --- a/glide.yaml +++ b/glide.yaml @@ -22,7 +22,7 @@ import: version: develop - package: github.com/tendermint/go-p2p version: unstable -- package: github.com/tendermint/go-rpc +- package: github.com/tendermint/tendermint/rpc version: develop - package: github.com/tendermint/go-wire version: develop diff --git a/node/node.go b/node/node.go index e63e0db3e..e912495f2 100644 --- a/node/node.go +++ b/node/node.go @@ -13,8 +13,8 @@ import ( crypto "github.com/tendermint/go-crypto" dbm "github.com/tendermint/tmlibs/db" p2p "github.com/tendermint/go-p2p" - rpc "github.com/tendermint/go-rpc" - rpcserver "github.com/tendermint/go-rpc/server" + rpc "github.com/tendermint/tendermint/rpc" + rpcserver "github.com/tendermint/tendermint/rpc/server" wire "github.com/tendermint/go-wire" bc "github.com/tendermint/tendermint/blockchain" "github.com/tendermint/tendermint/consensus" diff --git a/rpc/Dockerfile b/rpc/Dockerfile index c23c911ce..c22412672 100644 --- a/rpc/Dockerfile +++ b/rpc/Dockerfile @@ -1,12 +1,12 @@ FROM golang:latest -RUN mkdir -p /go/src/github.com/tendermint/go-rpc -WORKDIR /go/src/github.com/tendermint/go-rpc +RUN mkdir -p /go/src/github.com/tendermint/tendermint/rpc +WORKDIR /go/src/github.com/tendermint/tendermint/rpc -COPY Makefile /go/src/github.com/tendermint/go-rpc/ -# COPY glide.yaml /go/src/github.com/tendermint/go-rpc/ -# COPY glide.lock /go/src/github.com/tendermint/go-rpc/ +COPY Makefile /go/src/github.com/tendermint/tendermint/rpc/ +# COPY glide.yaml /go/src/github.com/tendermint/tendermint/rpc/ +# COPY glide.lock /go/src/github.com/tendermint/tendermint/rpc/ -COPY . /go/src/github.com/tendermint/go-rpc +COPY . /go/src/github.com/tendermint/tendermint/rpc RUN make get_deps diff --git a/rpc/README.md b/rpc/README.md index 79dd9692e..f1ef7485a 100644 --- a/rpc/README.md +++ b/rpc/README.md @@ -1,6 +1,6 @@ -# go-rpc +# tendermint/rpc -[![CircleCI](https://circleci.com/gh/tendermint/go-rpc.svg?style=svg)](https://circleci.com/gh/tendermint/go-rpc) +[![CircleCI](https://circleci.com/gh/tendermint/tendermint/rpc.svg?style=svg)](https://circleci.com/gh/tendermint/tendermint/rpc) HTTP RPC server supporting calls via uri params, jsonrpc, and jsonrpc over websockets diff --git a/rpc/client/http_client.go b/rpc/client/http_client.go index f4a2a6d7e..ce78da43d 100644 --- a/rpc/client/http_client.go +++ b/rpc/client/http_client.go @@ -12,7 +12,7 @@ import ( "strings" "github.com/pkg/errors" - types "github.com/tendermint/go-rpc/types" + types "github.com/tendermint/tendermint/rpc/types" wire "github.com/tendermint/go-wire" ) @@ -27,7 +27,7 @@ func makeHTTPDialer(remoteAddr string) (string, func(string, string) (net.Conn, parts := strings.SplitN(remoteAddr, "://", 2) var protocol, address string if len(parts) != 2 { - log.Warn("WARNING (go-rpc): Please use fully formed listening addresses, including the tcp:// or unix:// prefix") + log.Warn("WARNING (tendermint/rpc): Please use fully formed listening addresses, including the tcp:// or unix:// prefix") protocol = types.SocketType(remoteAddr) address = remoteAddr } else { diff --git a/rpc/client/ws_client.go b/rpc/client/ws_client.go index b83d62974..70522265f 100644 --- a/rpc/client/ws_client.go +++ b/rpc/client/ws_client.go @@ -9,7 +9,7 @@ import ( "github.com/gorilla/websocket" "github.com/pkg/errors" cmn "github.com/tendermint/tmlibs/common" - types "github.com/tendermint/go-rpc/types" + types "github.com/tendermint/tendermint/rpc/types" wire "github.com/tendermint/go-wire" ) diff --git a/rpc/rpc_test.go b/rpc/rpc_test.go index ed28cbc8d..82940fc32 100644 --- a/rpc/rpc_test.go +++ b/rpc/rpc_test.go @@ -12,9 +12,9 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - client "github.com/tendermint/go-rpc/client" - server "github.com/tendermint/go-rpc/server" - types "github.com/tendermint/go-rpc/types" + client "github.com/tendermint/tendermint/rpc/client" + server "github.com/tendermint/tendermint/rpc/server" + types "github.com/tendermint/tendermint/rpc/types" wire "github.com/tendermint/go-wire" ) @@ -22,8 +22,8 @@ import ( const ( tcpAddr = "tcp://0.0.0.0:46657" - unixSocket = "/tmp/go-rpc.sock" - unixAddr = "unix:///tmp/go-rpc.sock" + unixSocket = "/tmp/tendermint/rpc.sock" + unixAddr = "unix:///tmp/tendermint/rpc.sock" websocketEndpoint = "/websocket/endpoint" ) diff --git a/rpc/server/handlers.go b/rpc/server/handlers.go index 456b4aaf5..f5b3659d3 100644 --- a/rpc/server/handlers.go +++ b/rpc/server/handlers.go @@ -14,7 +14,7 @@ import ( "github.com/gorilla/websocket" "github.com/pkg/errors" - types "github.com/tendermint/go-rpc/types" + types "github.com/tendermint/tendermint/rpc/types" wire "github.com/tendermint/go-wire" cmn "github.com/tendermint/tmlibs/common" events "github.com/tendermint/tmlibs/events" diff --git a/rpc/server/http_server.go b/rpc/server/http_server.go index 5375c574f..a613be253 100644 --- a/rpc/server/http_server.go +++ b/rpc/server/http_server.go @@ -12,7 +12,7 @@ import ( "time" "github.com/pkg/errors" - types "github.com/tendermint/go-rpc/types" + types "github.com/tendermint/tendermint/rpc/types" ) func StartHTTPServer(listenAddr string, handler http.Handler) (listener net.Listener, err error) { @@ -20,7 +20,7 @@ func StartHTTPServer(listenAddr string, handler http.Handler) (listener net.List var proto, addr string parts := strings.SplitN(listenAddr, "://", 2) if len(parts) != 2 { - log.Warn("WARNING (go-rpc): Please use fully formed listening addresses, including the tcp:// or unix:// prefix") + log.Warn("WARNING (tendermint/rpc): Please use fully formed listening addresses, including the tcp:// or unix:// prefix") // we used to allow addrs without tcp/unix prefix by checking for a colon // TODO: Deprecate proto = types.SocketType(listenAddr) diff --git a/rpc/tendermint/client/httpclient.go b/rpc/tendermint/client/httpclient.go index 8e661443f..e8f404d22 100644 --- a/rpc/tendermint/client/httpclient.go +++ b/rpc/tendermint/client/httpclient.go @@ -6,7 +6,7 @@ import ( "github.com/pkg/errors" data "github.com/tendermint/go-wire/data" events "github.com/tendermint/tmlibs/events" - "github.com/tendermint/go-rpc/client" + "github.com/tendermint/tendermint/rpc/client" wire "github.com/tendermint/go-wire" ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" "github.com/tendermint/tendermint/types" diff --git a/rpc/tendermint/core/events.go b/rpc/tendermint/core/events.go index a92eda3d7..e12122e57 100644 --- a/rpc/tendermint/core/events.go +++ b/rpc/tendermint/core/events.go @@ -1,7 +1,7 @@ package core import ( - "github.com/tendermint/go-rpc/types" + "github.com/tendermint/tendermint/rpc/types" ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/core/routes.go b/rpc/tendermint/core/routes.go index d50968eee..1ed874f28 100644 --- a/rpc/tendermint/core/routes.go +++ b/rpc/tendermint/core/routes.go @@ -2,8 +2,8 @@ package core import ( data "github.com/tendermint/go-wire/data" - rpc "github.com/tendermint/go-rpc/server" - "github.com/tendermint/go-rpc/types" + rpc "github.com/tendermint/tendermint/rpc/server" + "github.com/tendermint/tendermint/rpc/types" ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/core/types/responses.go b/rpc/tendermint/core/types/responses.go index ba4584830..6f276def9 100644 --- a/rpc/tendermint/core/types/responses.go +++ b/rpc/tendermint/core/types/responses.go @@ -7,7 +7,7 @@ import ( "github.com/tendermint/go-crypto" data "github.com/tendermint/go-wire/data" "github.com/tendermint/go-p2p" - "github.com/tendermint/go-rpc/types" + "github.com/tendermint/tendermint/rpc/types" "github.com/tendermint/go-wire" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/test/client_test.go b/rpc/tendermint/test/client_test.go index 9c1bbd8d7..fda9fca27 100644 --- a/rpc/tendermint/test/client_test.go +++ b/rpc/tendermint/test/client_test.go @@ -12,7 +12,7 @@ import ( "github.com/stretchr/testify/require" abci "github.com/tendermint/abci/types" . "github.com/tendermint/tmlibs/common" - rpc "github.com/tendermint/go-rpc/client" + rpc "github.com/tendermint/tendermint/rpc/client" "github.com/tendermint/tendermint/rpc/tendermint/core" ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" "github.com/tendermint/tendermint/state/txindex/null" diff --git a/rpc/tendermint/test/helpers.go b/rpc/tendermint/test/helpers.go index 6f7050f8b..e5a2fb4e2 100644 --- a/rpc/tendermint/test/helpers.go +++ b/rpc/tendermint/test/helpers.go @@ -15,7 +15,7 @@ import ( abci "github.com/tendermint/abci/types" cfg "github.com/tendermint/go-config" - client "github.com/tendermint/go-rpc/client" + client "github.com/tendermint/tendermint/rpc/client" "github.com/tendermint/tendermint/config/tendermint_test" nm "github.com/tendermint/tendermint/node" "github.com/tendermint/tendermint/proxy" diff --git a/rpc/test/main.go b/rpc/test/main.go index 59c6e9b8f..ea91fcfd0 100644 --- a/rpc/test/main.go +++ b/rpc/test/main.go @@ -5,7 +5,7 @@ import ( "net/http" cmn "github.com/tendermint/tmlibs/common" - rpcserver "github.com/tendermint/go-rpc/server" + rpcserver "github.com/tendermint/tendermint/rpc/server" ) var routes = map[string]*rpcserver.RPCFunc{ diff --git a/test/test_libs.sh b/test/test_libs.sh index bf1b0096c..cb5090e1c 100644 --- a/test/test_libs.sh +++ b/test/test_libs.sh @@ -15,7 +15,7 @@ fi # some libs are tested with go, others with make # TODO: should be all make (post repo merge) LIBS_GO_TEST=(tmlibs/clist tmlibs/common go-config go-crypto tmlibs/db tmlibs/events go-merkle go-p2p) -LIBS_MAKE_TEST=(go-rpc go-wire abci) +LIBS_MAKE_TEST=(tendermint/rpc go-wire abci) for lib in "${LIBS_GO_TEST[@]}"; do From 56c60fba2381e4ac41d2ae38a1eb6569acfbc095 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 21 Apr 2017 18:19:41 -0400 Subject: [PATCH 195/309] go-p2p -> tendermint/p2p --- README.md | 2 +- benchmarks/codec_test.go | 2 +- blockchain/reactor.go | 2 +- cmd/tendermint/commands/probe_upnp.go | 2 +- consensus/byzantine_test.go | 2 +- consensus/common_test.go | 2 +- consensus/reactor.go | 2 +- consensus/reactor_test.go | 2 +- glide.lock | 2 +- glide.yaml | 2 +- mempool/reactor.go | 2 +- node/node.go | 2 +- p2p/Dockerfile | 10 +++++----- p2p/README.md | 6 +++--- p2p/connection_test.go | 2 +- p2p/listener.go | 2 +- rpc/tendermint/core/pipe.go | 2 +- rpc/tendermint/core/types/responses.go | 2 +- rpc/tendermint/core/types/responses_test.go | 2 +- test/test_libs.sh | 2 +- 20 files changed, 26 insertions(+), 26 deletions(-) diff --git a/README.md b/README.md index 24b3aef2e..0d7b85bbc 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ Yay open source! Please see our [contributing guidelines](https://tendermint.com * [ABCI](http://github.com/tendermint/abci) * [Mintnet](http://github.com/tendermint/mintnet) * [Go-Wire](http://github.com/tendermint/go-wire) -* [Go-P2P](http://github.com/tendermint/go-p2p) +* [Go-P2P](http://github.com/tendermint/tendermint/p2p) * [Go-Merkle](http://github.com/tendermint/go-merkle) ### Applications diff --git a/benchmarks/codec_test.go b/benchmarks/codec_test.go index 218b3fd04..205aec403 100644 --- a/benchmarks/codec_test.go +++ b/benchmarks/codec_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/tendermint/go-crypto" - "github.com/tendermint/go-p2p" + "github.com/tendermint/tendermint/p2p" "github.com/tendermint/go-wire" proto "github.com/tendermint/tendermint/benchmarks/proto" ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" diff --git a/blockchain/reactor.go b/blockchain/reactor.go index 122f03ae2..a788c4aca 100644 --- a/blockchain/reactor.go +++ b/blockchain/reactor.go @@ -8,7 +8,7 @@ import ( cmn "github.com/tendermint/tmlibs/common" cfg "github.com/tendermint/go-config" - "github.com/tendermint/go-p2p" + "github.com/tendermint/tendermint/p2p" "github.com/tendermint/go-wire" "github.com/tendermint/tendermint/proxy" sm "github.com/tendermint/tendermint/state" diff --git a/cmd/tendermint/commands/probe_upnp.go b/cmd/tendermint/commands/probe_upnp.go index bff433bc9..eb55d6690 100644 --- a/cmd/tendermint/commands/probe_upnp.go +++ b/cmd/tendermint/commands/probe_upnp.go @@ -6,7 +6,7 @@ import ( "github.com/spf13/cobra" - "github.com/tendermint/go-p2p/upnp" + "github.com/tendermint/tendermint/p2p/upnp" ) var probeUpnpCmd = &cobra.Command{ diff --git a/consensus/byzantine_test.go b/consensus/byzantine_test.go index fabf4e3c7..acd9e90e2 100644 --- a/consensus/byzantine_test.go +++ b/consensus/byzantine_test.go @@ -10,7 +10,7 @@ import ( . "github.com/tendermint/tmlibs/common" cfg "github.com/tendermint/go-config" "github.com/tendermint/tmlibs/events" - "github.com/tendermint/go-p2p" + "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/types" ) diff --git a/consensus/common_test.go b/consensus/common_test.go index 6effddb2e..77cc8172a 100644 --- a/consensus/common_test.go +++ b/consensus/common_test.go @@ -16,7 +16,7 @@ import ( . "github.com/tendermint/tmlibs/common" cfg "github.com/tendermint/go-config" dbm "github.com/tendermint/tmlibs/db" - "github.com/tendermint/go-p2p" + "github.com/tendermint/tendermint/p2p" bc "github.com/tendermint/tendermint/blockchain" "github.com/tendermint/tendermint/config/tendermint_test" mempl "github.com/tendermint/tendermint/mempool" diff --git a/consensus/reactor.go b/consensus/reactor.go index cd0c069ff..5fe45cc01 100644 --- a/consensus/reactor.go +++ b/consensus/reactor.go @@ -9,7 +9,7 @@ import ( "time" . "github.com/tendermint/tmlibs/common" - "github.com/tendermint/go-p2p" + "github.com/tendermint/tendermint/p2p" "github.com/tendermint/go-wire" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" diff --git a/consensus/reactor_test.go b/consensus/reactor_test.go index 1ebbf8a5b..66827c155 100644 --- a/consensus/reactor_test.go +++ b/consensus/reactor_test.go @@ -9,7 +9,7 @@ import ( "github.com/tendermint/tendermint/config/tendermint_test" "github.com/tendermint/tmlibs/events" - "github.com/tendermint/go-p2p" + "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/types" "github.com/tendermint/abci/example/dummy" ) diff --git a/glide.lock b/glide.lock index c7c4649e9..b83a05146 100644 --- a/glide.lock +++ b/glide.lock @@ -104,7 +104,7 @@ imports: version: cefb3a45c0bf3c493a04e9bcd9b1540528be59f2 - name: github.com/tendermint/go-merkle version: 714d4d04557fd068a7c2a1748241ce8428015a96 -- name: github.com/tendermint/go-p2p +- name: github.com/tendermint/tendermint/p2p version: b5f314ffed65c81bd019ba1dd2bae0e95f3937f3 subpackages: - upnp diff --git a/glide.yaml b/glide.yaml index a1013eb90..b7e24b545 100644 --- a/glide.yaml +++ b/glide.yaml @@ -20,7 +20,7 @@ import: version: develop - package: github.com/tendermint/go-merkle version: develop -- package: github.com/tendermint/go-p2p +- package: github.com/tendermint/tendermint/p2p version: unstable - package: github.com/tendermint/tendermint/rpc version: develop diff --git a/mempool/reactor.go b/mempool/reactor.go index 4b30dd4c8..4d1638888 100644 --- a/mempool/reactor.go +++ b/mempool/reactor.go @@ -9,7 +9,7 @@ import ( abci "github.com/tendermint/abci/types" "github.com/tendermint/tmlibs/clist" cfg "github.com/tendermint/go-config" - "github.com/tendermint/go-p2p" + "github.com/tendermint/tendermint/p2p" "github.com/tendermint/go-wire" "github.com/tendermint/tendermint/types" ) diff --git a/node/node.go b/node/node.go index e912495f2..f24c1c4f2 100644 --- a/node/node.go +++ b/node/node.go @@ -12,7 +12,7 @@ import ( cfg "github.com/tendermint/go-config" crypto "github.com/tendermint/go-crypto" dbm "github.com/tendermint/tmlibs/db" - p2p "github.com/tendermint/go-p2p" + p2p "github.com/tendermint/tendermint/p2p" rpc "github.com/tendermint/tendermint/rpc" rpcserver "github.com/tendermint/tendermint/rpc/server" wire "github.com/tendermint/go-wire" diff --git a/p2p/Dockerfile b/p2p/Dockerfile index 3716185f2..6c71b2f81 100644 --- a/p2p/Dockerfile +++ b/p2p/Dockerfile @@ -2,12 +2,12 @@ FROM golang:latest RUN curl https://glide.sh/get | sh -RUN mkdir -p /go/src/github.com/tendermint/go-p2p -WORKDIR /go/src/github.com/tendermint/go-p2p +RUN mkdir -p /go/src/github.com/tendermint/tendermint/p2p +WORKDIR /go/src/github.com/tendermint/tendermint/p2p -COPY glide.yaml /go/src/github.com/tendermint/go-p2p/ -COPY glide.lock /go/src/github.com/tendermint/go-p2p/ +COPY glide.yaml /go/src/github.com/tendermint/tendermint/p2p/ +COPY glide.lock /go/src/github.com/tendermint/tendermint/p2p/ RUN glide install -COPY . /go/src/github.com/tendermint/go-p2p +COPY . /go/src/github.com/tendermint/tendermint/p2p diff --git a/p2p/README.md b/p2p/README.md index 236efd367..bf0a5c4d0 100644 --- a/p2p/README.md +++ b/p2p/README.md @@ -1,8 +1,8 @@ -# `tendermint/go-p2p` +# `tendermint/tendermint/p2p` -[![CircleCI](https://circleci.com/gh/tendermint/go-p2p.svg?style=svg)](https://circleci.com/gh/tendermint/go-p2p) +[![CircleCI](https://circleci.com/gh/tendermint/tendermint/p2p.svg?style=svg)](https://circleci.com/gh/tendermint/tendermint/p2p) -`tendermint/go-p2p` provides an abstraction around peer-to-peer communication.
+`tendermint/tendermint/p2p` provides an abstraction around peer-to-peer communication.
## Peer/MConnection/Channel diff --git a/p2p/connection_test.go b/p2p/connection_test.go index 33d8adfd1..993d2d737 100644 --- a/p2p/connection_test.go +++ b/p2p/connection_test.go @@ -7,7 +7,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - p2p "github.com/tendermint/go-p2p" + p2p "github.com/tendermint/tendermint/p2p" ) func createMConnection(conn net.Conn) *p2p.MConnection { diff --git a/p2p/listener.go b/p2p/listener.go index 51beb5e27..2acf4d065 100644 --- a/p2p/listener.go +++ b/p2p/listener.go @@ -7,7 +7,7 @@ import ( "time" . "github.com/tendermint/tmlibs/common" - "github.com/tendermint/go-p2p/upnp" + "github.com/tendermint/tendermint/p2p/upnp" ) type Listener interface { diff --git a/rpc/tendermint/core/pipe.go b/rpc/tendermint/core/pipe.go index 4993ed992..d4a1d127e 100644 --- a/rpc/tendermint/core/pipe.go +++ b/rpc/tendermint/core/pipe.go @@ -4,7 +4,7 @@ import ( cfg "github.com/tendermint/go-config" crypto "github.com/tendermint/go-crypto" - p2p "github.com/tendermint/go-p2p" + p2p "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/consensus" "github.com/tendermint/tendermint/proxy" "github.com/tendermint/tendermint/state/txindex" diff --git a/rpc/tendermint/core/types/responses.go b/rpc/tendermint/core/types/responses.go index 6f276def9..f88b297e3 100644 --- a/rpc/tendermint/core/types/responses.go +++ b/rpc/tendermint/core/types/responses.go @@ -6,7 +6,7 @@ import ( abci "github.com/tendermint/abci/types" "github.com/tendermint/go-crypto" data "github.com/tendermint/go-wire/data" - "github.com/tendermint/go-p2p" + "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/rpc/types" "github.com/tendermint/go-wire" "github.com/tendermint/tendermint/types" diff --git a/rpc/tendermint/core/types/responses_test.go b/rpc/tendermint/core/types/responses_test.go index 69ee4faec..8eef19799 100644 --- a/rpc/tendermint/core/types/responses_test.go +++ b/rpc/tendermint/core/types/responses_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/stretchr/testify/assert" - "github.com/tendermint/go-p2p" + "github.com/tendermint/tendermint/p2p" ) func TestStatusIndexer(t *testing.T) { diff --git a/test/test_libs.sh b/test/test_libs.sh index cb5090e1c..1d57ae049 100644 --- a/test/test_libs.sh +++ b/test/test_libs.sh @@ -14,7 +14,7 @@ fi # some libs are tested with go, others with make # TODO: should be all make (post repo merge) -LIBS_GO_TEST=(tmlibs/clist tmlibs/common go-config go-crypto tmlibs/db tmlibs/events go-merkle go-p2p) +LIBS_GO_TEST=(tmlibs/clist tmlibs/common go-config go-crypto tmlibs/db tmlibs/events go-merkle tendermint/p2p) LIBS_MAKE_TEST=(tendermint/rpc go-wire abci) for lib in "${LIBS_GO_TEST[@]}"; do From e160318eefbc4ebcd2c82932b02b407c0f39de6a Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 21 Apr 2017 18:21:59 -0400 Subject: [PATCH 196/309] glide update --- glide.lock | 56 ++++++++++++----------------------- glide.yaml | 86 +++++++++++++++++++++++++++--------------------------- 2 files changed, 62 insertions(+), 80 deletions(-) diff --git a/glide.lock b/glide.lock index b83a05146..c96f014ff 100644 --- a/glide.lock +++ b/glide.lock @@ -1,5 +1,5 @@ -hash: 7fc53c3edfe508d56a5f2241ab73cef88652cbc40036ca2598730619edac7740 -updated: 2017-04-21T16:57:57.932584858-04:00 +hash: a79d5a28c894511eb8acfc59c1bd9b91ab15d7a6dae49701fbf037675852c50c +updated: 2017-04-21T18:21:33.986691926-04:00 imports: - name: github.com/btcsuite/btcd version: 583684b21bfbde9b5fc4403916fd7c807feb0289 @@ -78,42 +78,18 @@ imports: subpackages: - edwards25519 - extra25519 -- name: github.com/tendermint/tmlibs/autofile - version: 48b17de82914e1ec2f134ce823ba426337d2c518 -- name: github.com/tendermint/tmlibs/clist - version: 3baa390bbaf7634251c42ad69a8682e7e3990552 -- name: github.com/tendermint/tmlibs/common +- name: github.com/tendermint/go-common version: f9e3db037330c8a8d61d3966de8473eaf01154fa - subpackages: - - test - name: github.com/tendermint/go-config version: 620dcbbd7d587cf3599dedbf329b64311b0c307a - name: github.com/tendermint/go-crypto version: 9b95da8fa4187f6799558d89b271dc8ab6485615 -- name: github.com/tendermint/go-wire/data - version: e7fcc6d081ec8518912fcdc103188275f83a3ee5 -- name: github.com/tendermint/tmlibs/db +- name: github.com/tendermint/go-db version: 9643f60bc2578693844aacf380a7c32e4c029fee -- name: github.com/tendermint/tmlibs/events - version: f8ffbfb2be3483e9e7927495590a727f51c0c11f -- name: github.com/tendermint/go-flowrate - version: a20c98e61957faa93b4014fbd902f20ab9317a6a - subpackages: - - flowrate -- name: github.com/tendermint/tmlibs/logger +- name: github.com/tendermint/go-logger version: cefb3a45c0bf3c493a04e9bcd9b1540528be59f2 - name: github.com/tendermint/go-merkle version: 714d4d04557fd068a7c2a1748241ce8428015a96 -- name: github.com/tendermint/tendermint/p2p - version: b5f314ffed65c81bd019ba1dd2bae0e95f3937f3 - subpackages: - - upnp -- name: github.com/tendermint/tendermint/rpc - version: 2c8df0ee6b60d8ac33662df13a4e358c679e02bf - subpackages: - - client - - server - - types - name: github.com/tendermint/go-wire version: 334005c236d19c632fb5f073f9de3b0fab6a522b subpackages: @@ -122,19 +98,18 @@ imports: version: ae0f3d6450da9eac7074b439c8e1c3cabf0d5ce6 subpackages: - term -- name: github.com/tendermint/merkleeyes - version: 742c791e1b412ef0f2016a2d53647b58e40c8964 - subpackages: - - app - - client - - iavl - - testutil - name: github.com/tendermint/tmlibs version: df250b69416a35a943a6e2a92118667e9ef031d4 subpackages: + - autofile + - clist - common - db + - events + - flowrate - logger + - merkle + - test - name: golang.org/x/crypto version: 7c6cc321c680f03b9ef0764448e780704f486b51 subpackages: @@ -173,4 +148,11 @@ imports: - stats - tap - transport -testImports: [] +testImports: +- name: github.com/tendermint/merkleeyes + version: 742c791e1b412ef0f2016a2d53647b58e40c8964 + subpackages: + - app + - client + - iavl + - testutil diff --git a/glide.yaml b/glide.yaml index b7e24b545..1f4226d13 100644 --- a/glide.yaml +++ b/glide.yaml @@ -1,56 +1,56 @@ package: github.com/tendermint/tendermint import: -- package: github.com/tendermint/tmlibs/autofile - version: develop -- package: github.com/tendermint/tmlibs/clist - version: develop -- package: github.com/tendermint/tmlibs/common - version: develop +- package: github.com/ebuchman/fail-test +- package: github.com/gogo/protobuf + subpackages: + - proto +- package: github.com/golang/protobuf + subpackages: + - proto +- package: github.com/gorilla/websocket +- package: github.com/pkg/errors +- package: github.com/spf13/cobra +- package: github.com/stretchr/testify + subpackages: + - require +- package: github.com/tendermint/abci + subpackages: + - client + - example/dummy + - types - package: github.com/tendermint/go-config version: develop - package: github.com/tendermint/go-crypto version: develop -- package: github.com/tendermint/go-wire/data - version: develop -- package: github.com/tendermint/tmlibs/db - version: develop -- package: github.com/tendermint/tmlibs/events - version: develop -- package: github.com/tendermint/tmlibs/logger - version: develop -- package: github.com/tendermint/go-merkle - version: develop -- package: github.com/tendermint/tendermint/p2p - version: unstable -- package: github.com/tendermint/tendermint/rpc - version: develop - package: github.com/tendermint/go-wire version: develop -- package: github.com/tendermint/abci - version: develop -- package: github.com/tendermint/go-flowrate + subpackages: + - data - package: github.com/tendermint/log15 -- package: github.com/tendermint/ed25519 +- package: github.com/tendermint/tmlibs + version: develop + subpackages: + - autofile + - clist + - common + - db + - events + - flowrate + - logger + - merkle +- package: golang.org/x/crypto + subpackages: + - nacl/box + - nacl/secretbox + - ripemd160 +- package: golang.org/x/net + subpackages: + - context +- package: google.golang.org/grpc +testImport: - package: github.com/tendermint/merkleeyes version: develop subpackages: - app -- package: github.com/gogo/protobuf - version: ^0.3 - subpackages: - - proto -- package: github.com/gorilla/websocket - version: ^1.1.0 -- package: github.com/spf13/cobra -- package: github.com/spf13/pflag -- package: github.com/pkg/errors - version: ^0.8.0 -- package: golang.org/x/crypto - subpackages: - - ripemd160 -testImport: -- package: github.com/stretchr/testify - version: ^1.1.4 - subpackages: - - assert - - require + - iavl + - testutil From 4e0afc55e67f246cf8357e20bb21359b3c468c7f Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 21 Apr 2017 18:35:48 -0400 Subject: [PATCH 197/309] glide update --- glide.lock | 28 +++++++++++----------------- glide.yaml | 1 + 2 files changed, 12 insertions(+), 17 deletions(-) diff --git a/glide.lock b/glide.lock index c96f014ff..ffaaea755 100644 --- a/glide.lock +++ b/glide.lock @@ -1,5 +1,5 @@ -hash: a79d5a28c894511eb8acfc59c1bd9b91ab15d7a6dae49701fbf037675852c50c -updated: 2017-04-21T18:21:33.986691926-04:00 +hash: 9096fc4e29eff8fac3708ed30deacac67b7a181f0192b177006105dccdb16686 +updated: 2017-04-21T18:34:16.345204981-04:00 imports: - name: github.com/btcsuite/btcd version: 583684b21bfbde9b5fc4403916fd7c807feb0289 @@ -66,7 +66,7 @@ imports: - leveldb/table - leveldb/util - name: github.com/tendermint/abci - version: 56e13d87f4e3ec1ea756957d6b23caa6ebcf0998 + version: be61e273cebeb64866a83c578f92b22cf2169cdd subpackages: - client - example/counter @@ -84,12 +84,6 @@ imports: version: 620dcbbd7d587cf3599dedbf329b64311b0c307a - name: github.com/tendermint/go-crypto version: 9b95da8fa4187f6799558d89b271dc8ab6485615 -- name: github.com/tendermint/go-db - version: 9643f60bc2578693844aacf380a7c32e4c029fee -- name: github.com/tendermint/go-logger - version: cefb3a45c0bf3c493a04e9bcd9b1540528be59f2 -- name: github.com/tendermint/go-merkle - version: 714d4d04557fd068a7c2a1748241ce8428015a96 - name: github.com/tendermint/go-wire version: 334005c236d19c632fb5f073f9de3b0fab6a522b subpackages: @@ -98,6 +92,13 @@ imports: version: ae0f3d6450da9eac7074b439c8e1c3cabf0d5ce6 subpackages: - term +- name: github.com/tendermint/merkleeyes + version: 41fe51f4a6d3f1abc45fd4684e1351e084860ca4 + subpackages: + - app + - client + - iavl + - testutil - name: github.com/tendermint/tmlibs version: df250b69416a35a943a6e2a92118667e9ef031d4 subpackages: @@ -148,11 +149,4 @@ imports: - stats - tap - transport -testImports: -- name: github.com/tendermint/merkleeyes - version: 742c791e1b412ef0f2016a2d53647b58e40c8964 - subpackages: - - app - - client - - iavl - - testutil +testImports: [] diff --git a/glide.yaml b/glide.yaml index 1f4226d13..a5570d038 100644 --- a/glide.yaml +++ b/glide.yaml @@ -14,6 +14,7 @@ import: subpackages: - require - package: github.com/tendermint/abci + version: develop subpackages: - client - example/dummy From 3cdd2daf08d551dbe9bc07968f55a144a6fb698b Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 21 Apr 2017 18:44:37 -0400 Subject: [PATCH 198/309] fix tests --- glide.lock | 4 ++-- rpc/rpc_test.go | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/glide.lock b/glide.lock index ffaaea755..954064e5c 100644 --- a/glide.lock +++ b/glide.lock @@ -1,5 +1,5 @@ hash: 9096fc4e29eff8fac3708ed30deacac67b7a181f0192b177006105dccdb16686 -updated: 2017-04-21T18:34:16.345204981-04:00 +updated: 2017-04-21T18:39:37.154946943-04:00 imports: - name: github.com/btcsuite/btcd version: 583684b21bfbde9b5fc4403916fd7c807feb0289 @@ -93,7 +93,7 @@ imports: subpackages: - term - name: github.com/tendermint/merkleeyes - version: 41fe51f4a6d3f1abc45fd4684e1351e084860ca4 + version: 6fd69aa0871a4e685a5570aa7ab3d12e4068a722 subpackages: - app - client diff --git a/rpc/rpc_test.go b/rpc/rpc_test.go index 82940fc32..ef8832a88 100644 --- a/rpc/rpc_test.go +++ b/rpc/rpc_test.go @@ -12,18 +12,18 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + wire "github.com/tendermint/go-wire" client "github.com/tendermint/tendermint/rpc/client" server "github.com/tendermint/tendermint/rpc/server" types "github.com/tendermint/tendermint/rpc/types" - wire "github.com/tendermint/go-wire" ) // Client and Server should work over tcp or unix sockets const ( tcpAddr = "tcp://0.0.0.0:46657" - unixSocket = "/tmp/tendermint/rpc.sock" - unixAddr = "unix:///tmp/tendermint/rpc.sock" + unixSocket = "/tmp/rpc.sock" + unixAddr = "unix:///tmp/rpc.sock" websocketEndpoint = "/websocket/endpoint" ) From 803b1f21157aa869552c82545d7c03bc681b32db Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Tue, 25 Apr 2017 16:49:01 +0200 Subject: [PATCH 199/309] Improve client test cases --- rpc/tendermint/test/client_test.go | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/rpc/tendermint/test/client_test.go b/rpc/tendermint/test/client_test.go index fda9fca27..1164bdd79 100644 --- a/rpc/tendermint/test/client_test.go +++ b/rpc/tendermint/test/client_test.go @@ -11,12 +11,12 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" abci "github.com/tendermint/abci/types" - . "github.com/tendermint/tmlibs/common" rpc "github.com/tendermint/tendermint/rpc/client" "github.com/tendermint/tendermint/rpc/tendermint/core" ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" "github.com/tendermint/tendermint/state/txindex/null" "github.com/tendermint/tendermint/types" + . "github.com/tendermint/tmlibs/common" ) //-------------------------------------------------------------------------------- @@ -94,9 +94,12 @@ func testTxKV(t *testing.T) ([]byte, []byte, types.Tx) { func sendTx(t *testing.T, client rpc.HTTPClient) ([]byte, []byte) { tmResult := new(ctypes.TMResult) k, v, tx := testTxKV(t) - txBytes := []byte(tx) // XXX - _, err := client.Call("broadcast_tx_commit", map[string]interface{}{"tx": txBytes}, tmResult) + _, err := client.Call("broadcast_tx_commit", map[string]interface{}{"tx": tx}, tmResult) require.Nil(t, err) + bres := (*tmResult).(*ctypes.ResultBroadcastTxCommit) + require.NotNil(t, 0, bres.DeliverTx, "%#v", bres) + require.EqualValues(t, 0, bres.CheckTx.GetCode(), "%#v", bres) + require.EqualValues(t, 0, bres.DeliverTx.GetCode(), "%#v", bres) return k, v } @@ -105,7 +108,7 @@ func TestURIABCIQuery(t *testing.T) { } func TestJSONABCIQuery(t *testing.T) { - testABCIQuery(t, GetURIClient()) + testABCIQuery(t, GetJSONClient()) } func testABCIQuery(t *testing.T, client rpc.HTTPClient) { From bd93f76950f80995afedc18c6cddae592f7d2f07 Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Tue, 25 Apr 2017 17:17:51 +0200 Subject: [PATCH 200/309] Improve rpc to properly format any alias for []byte in URIClient --- rpc/client/args_test.go | 39 +++++++++++++++++++++++++++++++++++++++ rpc/client/http_client.go | 9 +++++---- 2 files changed, 44 insertions(+), 4 deletions(-) create mode 100644 rpc/client/args_test.go diff --git a/rpc/client/args_test.go b/rpc/client/args_test.go new file mode 100644 index 000000000..ccabd0d2c --- /dev/null +++ b/rpc/client/args_test.go @@ -0,0 +1,39 @@ +package rpcclient + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +type Tx []byte + +type Foo struct { + Bar int + Baz string +} + +func TestArgToJSON(t *testing.T) { + assert := assert.New(t) + require := require.New(t) + + cases := []struct { + input interface{} + expected string + }{ + {[]byte("1234"), "0x31323334"}, + {Tx("654"), "0x363534"}, + {Foo{7, "hello"}, `{"Bar":7,"Baz":"hello"}`}, + } + + for i, tc := range cases { + args := map[string]interface{}{"data": tc.input} + err := argsToJson(args) + require.Nil(err, "%d: %+v", i, err) + require.Equal(1, len(args), "%d", i) + data, ok := args["data"].(string) + require.True(ok, "%d: %#v", i, args["data"]) + assert.Equal(tc.expected, data, "%d", i) + } +} diff --git a/rpc/client/http_client.go b/rpc/client/http_client.go index ce78da43d..38a7f20fc 100644 --- a/rpc/client/http_client.go +++ b/rpc/client/http_client.go @@ -12,8 +12,8 @@ import ( "strings" "github.com/pkg/errors" - types "github.com/tendermint/tendermint/rpc/types" wire "github.com/tendermint/go-wire" + types "github.com/tendermint/tendermint/rpc/types" ) // HTTPClient is a common interface for JSONRPCClient and URIClient. @@ -179,10 +179,11 @@ func argsToJson(args map[string]interface{}) error { var n int var err error for k, v := range args { - // Convert byte slices to "0x"-prefixed hex - byteSlice, isByteSlice := reflect.ValueOf(v).Interface().([]byte) + rt := reflect.TypeOf(v) + isByteSlice := rt.Kind() == reflect.Slice && rt.Elem().Kind() == reflect.Uint8 if isByteSlice { - args[k] = fmt.Sprintf("0x%X", byteSlice) + bytes := reflect.ValueOf(v).Bytes() + args[k] = fmt.Sprintf("0x%X", bytes) continue } From 47852122d0db9841216554e1869d952e39292f38 Mon Sep 17 00:00:00 2001 From: rigelrozanski Date: Tue, 28 Mar 2017 02:00:42 -0400 Subject: [PATCH 201/309] changed reset commands --- cmd/tendermint/commands/reset_priv_validator.go | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/cmd/tendermint/commands/reset_priv_validator.go b/cmd/tendermint/commands/reset_priv_validator.go index b1fb334bc..49d277411 100644 --- a/cmd/tendermint/commands/reset_priv_validator.go +++ b/cmd/tendermint/commands/reset_priv_validator.go @@ -43,20 +43,21 @@ func resetPrivValidator(cmd *cobra.Command, args []string) { func ResetAll(c cfg.Config, l log15.Logger) { ResetPrivValidator(c, l) os.RemoveAll(c.GetString("db_dir")) + l.Notice("Removed all data", "dir", dataDir) } func ResetPrivValidator(c cfg.Config, l log15.Logger) { // Get PrivValidator var privValidator *types.PrivValidator - privValidatorFile := config.GetString("priv_validator_file") + privValidatorFile := c.GetString("priv_validator_file") if _, err := os.Stat(privValidatorFile); err == nil { privValidator = types.LoadPrivValidator(privValidatorFile) privValidator.Reset() - log.Notice("Reset PrivValidator", "file", privValidatorFile) + l.Notice("Reset PrivValidator", "file", privValidatorFile) } else { privValidator = types.GenPrivValidator() privValidator.SetFile(privValidatorFile) privValidator.Save() - log.Notice("Generated PrivValidator", "file", privValidatorFile) + l.Notice("Generated PrivValidator", "file", privValidatorFile) } } From cefb2bede0907cdb492eda165c1eed10c475d1ea Mon Sep 17 00:00:00 2001 From: Rigel Rozanski Date: Sat, 8 Apr 2017 22:04:06 -0400 Subject: [PATCH 202/309] adding viper int int --- blockchain/reactor.go | 10 +-- cmd/tendermint/commands/root.go | 3 +- config/tendermint/config.go | 102 ++++++++++++++++--------------- config/tendermint_test/config.go | 102 +++++++++++++++++-------------- consensus/byzantine_test.go | 8 ++- consensus/common_test.go | 14 +++-- consensus/replay.go | 10 +-- consensus/replay_file.go | 10 +-- consensus/replay_test.go | 15 ++--- consensus/state.go | 9 +-- glide.lock | 4 +- glide.yaml | 11 ++++ mempool/mempool.go | 12 ++-- mempool/reactor.go | 10 +-- node/node.go | 24 +++++--- proxy/client.go | 5 +- proxy/multi_app_conn.go | 9 +-- rpc/tendermint/core/pipe.go | 7 ++- rpc/tendermint/test/helpers.go | 9 +-- state/state.go | 6 +- 20 files changed, 218 insertions(+), 162 deletions(-) diff --git a/blockchain/reactor.go b/blockchain/reactor.go index a788c4aca..f45975e00 100644 --- a/blockchain/reactor.go +++ b/blockchain/reactor.go @@ -6,13 +6,15 @@ import ( "reflect" "time" - cmn "github.com/tendermint/tmlibs/common" + "github.com/spf13/viper" + cfg "github.com/tendermint/go-config" - "github.com/tendermint/tendermint/p2p" "github.com/tendermint/go-wire" + "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/proxy" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" + cmn "github.com/tendermint/tmlibs/common" ) const ( @@ -43,7 +45,7 @@ type consensusReactor interface { type BlockchainReactor struct { p2p.BaseReactor - config cfg.Config + config *viper.Viper state *sm.State proxyAppConn proxy.AppConnConsensus // same as consensus.proxyAppConn store *BlockStore @@ -57,7 +59,7 @@ type BlockchainReactor struct { } // NewBlockchainReactor returns new reactor instance. -func NewBlockchainReactor(config cfg.Config, state *sm.State, proxyAppConn proxy.AppConnConsensus, store *BlockStore, fastSync bool) *BlockchainReactor { +func NewBlockchainReactor(config *viper.Viper, state *sm.State, proxyAppConn proxy.AppConnConsensus, store *BlockStore, fastSync bool) *BlockchainReactor { if state.LastBlockHeight == store.Height()-1 { store.height-- // XXX HACK, make this better } diff --git a/cmd/tendermint/commands/root.go b/cmd/tendermint/commands/root.go index 120d53c04..78d197289 100644 --- a/cmd/tendermint/commands/root.go +++ b/cmd/tendermint/commands/root.go @@ -2,9 +2,10 @@ package commands import ( "github.com/spf13/cobra" + "github.com/spf13/viper" - "github.com/tendermint/tmlibs/logger" tmcfg "github.com/tendermint/tendermint/config/tendermint" + "github.com/tendermint/tmlibs/logger" ) var ( diff --git a/config/tendermint/config.go b/config/tendermint/config.go index 93650eaef..2e8cbb538 100644 --- a/config/tendermint/config.go +++ b/config/tendermint/config.go @@ -5,8 +5,10 @@ import ( "path" "strings" - . "github.com/tendermint/tmlibs/common" + "github.com/spf13/viper" + cfg "github.com/tendermint/go-config" + . "github.com/tendermint/tmlibs/common" ) func getTMRoot(rootDir string) string { @@ -38,72 +40,76 @@ func initTMRoot(rootDir string) { } } -func GetConfig(rootDir string) cfg.Config { +func GetConfig(rootDir string) *viper.Viper { rootDir = getTMRoot(rootDir) initTMRoot(rootDir) - configFilePath := path.Join(rootDir, "config.toml") - mapConfig, err := cfg.ReadMapConfigFromFile(configFilePath) + config := viper.New() + config.SetConfigName("config") + config.SetConfigType("toml") + config.AddConfigPath(rootDir) + err := viper.ReadInConfig() if err != nil { Exit(Fmt("Could not read config: %v", err)) } + config.WatchConfig() // Set defaults or panic - if mapConfig.IsSet("chain_id") { + if config.IsSet("chain_id") { Exit("Cannot set 'chain_id' via config.toml") } - if mapConfig.IsSet("revision_file") { + if config.IsSet("revision_file") { Exit("Cannot set 'revision_file' via config.toml. It must match what's in the Makefile") } - mapConfig.SetRequired("chain_id") // blows up if you try to use it before setting. - mapConfig.SetDefault("genesis_file", rootDir+"/genesis.json") - mapConfig.SetDefault("proxy_app", "tcp://127.0.0.1:46658") - mapConfig.SetDefault("abci", "socket") - mapConfig.SetDefault("moniker", "anonymous") - mapConfig.SetDefault("node_laddr", "tcp://0.0.0.0:46656") - mapConfig.SetDefault("seeds", "") - // mapConfig.SetDefault("seeds", "goldenalchemist.chaintest.net:46656") - mapConfig.SetDefault("fast_sync", true) - mapConfig.SetDefault("skip_upnp", false) - mapConfig.SetDefault("addrbook_file", rootDir+"/addrbook.json") - mapConfig.SetDefault("addrbook_strict", true) // disable to allow connections locally - mapConfig.SetDefault("pex_reactor", false) // enable for peer exchange - mapConfig.SetDefault("priv_validator_file", rootDir+"/priv_validator.json") - mapConfig.SetDefault("db_backend", "leveldb") - mapConfig.SetDefault("db_dir", rootDir+"/data") - mapConfig.SetDefault("log_level", "info") - mapConfig.SetDefault("rpc_laddr", "tcp://0.0.0.0:46657") - mapConfig.SetDefault("grpc_laddr", "") - mapConfig.SetDefault("prof_laddr", "") - mapConfig.SetDefault("revision_file", rootDir+"/revision") - mapConfig.SetDefault("cs_wal_file", rootDir+"/data/cs.wal/wal") - mapConfig.SetDefault("cs_wal_light", false) - mapConfig.SetDefault("filter_peers", false) + //mapConfig.SetRequired("chain_id") // blows up if you try to use it before setting. + config.SetDefault("genesis_file", rootDir+"/genesis.json") + config.SetDefault("proxy_app", "tcp://127.0.0.1:46658") + config.SetDefault("abci", "socket") + config.SetDefault("moniker", "anonymous") + config.SetDefault("node_laddr", "tcp://0.0.0.0:46656") + config.SetDefault("seeds", "") + // config.SetDefault("seeds", "goldenalchemist.chaintest.net:46656") + config.SetDefault("fast_sync", true) + config.SetDefault("skip_upnp", false) + config.SetDefault("addrbook_file", rootDir+"/addrbook.json") + config.SetDefault("addrbook_strict", true) // disable to allow connections locally + config.SetDefault("pex_reactor", false) // enable for peer exchange + config.SetDefault("priv_validator_file", rootDir+"/priv_validator.json") + config.SetDefault("db_backend", "leveldb") + config.SetDefault("db_dir", rootDir+"/data") + config.SetDefault("log_level", "info") + config.SetDefault("rpc_laddr", "tcp://0.0.0.0:46657") + config.SetDefault("grpc_laddr", "") + config.SetDefault("prof_laddr", "") + config.SetDefault("revision_file", rootDir+"/revision") + config.SetDefault("cs_wal_file", rootDir+"/data/cs.wal/wal") + config.SetDefault("cs_wal_light", false) + config.SetDefault("filter_peers", false) - mapConfig.SetDefault("block_size", 10000) // max number of txs - mapConfig.SetDefault("block_part_size", 65536) // part size 64K - mapConfig.SetDefault("disable_data_hash", false) + config.SetDefault("block_size", 10000) // max number of txs + config.SetDefault("block_part_size", 65536) // part size 64K + config.SetDefault("disable_data_hash", false) // all timeouts are in ms - mapConfig.SetDefault("timeout_handshake", 10000) - mapConfig.SetDefault("timeout_propose", 3000) - mapConfig.SetDefault("timeout_propose_delta", 500) - mapConfig.SetDefault("timeout_prevote", 1000) - mapConfig.SetDefault("timeout_prevote_delta", 500) - mapConfig.SetDefault("timeout_precommit", 1000) - mapConfig.SetDefault("timeout_precommit_delta", 500) - mapConfig.SetDefault("timeout_commit", 1000) + config.SetDefault("timeout_handshake", 10000) + config.SetDefault("timeout_propose", 3000) + config.SetDefault("timeout_propose_delta", 500) + config.SetDefault("timeout_prevote", 1000) + config.SetDefault("timeout_prevote_delta", 500) + config.SetDefault("timeout_precommit", 1000) + config.SetDefault("timeout_precommit_delta", 500) + config.SetDefault("timeout_commit", 1000) // make progress asap (no `timeout_commit`) on full precommit votes - mapConfig.SetDefault("skip_timeout_commit", false) - mapConfig.SetDefault("mempool_recheck", true) - mapConfig.SetDefault("mempool_recheck_empty", true) - mapConfig.SetDefault("mempool_broadcast", true) - mapConfig.SetDefault("mempool_wal_dir", rootDir+"/data/mempool.wal") + config.SetDefault("skip_timeout_commit", false) + config.SetDefault("mempool_recheck", true) + config.SetDefault("mempool_recheck_empty", true) + config.SetDefault("mempool_broadcast", true) + config.SetDefault("mempool_wal_dir", rootDir+"/data/mempool.wal") - mapConfig.SetDefault("tx_index", "kv") + config.SetDefault("tx_index", "kv") - return mapConfig + return config } var defaultConfigTmpl = `# This is a TOML config file. diff --git a/config/tendermint_test/config.go b/config/tendermint_test/config.go index fcdc572b9..846d28c64 100644 --- a/config/tendermint_test/config.go +++ b/config/tendermint_test/config.go @@ -3,12 +3,15 @@ package tendermint_test import ( + "fmt" "os" "path" "strings" - . "github.com/tendermint/tmlibs/common" + "github.com/spf13/viper" + cfg "github.com/tendermint/go-config" + . "github.com/tendermint/tmlibs/common" "github.com/tendermint/tmlibs/logger" ) @@ -53,65 +56,70 @@ func initTMRoot(rootDir string) { MustWriteFile(privFilePath, []byte(defaultPrivValidator), 0644) } -func ResetConfig(localPath string) cfg.Config { +func ResetConfig(localPath string) *viper.Viper { rootDir := os.Getenv("HOME") + "/.tendermint_test/" + localPath initTMRoot(rootDir) - configFilePath := path.Join(rootDir, "config.toml") - mapConfig, err := cfg.ReadMapConfigFromFile(configFilePath) + config := viper.New() + config.SetConfigName("config") + config.SetConfigType("toml") + config.AddConfigPath(rootDir) + err := config.ReadInConfig() if err != nil { Exit(Fmt("Could not read config: %v", err)) } + config.WatchConfig() // Set defaults or panic - if mapConfig.IsSet("chain_id") { - Exit("Cannot set 'chain_id' via config.toml") + if config.IsSet("chain_id") { + Exit(fmt.Sprintf("Cannot set 'chain_id' via config.toml:\n %v\n %v\n ", config.Get("chain_id"), rootDir)) } - mapConfig.SetDefault("chain_id", "tendermint_test") - mapConfig.SetDefault("genesis_file", rootDir+"/genesis.json") - mapConfig.SetDefault("proxy_app", "dummy") - mapConfig.SetDefault("abci", "socket") - mapConfig.SetDefault("moniker", "anonymous") - mapConfig.SetDefault("node_laddr", "tcp://0.0.0.0:36656") - mapConfig.SetDefault("fast_sync", false) - mapConfig.SetDefault("skip_upnp", true) - mapConfig.SetDefault("addrbook_file", rootDir+"/addrbook.json") - mapConfig.SetDefault("addrbook_strict", true) // disable to allow connections locally - mapConfig.SetDefault("pex_reactor", false) // enable for peer exchange - mapConfig.SetDefault("priv_validator_file", rootDir+"/priv_validator.json") - mapConfig.SetDefault("db_backend", "memdb") - mapConfig.SetDefault("db_dir", rootDir+"/data") - mapConfig.SetDefault("log_level", "info") - mapConfig.SetDefault("rpc_laddr", "tcp://0.0.0.0:36657") - mapConfig.SetDefault("grpc_laddr", "tcp://0.0.0.0:36658") - mapConfig.SetDefault("prof_laddr", "") - mapConfig.SetDefault("revision_file", rootDir+"/revision") - mapConfig.SetDefault("cs_wal_file", rootDir+"/data/cs.wal/wal") - mapConfig.SetDefault("cs_wal_light", false) - mapConfig.SetDefault("filter_peers", false) - mapConfig.SetDefault("block_size", 10000) - mapConfig.SetDefault("block_part_size", 65536) // part size 64K - mapConfig.SetDefault("disable_data_hash", false) - mapConfig.SetDefault("timeout_handshake", 10000) - mapConfig.SetDefault("timeout_propose", 2000) - mapConfig.SetDefault("timeout_propose_delta", 1) - mapConfig.SetDefault("timeout_prevote", 10) - mapConfig.SetDefault("timeout_prevote_delta", 1) - mapConfig.SetDefault("timeout_precommit", 10) - mapConfig.SetDefault("timeout_precommit_delta", 1) - mapConfig.SetDefault("timeout_commit", 10) - mapConfig.SetDefault("skip_timeout_commit", true) - mapConfig.SetDefault("mempool_recheck", true) - mapConfig.SetDefault("mempool_recheck_empty", true) - mapConfig.SetDefault("mempool_broadcast", true) - mapConfig.SetDefault("mempool_wal_dir", "") + config.SetDefault("chain_id", "tendermint_test") + config.SetDefault("genesis_file", rootDir+"/genesis.json") + config.SetDefault("proxy_app", "dummy") + config.SetDefault("abci", "socket") + config.SetDefault("moniker", "anonymous") + config.SetDefault("node_laddr", "tcp://0.0.0.0:36656") + config.SetDefault("fast_sync", false) + config.SetDefault("skip_upnp", true) + config.SetDefault("addrbook_file", rootDir+"/addrbook.json") + config.SetDefault("addrbook_strict", true) // disable to allow connections locally + config.SetDefault("pex_reactor", false) // enable for peer exchange + config.SetDefault("priv_validator_file", rootDir+"/priv_validator.json") + config.SetDefault("db_backend", "memdb") + config.SetDefault("db_dir", rootDir+"/data") + config.SetDefault("log_level", "info") + config.SetDefault("rpc_laddr", "tcp://0.0.0.0:36657") + config.SetDefault("grpc_laddr", "tcp://0.0.0.0:36658") + config.SetDefault("prof_laddr", "") + config.SetDefault("revision_file", rootDir+"/revision") + config.SetDefault("cs_wal_file", rootDir+"/data/cs.wal/wal") + config.SetDefault("cs_wal_light", false) + config.SetDefault("filter_peers", false) - mapConfig.SetDefault("tx_index", "kv") + config.SetDefault("block_size", 10000) + config.SetDefault("block_part_size", 65536) // part size 64K + config.SetDefault("disable_data_hash", false) + config.SetDefault("timeout_handshake", 10000) + config.SetDefault("timeout_propose", 2000) + config.SetDefault("timeout_propose_delta", 1) + config.SetDefault("timeout_prevote", 10) + config.SetDefault("timeout_prevote_delta", 1) + config.SetDefault("timeout_precommit", 10) + config.SetDefault("timeout_precommit_delta", 1) + config.SetDefault("timeout_commit", 10) + config.SetDefault("skip_timeout_commit", true) + config.SetDefault("mempool_recheck", true) + config.SetDefault("mempool_recheck_empty", true) + config.SetDefault("mempool_broadcast", true) + config.SetDefault("mempool_wal_dir", "") - logger.SetLogLevel(mapConfig.GetString("log_level")) + config.SetDefault("tx_index", "kv") - return mapConfig + logger.SetLogLevel(config.GetString("log_level")) + + return config } var defaultConfigTmpl = `# This is a TOML config file. diff --git a/consensus/byzantine_test.go b/consensus/byzantine_test.go index acd9e90e2..d4cda4046 100644 --- a/consensus/byzantine_test.go +++ b/consensus/byzantine_test.go @@ -5,13 +5,15 @@ import ( "testing" "time" + "github.com/spf13/viper" + "github.com/tendermint/tendermint/config/tendermint_test" - . "github.com/tendermint/tmlibs/common" cfg "github.com/tendermint/go-config" - "github.com/tendermint/tmlibs/events" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/types" + . "github.com/tendermint/tmlibs/common" + "github.com/tendermint/tmlibs/events" ) func init() { @@ -36,7 +38,7 @@ func TestByzantine(t *testing.T) { switches := make([]*p2p.Switch, N) for i := 0; i < N; i++ { - switches[i] = p2p.NewSwitch(cfg.NewMapConfig(nil)) + switches[i] = p2p.NewSwitch(viper.New()) } reactors := make([]p2p.Reactor, N) diff --git a/consensus/common_test.go b/consensus/common_test.go index 77cc8172a..7acb54ad7 100644 --- a/consensus/common_test.go +++ b/consensus/common_test.go @@ -11,23 +11,25 @@ import ( "testing" "time" + "github.com/spf13/viper" + abcicli "github.com/tendermint/abci/client" abci "github.com/tendermint/abci/types" - . "github.com/tendermint/tmlibs/common" cfg "github.com/tendermint/go-config" - dbm "github.com/tendermint/tmlibs/db" - "github.com/tendermint/tendermint/p2p" bc "github.com/tendermint/tendermint/blockchain" "github.com/tendermint/tendermint/config/tendermint_test" mempl "github.com/tendermint/tendermint/mempool" + "github.com/tendermint/tendermint/p2p" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" + . "github.com/tendermint/tmlibs/common" + dbm "github.com/tendermint/tmlibs/db" "github.com/tendermint/abci/example/counter" "github.com/tendermint/abci/example/dummy" ) -var config cfg.Config // NOTE: must be reset for each _test.go file +var config *viper.Viper // NOTE: must be reset for each _test.go file var ensureTimeout = time.Duration(2) func ensureDir(dir string, mode os.FileMode) { @@ -233,7 +235,7 @@ func newConsensusState(state *sm.State, pv *types.PrivValidator, app abci.Applic return newConsensusStateWithConfig(config, state, pv, app) } -func newConsensusStateWithConfig(thisConfig cfg.Config, state *sm.State, pv *types.PrivValidator, app abci.Application) *ConsensusState { +func newConsensusStateWithConfig(thisConfig *viper.Viper, state *sm.State, pv *types.PrivValidator, app abci.Application) *ConsensusState { // Get BlockStore blockDB := dbm.NewMemDB() blockStore := bc.NewBlockStore(blockDB) @@ -256,7 +258,7 @@ func newConsensusStateWithConfig(thisConfig cfg.Config, state *sm.State, pv *typ return cs } -func loadPrivValidator(conf cfg.Config) *types.PrivValidator { +func loadPrivValidator(conf *viper.Viper) *types.PrivValidator { privValidatorFile := conf.GetString("priv_validator_file") ensureDir(path.Dir(privValidatorFile), 0700) privValidator := types.LoadOrGenPrivValidator(privValidatorFile) diff --git a/consensus/replay.go b/consensus/replay.go index 931e8893d..acbe44098 100644 --- a/consensus/replay.go +++ b/consensus/replay.go @@ -10,11 +10,13 @@ import ( "strings" "time" + "github.com/spf13/viper" + abci "github.com/tendermint/abci/types" - auto "github.com/tendermint/tmlibs/autofile" - . "github.com/tendermint/tmlibs/common" cfg "github.com/tendermint/go-config" "github.com/tendermint/go-wire" + auto "github.com/tendermint/tmlibs/autofile" + . "github.com/tendermint/tmlibs/common" "github.com/tendermint/tendermint/proxy" sm "github.com/tendermint/tendermint/state" @@ -199,14 +201,14 @@ func makeHeightSearchFunc(height int) auto.SearchFunc { // we were last and using the WAL to recover there type Handshaker struct { - config cfg.Config + config *viper.Viper state *sm.State store types.BlockStore nBlocks int // number of blocks applied to the state } -func NewHandshaker(config cfg.Config, state *sm.State, store types.BlockStore) *Handshaker { +func NewHandshaker(config *viper.Viper, state *sm.State, store types.BlockStore) *Handshaker { return &Handshaker{config, state, store, 0} } diff --git a/consensus/replay_file.go b/consensus/replay_file.go index 3de0e3d10..e5056ef0d 100644 --- a/consensus/replay_file.go +++ b/consensus/replay_file.go @@ -8,20 +8,22 @@ import ( "strconv" "strings" - . "github.com/tendermint/tmlibs/common" + "github.com/spf13/viper" + cfg "github.com/tendermint/go-config" - dbm "github.com/tendermint/tmlibs/db" bc "github.com/tendermint/tendermint/blockchain" mempl "github.com/tendermint/tendermint/mempool" "github.com/tendermint/tendermint/proxy" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" + . "github.com/tendermint/tmlibs/common" + dbm "github.com/tendermint/tmlibs/db" ) //-------------------------------------------------------- // replay messages interactively or all at once -func RunReplayFile(config cfg.Config, walFile string, console bool) { +func RunReplayFile(config *viper.Viper, walFile string, console bool) { consensusState := newConsensusStateForReplay(config) if err := consensusState.ReplayFile(walFile, console); err != nil { @@ -236,7 +238,7 @@ func (pb *playback) replayConsoleLoop() int { //-------------------------------------------------------------------------------- // convenience for replay mode -func newConsensusStateForReplay(config cfg.Config) *ConsensusState { +func newConsensusStateForReplay(config *viper.Viper) *ConsensusState { // Get BlockStore blockStoreDB := dbm.NewDB("blockstore", config.GetString("db_backend"), config.GetString("db_dir")) blockStore := bc.NewBlockStore(blockStoreDB) diff --git a/consensus/replay_test.go b/consensus/replay_test.go index 32415d6e3..b78d5915f 100644 --- a/consensus/replay_test.go +++ b/consensus/replay_test.go @@ -12,17 +12,18 @@ import ( "testing" "time" - "github.com/tendermint/tendermint/config/tendermint_test" + "github.com/spf13/viper" "github.com/tendermint/abci/example/dummy" - cmn "github.com/tendermint/tmlibs/common" cfg "github.com/tendermint/go-config" "github.com/tendermint/go-crypto" - dbm "github.com/tendermint/tmlibs/db" "github.com/tendermint/go-wire" + "github.com/tendermint/tendermint/config/tendermint_test" "github.com/tendermint/tendermint/proxy" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" + cmn "github.com/tendermint/tmlibs/common" + dbm "github.com/tendermint/tmlibs/db" ) func init() { @@ -408,7 +409,7 @@ func buildAppStateFromChain(proxyApp proxy.AppConns, } -func buildTMStateFromChain(config cfg.Config, state *sm.State, chain []*types.Block, mode uint) []byte { +func buildTMStateFromChain(config *viper.Viper, state *sm.State, chain []*types.Block, mode uint) []byte { // run the whole chain against this client to build up the tendermint state clientCreator := proxy.NewLocalClientCreator(dummy.NewPersistentDummyApplication(path.Join(config.GetString("db_dir"), "1"))) proxyApp := proxy.NewAppConns(config, clientCreator, nil) // sm.NewHandshaker(config, state, store, ReplayLastBlock)) @@ -602,7 +603,7 @@ func makeBlockchain(t *testing.T, chainID string, nBlocks int, privVal *types.Pr } // fresh state and mock store -func stateAndStore(config cfg.Config, pubKey crypto.PubKey) (*sm.State, *mockBlockStore) { +func stateAndStore(config *viper.Viper, pubKey crypto.PubKey) (*sm.State, *mockBlockStore) { stateDB := dbm.NewMemDB() return sm.MakeGenesisState(stateDB, &types.GenesisDoc{ ChainID: config.GetString("chain_id"), @@ -617,13 +618,13 @@ func stateAndStore(config cfg.Config, pubKey crypto.PubKey) (*sm.State, *mockBlo // mock block store type mockBlockStore struct { - config cfg.Config + config *viper.Viper chain []*types.Block commits []*types.Commit } // TODO: NewBlockStore(db.NewMemDB) ... -func NewMockBlockStore(config cfg.Config) *mockBlockStore { +func NewMockBlockStore(config *viper.Viper) *mockBlockStore { return &mockBlockStore{config, nil, nil} } diff --git a/consensus/state.go b/consensus/state.go index 8077dcec1..06c20db2a 100644 --- a/consensus/state.go +++ b/consensus/state.go @@ -10,13 +10,14 @@ import ( "time" "github.com/ebuchman/fail-test" + "github.com/spf13/viper" - . "github.com/tendermint/tmlibs/common" cfg "github.com/tendermint/go-config" "github.com/tendermint/go-wire" "github.com/tendermint/tendermint/proxy" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" + . "github.com/tendermint/tmlibs/common" ) //----------------------------------------------------------------------------- @@ -56,7 +57,7 @@ func (tp *TimeoutParams) Commit(t time.Time) time.Time { } // InitTimeoutParamsFromConfig initializes parameters from config -func InitTimeoutParamsFromConfig(config cfg.Config) *TimeoutParams { +func InitTimeoutParamsFromConfig(config *viper.Viper) *TimeoutParams { return &TimeoutParams{ Propose0: config.GetInt("timeout_propose"), ProposeDelta: config.GetInt("timeout_propose_delta"), @@ -224,7 +225,7 @@ type PrivValidator interface { type ConsensusState struct { BaseService - config cfg.Config + config *viper.Viper proxyAppConn proxy.AppConnConsensus blockStore types.BlockStore mempool types.Mempool @@ -255,7 +256,7 @@ type ConsensusState struct { done chan struct{} } -func NewConsensusState(config cfg.Config, state *sm.State, proxyAppConn proxy.AppConnConsensus, blockStore types.BlockStore, mempool types.Mempool) *ConsensusState { +func NewConsensusState(config *viper.Viper, state *sm.State, proxyAppConn proxy.AppConnConsensus, blockStore types.BlockStore, mempool types.Mempool) *ConsensusState { cs := &ConsensusState{ config: config, proxyAppConn: proxyAppConn, diff --git a/glide.lock b/glide.lock index 954064e5c..7b8eb278b 100644 --- a/glide.lock +++ b/glide.lock @@ -41,8 +41,10 @@ imports: version: d8ed2627bdf02c080bf22230dbb337003b7aba2d subpackages: - difflib +- name: github.com/spf13/viper + version: 84f94806c67f59dd7ae87bc5351f7a9c94a4558d - name: github.com/spf13/cobra - version: fcd0c5a1df88f5d6784cb4feead962c3f3d0b66c + version: 5deb57bbca49eb370538fc295ba4b2988f9f5e09 - name: github.com/spf13/pflag version: 9ff6c6923cfffbcd502984b8e0c80539a94968b7 - name: github.com/stretchr/testify diff --git a/glide.yaml b/glide.yaml index a5570d038..e4c2e4138 100644 --- a/glide.yaml +++ b/glide.yaml @@ -39,6 +39,17 @@ import: - flowrate - logger - merkle +- package: github.com/gogo/protobuf + version: ^0.3 + subpackages: + - proto +- package: github.com/gorilla/websocket + version: ^1.1.0 +- package: github.com/spf13/cobra +- package: github.com/spf13/viper +- package: github.com/spf13/pflag +- package: github.com/pkg/errors + version: ^0.8.0 - package: golang.org/x/crypto subpackages: - nacl/box diff --git a/mempool/mempool.go b/mempool/mempool.go index eedf6fb9c..086a99e32 100644 --- a/mempool/mempool.go +++ b/mempool/mempool.go @@ -7,13 +7,15 @@ import ( "sync/atomic" "time" + "github.com/spf13/viper" + abci "github.com/tendermint/abci/types" - auto "github.com/tendermint/tmlibs/autofile" - "github.com/tendermint/tmlibs/clist" - . "github.com/tendermint/tmlibs/common" cfg "github.com/tendermint/go-config" "github.com/tendermint/tendermint/proxy" "github.com/tendermint/tendermint/types" + auto "github.com/tendermint/tmlibs/autofile" + "github.com/tendermint/tmlibs/clist" + . "github.com/tendermint/tmlibs/common" ) /* @@ -47,7 +49,7 @@ TODO: Better handle abci client errors. (make it automatically handle connection const cacheSize = 100000 type Mempool struct { - config cfg.Config + config *viper.Viper proxyMtx sync.Mutex proxyAppConn proxy.AppConnMempool @@ -66,7 +68,7 @@ type Mempool struct { wal *auto.AutoFile } -func NewMempool(config cfg.Config, proxyAppConn proxy.AppConnMempool) *Mempool { +func NewMempool(config *viper.Viper, proxyAppConn proxy.AppConnMempool) *Mempool { mempool := &Mempool{ config: config, proxyAppConn: proxyAppConn, diff --git a/mempool/reactor.go b/mempool/reactor.go index 4d1638888..d30fd1151 100644 --- a/mempool/reactor.go +++ b/mempool/reactor.go @@ -6,12 +6,14 @@ import ( "reflect" "time" + "github.com/spf13/viper" + abci "github.com/tendermint/abci/types" - "github.com/tendermint/tmlibs/clist" cfg "github.com/tendermint/go-config" - "github.com/tendermint/tendermint/p2p" "github.com/tendermint/go-wire" + "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/types" + "github.com/tendermint/tmlibs/clist" ) const ( @@ -24,12 +26,12 @@ const ( // MempoolReactor handles mempool tx broadcasting amongst peers. type MempoolReactor struct { p2p.BaseReactor - config cfg.Config + config *viper.Viper Mempool *Mempool evsw types.EventSwitch } -func NewMempoolReactor(config cfg.Config, mempool *Mempool) *MempoolReactor { +func NewMempoolReactor(config *viper.Viper, mempool *Mempool) *MempoolReactor { memR := &MempoolReactor{ config: config, Mempool: mempool, diff --git a/node/node.go b/node/node.go index f24c1c4f2..17fb98bad 100644 --- a/node/node.go +++ b/node/node.go @@ -7,19 +7,19 @@ import ( "net/http" "strings" + "github.com/spf13/viper" + abci "github.com/tendermint/abci/types" - cmn "github.com/tendermint/tmlibs/common" cfg "github.com/tendermint/go-config" crypto "github.com/tendermint/go-crypto" - dbm "github.com/tendermint/tmlibs/db" - p2p "github.com/tendermint/tendermint/p2p" - rpc "github.com/tendermint/tendermint/rpc" - rpcserver "github.com/tendermint/tendermint/rpc/server" wire "github.com/tendermint/go-wire" bc "github.com/tendermint/tendermint/blockchain" "github.com/tendermint/tendermint/consensus" mempl "github.com/tendermint/tendermint/mempool" + p2p "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/proxy" + rpc "github.com/tendermint/tendermint/rpc" + rpcserver "github.com/tendermint/tendermint/rpc/server" rpccore "github.com/tendermint/tendermint/rpc/tendermint/core" grpccore "github.com/tendermint/tendermint/rpc/tendermint/grpc" sm "github.com/tendermint/tendermint/state" @@ -28,6 +28,8 @@ import ( "github.com/tendermint/tendermint/state/txindex/null" "github.com/tendermint/tendermint/types" "github.com/tendermint/tendermint/version" + cmn "github.com/tendermint/tmlibs/common" + dbm "github.com/tendermint/tmlibs/db" _ "net/http/pprof" ) @@ -36,7 +38,7 @@ type Node struct { cmn.BaseService // config - config cfg.Config // user config + config *viper.Viper // user config genesisDoc *types.GenesisDoc // initial validator set privValidator *types.PrivValidator // local node's validator key @@ -57,14 +59,14 @@ type Node struct { txIndexer txindex.TxIndexer } -func NewNodeDefault(config cfg.Config) *Node { +func NewNodeDefault(config *viper.Viper) *Node { // Get PrivValidator privValidatorFile := config.GetString("priv_validator_file") privValidator := types.LoadOrGenPrivValidator(privValidatorFile) return NewNode(config, privValidator, proxy.DefaultClientCreator(config)) } -func NewNode(config cfg.Config, privValidator *types.PrivValidator, clientCreator proxy.ClientCreator) *Node { +func NewNode(config *viper.Viper, privValidator *types.PrivValidator, clientCreator proxy.ClientCreator) *Node { // Get BlockStore blockStoreDB := dbm.NewDB("blockstore", config.GetString("db_backend"), config.GetString("db_dir")) @@ -134,7 +136,11 @@ func NewNode(config cfg.Config, privValidator *types.PrivValidator, clientCreato consensusReactor := consensus.NewConsensusReactor(consensusState, fastSync) // Make p2p network switch - sw := p2p.NewSwitch(config.GetConfig("p2p")) + p2pConfig := viper.New() + if config.IsSet("p2p") { //TODO verify this necessary, where is this ever set? + p2pConfig = config.Get("p2p").(*viper.Viper) + } + sw := p2p.NewSwitch(p2pConfig) sw.AddReactor("MEMPOOL", mempoolReactor) sw.AddReactor("BLOCKCHAIN", bcReactor) sw.AddReactor("CONSENSUS", consensusReactor) diff --git a/proxy/client.go b/proxy/client.go index ea9051989..4c50f38b3 100644 --- a/proxy/client.go +++ b/proxy/client.go @@ -4,10 +4,11 @@ import ( "fmt" "sync" + "github.com/spf13/viper" + abcicli "github.com/tendermint/abci/client" "github.com/tendermint/abci/example/dummy" "github.com/tendermint/abci/types" - cfg "github.com/tendermint/go-config" ) // NewABCIClient returns newly connected client @@ -63,7 +64,7 @@ func (r *remoteClientCreator) NewABCIClient() (abcicli.Client, error) { //----------------------------------------------------------------- // default -func DefaultClientCreator(config cfg.Config) ClientCreator { +func DefaultClientCreator(config *viper.Viper) ClientCreator { addr := config.GetString("proxy_app") transport := config.GetString("abci") diff --git a/proxy/multi_app_conn.go b/proxy/multi_app_conn.go index b70a0baf0..bb846c7fa 100644 --- a/proxy/multi_app_conn.go +++ b/proxy/multi_app_conn.go @@ -1,8 +1,9 @@ package proxy import ( - cmn "github.com/tendermint/tmlibs/common" + "github.com/spf13/viper" cfg "github.com/tendermint/go-config" + cmn "github.com/tendermint/tmlibs/common" ) //----------------------------- @@ -16,7 +17,7 @@ type AppConns interface { Query() AppConnQuery } -func NewAppConns(config cfg.Config, clientCreator ClientCreator, handshaker Handshaker) AppConns { +func NewAppConns(config *viper.Viper, clientCreator ClientCreator, handshaker Handshaker) AppConns { return NewMultiAppConn(config, clientCreator, handshaker) } @@ -34,7 +35,7 @@ type Handshaker interface { type multiAppConn struct { cmn.BaseService - config cfg.Config + config *viper.Viper handshaker Handshaker @@ -46,7 +47,7 @@ type multiAppConn struct { } // Make all necessary abci connections to the application -func NewMultiAppConn(config cfg.Config, clientCreator ClientCreator, handshaker Handshaker) *multiAppConn { +func NewMultiAppConn(config *viper.Viper, clientCreator ClientCreator, handshaker Handshaker) *multiAppConn { multiAppConn := &multiAppConn{ config: config, handshaker: handshaker, diff --git a/rpc/tendermint/core/pipe.go b/rpc/tendermint/core/pipe.go index d4a1d127e..6f4740902 100644 --- a/rpc/tendermint/core/pipe.go +++ b/rpc/tendermint/core/pipe.go @@ -1,11 +1,12 @@ package core import ( + "github.com/spf13/viper" cfg "github.com/tendermint/go-config" crypto "github.com/tendermint/go-crypto" - p2p "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/consensus" + p2p "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/proxy" "github.com/tendermint/tendermint/state/txindex" "github.com/tendermint/tendermint/types" @@ -34,7 +35,7 @@ var ( // external, thread safe interfaces eventSwitch types.EventSwitch proxyAppQuery proxy.AppConnQuery - config cfg.Config + config *viper.Viper // interfaces defined in types and above blockStore types.BlockStore @@ -49,7 +50,7 @@ var ( txIndexer txindex.TxIndexer ) -func SetConfig(c cfg.Config) { +func SetConfig(c *viper.Viper) { config = c } diff --git a/rpc/tendermint/test/helpers.go b/rpc/tendermint/test/helpers.go index e5a2fb4e2..8477ef570 100644 --- a/rpc/tendermint/test/helpers.go +++ b/rpc/tendermint/test/helpers.go @@ -9,23 +9,24 @@ import ( "testing" "time" + "github.com/spf13/viper" "github.com/stretchr/testify/require" - logger "github.com/tendermint/tmlibs/logger" wire "github.com/tendermint/go-wire" + logger "github.com/tendermint/tmlibs/logger" abci "github.com/tendermint/abci/types" cfg "github.com/tendermint/go-config" - client "github.com/tendermint/tendermint/rpc/client" "github.com/tendermint/tendermint/config/tendermint_test" nm "github.com/tendermint/tendermint/node" "github.com/tendermint/tendermint/proxy" + client "github.com/tendermint/tendermint/rpc/client" ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" core_grpc "github.com/tendermint/tendermint/rpc/tendermint/grpc" "github.com/tendermint/tendermint/types" ) var ( - config cfg.Config + config *viper.Viper ) const tmLogLevel = "error" @@ -56,7 +57,7 @@ func makeAddrs() (string, string, string) { } // GetConfig returns a config for the test cases as a singleton -func GetConfig() cfg.Config { +func GetConfig() *viper.Viper { if config == nil { pathname := makePathname() config = tendermint_test.ResetConfig(pathname) diff --git a/state/state.go b/state/state.go index ccdf508ac..3055fb7b7 100644 --- a/state/state.go +++ b/state/state.go @@ -6,10 +6,12 @@ import ( "sync" "time" + "github.com/spf13/viper" abci "github.com/tendermint/abci/types" - . "github.com/tendermint/tmlibs/common" cfg "github.com/tendermint/go-config" + . "github.com/tendermint/tmlibs/common" dbm "github.com/tendermint/tmlibs/db" + "github.com/tendermint/go-wire" "github.com/tendermint/tendermint/state/txindex" "github.com/tendermint/tendermint/state/txindex/null" @@ -168,7 +170,7 @@ func (s *State) GetValidators() (*types.ValidatorSet, *types.ValidatorSet) { // Load the most recent state from "state" db, // or create a new one (and save) from genesis. -func GetState(config cfg.Config, stateDB dbm.DB) *State { +func GetState(config *viper.Viper, stateDB dbm.DB) *State { state := LoadState(stateDB) if state == nil { state = MakeGenesisStateFromFile(stateDB, config.GetString("genesis_file")) From 270b68a893474cd22c820cc6eb3fa3f26b2b2c20 Mon Sep 17 00:00:00 2001 From: Rigel Rozanski Date: Sun, 9 Apr 2017 23:07:15 -0400 Subject: [PATCH 203/309] glide lock updates --- .../commands/reset_priv_validator.go | 7 +-- glide.lock | 43 ++++++++++++++++--- rpc/tendermint/test/client_test.go | 1 + 3 files changed, 42 insertions(+), 9 deletions(-) diff --git a/cmd/tendermint/commands/reset_priv_validator.go b/cmd/tendermint/commands/reset_priv_validator.go index 49d277411..c880e8313 100644 --- a/cmd/tendermint/commands/reset_priv_validator.go +++ b/cmd/tendermint/commands/reset_priv_validator.go @@ -4,8 +4,8 @@ import ( "os" "github.com/spf13/cobra" + "github.com/spf13/viper" - cfg "github.com/tendermint/go-config" "github.com/tendermint/log15" "github.com/tendermint/tendermint/types" ) @@ -40,13 +40,14 @@ func resetPrivValidator(cmd *cobra.Command, args []string) { } // Exported so other CLI tools can use it -func ResetAll(c cfg.Config, l log15.Logger) { +func ResetAll(c *viper.Viper, l log15.Logger) { ResetPrivValidator(c, l) os.RemoveAll(c.GetString("db_dir")) l.Notice("Removed all data", "dir", dataDir) } -func ResetPrivValidator(c cfg.Config, l log15.Logger) { +func ResetPrivValidator(c *viper.Viper, l log15.Logger) { + // Get PrivValidator var privValidator *types.PrivValidator privValidatorFile := c.GetString("priv_validator_file") diff --git a/glide.lock b/glide.lock index 7b8eb278b..bc4778927 100644 --- a/glide.lock +++ b/glide.lock @@ -13,6 +13,8 @@ imports: - spew - name: github.com/ebuchman/fail-test version: 95f809107225be108efcf10a3509e4ea6ceef3c4 +- name: github.com/fsnotify/fsnotify + version: 4da3e2cfbabc9f751898f250b49f2439785783a1 - name: github.com/go-stack/stack version: 100eb0c0a9c5b306ca2fb4f165df21d80ada4b82 - name: github.com/gogo/protobuf @@ -27,26 +29,53 @@ imports: version: d9eb7a3d35ec988b8585d4a0068e462c27d28380 - name: github.com/gorilla/websocket version: 3ab3a8b8831546bd18fd182c20687ca853b2bb13 +- name: github.com/hashicorp/hcl + version: 630949a3c5fa3c613328e1b8256052cbc2327c9b + subpackages: + - hcl/ast + - hcl/parser + - hcl/scanner + - hcl/strconv + - hcl/token + - json/parser + - json/scanner + - json/token - name: github.com/inconshreveable/mousetrap version: 76626ae9c91c4f2a10f34cad8ce83ea42c93bb75 - name: github.com/jmhodges/levigo version: c42d9e0ca023e2198120196f842701bb4c55d7b9 +- name: github.com/magiconair/properties + version: 51463bfca2576e06c62a8504b5c0f06d61312647 - name: github.com/mattn/go-colorable version: d228849504861217f796da67fae4f6e347643f15 - name: github.com/mattn/go-isatty version: 30a891c33c7cde7b02a981314b4228ec99380cca +- name: github.com/mitchellh/mapstructure + version: 53818660ed4955e899c0bcafa97299a388bd7c8e +- name: github.com/pelletier/go-buffruneio + version: c37440a7cf42ac63b919c752ca73a85067e05992 +- name: github.com/pelletier/go-toml + version: fe206efb84b2bc8e8cfafe6b4c1826622be969e3 - name: github.com/pkg/errors version: 645ef00459ed84a119197bfb8d8205042c6df63d - name: github.com/pmezard/go-difflib version: d8ed2627bdf02c080bf22230dbb337003b7aba2d subpackages: - difflib -- name: github.com/spf13/viper - version: 84f94806c67f59dd7ae87bc5351f7a9c94a4558d +- name: github.com/spf13/afero + version: 9be650865eab0c12963d8753212f4f9c66cdcf12 + subpackages: + - mem +- name: github.com/spf13/cast + version: ce135a4ebeee6cfe9a26c93ee0d37825f26113c7 - name: github.com/spf13/cobra - version: 5deb57bbca49eb370538fc295ba4b2988f9f5e09 + version: fcd0c5a1df88f5d6784cb4feead962c3f3d0b66c +- name: github.com/spf13/jwalterweatherman + version: fa7ca7e836cf3a8bb4ebf799f472c12d7e903d66 - name: github.com/spf13/pflag version: 9ff6c6923cfffbcd502984b8e0c80539a94968b7 +- name: github.com/spf13/viper + version: 84f94806c67f59dd7ae87bc5351f7a9c94a4558d - name: github.com/stretchr/testify version: 69483b4bd14f5845b5a1e55bca19e954e827f1d0 subpackages: @@ -81,9 +110,9 @@ imports: - edwards25519 - extra25519 - name: github.com/tendermint/go-common - version: f9e3db037330c8a8d61d3966de8473eaf01154fa -- name: github.com/tendermint/go-config - version: 620dcbbd7d587cf3599dedbf329b64311b0c307a + version: 6af2364fa91ef2f3afc8ba0db33b66d9d3ae006c + subpackages: + - test - name: github.com/tendermint/go-crypto version: 9b95da8fa4187f6799558d89b271dc8ab6485615 - name: github.com/tendermint/go-wire @@ -151,4 +180,6 @@ imports: - stats - tap - transport +- name: gopkg.in/yaml.v2 + version: cd8b52f8269e0feb286dfeef29f8fe4d5b397e0b testImports: [] diff --git a/rpc/tendermint/test/client_test.go b/rpc/tendermint/test/client_test.go index 1164bdd79..2fc8a2d9b 100644 --- a/rpc/tendermint/test/client_test.go +++ b/rpc/tendermint/test/client_test.go @@ -10,6 +10,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + abci "github.com/tendermint/abci/types" rpc "github.com/tendermint/tendermint/rpc/client" "github.com/tendermint/tendermint/rpc/tendermint/core" From 6e662337ffadd85cb635139b95e5cf20b822cf74 Mon Sep 17 00:00:00 2001 From: Rigel Rozanski Date: Mon, 10 Apr 2017 12:59:43 -0400 Subject: [PATCH 204/309] dont export resetPrivValidator --- cmd/tendermint/commands/reset_priv_validator.go | 9 +++++---- glide.lock | 5 +++++ 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/cmd/tendermint/commands/reset_priv_validator.go b/cmd/tendermint/commands/reset_priv_validator.go index c880e8313..a611935bb 100644 --- a/cmd/tendermint/commands/reset_priv_validator.go +++ b/cmd/tendermint/commands/reset_priv_validator.go @@ -36,17 +36,18 @@ func resetAll(cmd *cobra.Command, args []string) { // XXX: this is totally unsafe. // it's only suitable for testnets. func resetPrivValidator(cmd *cobra.Command, args []string) { - ResetPrivValidator(config, log) + resetPrivValidatorLocal(config, log) } // Exported so other CLI tools can use it func ResetAll(c *viper.Viper, l log15.Logger) { - ResetPrivValidator(c, l) - os.RemoveAll(c.GetString("db_dir")) + resetPrivValidatorLocal(c, l) + dataDir := c.GetString("db_dir") + os.RemoveAll(dataDir) l.Notice("Removed all data", "dir", dataDir) } -func ResetPrivValidator(c *viper.Viper, l log15.Logger) { +func resetPrivValidatorLocal(c *viper.Viper, l log15.Logger) { // Get PrivValidator var privValidator *types.PrivValidator diff --git a/glide.lock b/glide.lock index bc4778927..70da9fac1 100644 --- a/glide.lock +++ b/glide.lock @@ -167,6 +167,11 @@ imports: version: d75a52659825e75fff6158388dddc6a5b04f9ba5 subpackages: - unix +- name: golang.org/x/text + version: f4b4367115ec2de254587813edaa901bc1c723a8 + subpackages: + - transform + - unicode/norm - name: google.golang.org/grpc version: cbcceb2942a489498cf22b2f918536e819d33f0a subpackages: From 7448753257e394d02e2886bc45b34a9c281b0e4a Mon Sep 17 00:00:00 2001 From: Rigel Rozanski Date: Wed, 12 Apr 2017 21:23:58 -0400 Subject: [PATCH 205/309] fixing tests --- config/tendermint/config.go | 2 +- config/tendermint_test/config.go | 2 +- rpc/tendermint/test/client_test.go | 102 +++++++++++++++-------------- rpc/tendermint/test/helpers.go | 4 +- 4 files changed, 55 insertions(+), 55 deletions(-) diff --git a/config/tendermint/config.go b/config/tendermint/config.go index 2e8cbb538..bb2846f7f 100644 --- a/config/tendermint/config.go +++ b/config/tendermint/config.go @@ -52,7 +52,7 @@ func GetConfig(rootDir string) *viper.Viper { if err != nil { Exit(Fmt("Could not read config: %v", err)) } - config.WatchConfig() + //config.WatchConfig() // Set defaults or panic if config.IsSet("chain_id") { diff --git a/config/tendermint_test/config.go b/config/tendermint_test/config.go index 846d28c64..5ff8e78f6 100644 --- a/config/tendermint_test/config.go +++ b/config/tendermint_test/config.go @@ -68,7 +68,7 @@ func ResetConfig(localPath string) *viper.Viper { if err != nil { Exit(Fmt("Could not read config: %v", err)) } - config.WatchConfig() + //config.WatchConfig() // Set defaults or panic if config.IsSet("chain_id") { diff --git a/rpc/tendermint/test/client_test.go b/rpc/tendermint/test/client_test.go index 2fc8a2d9b..d6d616f0c 100644 --- a/rpc/tendermint/test/client_test.go +++ b/rpc/tendermint/test/client_test.go @@ -67,8 +67,10 @@ func TestJSONBroadcastTxSync(t *testing.T) { } func testBroadcastTxSync(t *testing.T, client rpc.HTTPClient) { - config.Set("block_size", 0) - defer config.Set("block_size", -1) + // config.Set("block_size", 0) + // defer config.Set("block_size", -1) + mem := node.MempoolReactor().Mempool + initMemSize := mem.Size() tmResult := new(ctypes.TMResult) tx := randBytes(t) _, err := client.Call("broadcast_tx_sync", map[string]interface{}{"tx": tx}, tmResult) @@ -76,8 +78,7 @@ func testBroadcastTxSync(t *testing.T, client rpc.HTTPClient) { res := (*tmResult).(*ctypes.ResultBroadcastTx) require.Equal(t, abci.CodeType_OK, res.Code) - mem := node.MempoolReactor().Mempool - require.Equal(t, 1, mem.Size()) + require.Equal(t, initMemSize+1, mem.Size()) txs := mem.Reap(1) require.EqualValues(t, tx, txs[0]) mem.Flush() @@ -358,51 +359,52 @@ func TestWSDoubleFire(t *testing.T) { }*/ //-------------------------------------------------------------------------------- +//TODO needs to be refactored so we don't use a mutable config but rather update specific values we're interested in // unsafe_set_config -var stringVal = "my string" -var intVal = 987654321 -var boolVal = true - -// don't change these -var testCasesUnsafeSetConfig = [][]string{ - []string{"string", "key1", stringVal}, - []string{"int", "key2", fmt.Sprintf("%v", intVal)}, - []string{"bool", "key3", fmt.Sprintf("%v", boolVal)}, -} - -func TestURIUnsafeSetConfig(t *testing.T) { - for _, testCase := range testCasesUnsafeSetConfig { - tmResult := new(ctypes.TMResult) - _, err := GetURIClient().Call("unsafe_set_config", map[string]interface{}{ - "type": testCase[0], - "key": testCase[1], - "value": testCase[2], - }, tmResult) - require.Nil(t, err) - } - testUnsafeSetConfig(t) -} - -func TestJSONUnsafeSetConfig(t *testing.T) { - for _, testCase := range testCasesUnsafeSetConfig { - tmResult := new(ctypes.TMResult) - _, err := GetJSONClient().Call("unsafe_set_config", - map[string]interface{}{"type": testCase[0], "key": testCase[1], "value": testCase[2]}, - tmResult) - require.Nil(t, err) - } - testUnsafeSetConfig(t) -} - -func testUnsafeSetConfig(t *testing.T) { - require := require.New(t) - s := config.GetString("key1") - require.Equal(stringVal, s) - - i := config.GetInt("key2") - require.Equal(intVal, i) - - b := config.GetBool("key3") - require.Equal(boolVal, b) -} +//var stringVal = "my string" +//var intVal = 987654321 +//var boolVal = true +// +//// don't change these +//var testCasesUnsafeSetConfig = [][]string{ +// []string{"string", "key1", stringVal}, +// []string{"int", "key2", fmt.Sprintf("%v", intVal)}, +// []string{"bool", "key3", fmt.Sprintf("%v", boolVal)}, +//} +// +//func TestURIUnsafeSetConfig(t *testing.T) { +// for _, testCase := range testCasesUnsafeSetConfig { +// tmResult := new(ctypes.TMResult) +// _, err := GetURIClient().Call("unsafe_set_config", map[string]interface{}{ +// "type": testCase[0], +// "key": testCase[1], +// "value": testCase[2], +// }, tmResult) +// require.Nil(t, err) +// } +// testUnsafeSetConfig(t) +//} +// +//func TestJSONUnsafeSetConfig(t *testing.T) { +// for _, testCase := range testCasesUnsafeSetConfig { +// tmResult := new(ctypes.TMResult) +// _, err := GetJSONClient().Call("unsafe_set_config", +// map[string]interface{}{"type": testCase[0], "key": testCase[1], "value": testCase[2]}, +// tmResult) +// require.Nil(t, err) +// } +// testUnsafeSetConfig(t) +//} +// +//func testUnsafeSetConfig(t *testing.T) { +// require := require.New(t) +// s := config.GetString("key1") +// require.Equal(stringVal, s) +// +// i := config.GetInt("key2") +// require.Equal(intVal, i) +// +// b := config.GetBool("key3") +// require.Equal(boolVal, b) +//} diff --git a/rpc/tendermint/test/helpers.go b/rpc/tendermint/test/helpers.go index 8477ef570..f89287670 100644 --- a/rpc/tendermint/test/helpers.go +++ b/rpc/tendermint/test/helpers.go @@ -25,9 +25,7 @@ import ( "github.com/tendermint/tendermint/types" ) -var ( - config *viper.Viper -) +var config *viper.Viper const tmLogLevel = "error" From 7bb638e3b8e1e4e8ac3442dd78dffdc88428cdc1 Mon Sep 17 00:00:00 2001 From: Rigel Rozanski Date: Thu, 13 Apr 2017 16:31:29 -0400 Subject: [PATCH 206/309] fix test_integrations error --- config/tendermint/config.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/config/tendermint/config.go b/config/tendermint/config.go index bb2846f7f..c3424d9a4 100644 --- a/config/tendermint/config.go +++ b/config/tendermint/config.go @@ -48,9 +48,9 @@ func GetConfig(rootDir string) *viper.Viper { config.SetConfigName("config") config.SetConfigType("toml") config.AddConfigPath(rootDir) - err := viper.ReadInConfig() + err := config.ReadInConfig() if err != nil { - Exit(Fmt("Could not read config: %v", err)) + Exit(Fmt("Could not read config from directory %v: %v", rootDir, err)) } //config.WatchConfig() From 5d0c2a1414c976ed29163e50569cfdbcefc4b0db Mon Sep 17 00:00:00 2001 From: Rigel Rozanski Date: Sat, 15 Apr 2017 16:40:52 -0400 Subject: [PATCH 207/309] commands: Run -> RunE --- cmd/tendermint/commands/probe_upnp.go | 8 ++++---- cmd/tendermint/commands/run_node.go | 17 ++++++++++------- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/cmd/tendermint/commands/probe_upnp.go b/cmd/tendermint/commands/probe_upnp.go index eb55d6690..330dcf17d 100644 --- a/cmd/tendermint/commands/probe_upnp.go +++ b/cmd/tendermint/commands/probe_upnp.go @@ -12,14 +12,14 @@ import ( var probeUpnpCmd = &cobra.Command{ Use: "probe_upnp", Short: "Test UPnP functionality", - Run: probeUpnp, + RunE: probeUpnp, } func init() { RootCmd.AddCommand(probeUpnpCmd) } -func probeUpnp(cmd *cobra.Command, args []string) { +func probeUpnp(cmd *cobra.Command, args []string) error { capabilities, err := upnp.Probe() if err != nil { @@ -28,9 +28,9 @@ func probeUpnp(cmd *cobra.Command, args []string) { fmt.Println("Probe success!") jsonBytes, err := json.Marshal(capabilities) if err != nil { - panic(err) + return err } fmt.Println(string(jsonBytes)) } - + return nil } diff --git a/cmd/tendermint/commands/run_node.go b/cmd/tendermint/commands/run_node.go index 5e0fef32c..972ed5215 100644 --- a/cmd/tendermint/commands/run_node.go +++ b/cmd/tendermint/commands/run_node.go @@ -1,6 +1,7 @@ package commands import ( + "fmt" "io/ioutil" "time" @@ -13,9 +14,9 @@ import ( var runNodeCmd = &cobra.Command{ Use: "node", - Short: "Run the tendermint node", + Short: "RunE the tendermint node", PreRun: setConfigFlags, - Run: runNode, + RunE: runNode, } //flags @@ -82,7 +83,7 @@ func setConfigFlags(cmd *cobra.Command, args []string) { // should import github.com/tendermint/tendermint/node and implement // their own run_node to call node.NewNode (instead of node.NewNodeDefault) // with their custom priv validator and/or custom proxy.ClientCreator -func runNode(cmd *cobra.Command, args []string) { +func runNode(cmd *cobra.Command, args []string) error { // Wait until the genesis doc becomes available // This is for Mintnet compatibility. @@ -98,14 +99,14 @@ func runNode(cmd *cobra.Command, args []string) { } jsonBlob, err := ioutil.ReadFile(genDocFile) if err != nil { - Exit(Fmt("Couldn't read GenesisDoc file: %v", err)) + return fmt.Errorf("Couldn't read GenesisDoc file: %v", err) } genDoc, err := types.GenesisDocFromJSON(jsonBlob) if err != nil { - Exit(Fmt("Error reading GenesisDoc: %v", err)) + return fmt.Errorf("Error reading GenesisDoc: %v", err) } if genDoc.ChainID == "" { - Exit(Fmt("Genesis doc %v must include non-empty chain_id", genDocFile)) + return fmt.Errorf("Genesis doc %v must include non-empty chain_id", genDocFile) } config.Set("chain_id", genDoc.ChainID) } @@ -114,11 +115,13 @@ func runNode(cmd *cobra.Command, args []string) { // Create & start node n := node.NewNodeDefault(config) if _, err := n.Start(); err != nil { - Exit(Fmt("Failed to start node: %v", err)) + return fmt.Errorf("Failed to start node: %v", err) } else { log.Notice("Started node", "nodeInfo", n.Switch().NodeInfo()) } // Trap signal, run forever. n.RunForever() + + return nil } From 72c4be35e8bf2172dffb7eedd871903ffd1a8f89 Mon Sep 17 00:00:00 2001 From: rigel rozanski Date: Tue, 18 Apr 2017 03:19:15 -0400 Subject: [PATCH 208/309] tiny fix --- cmd/tendermint/commands/run_node.go | 2 +- rpc/tendermint/test/client_test.go | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/cmd/tendermint/commands/run_node.go b/cmd/tendermint/commands/run_node.go index 972ed5215..a4e4e69dd 100644 --- a/cmd/tendermint/commands/run_node.go +++ b/cmd/tendermint/commands/run_node.go @@ -14,7 +14,7 @@ import ( var runNodeCmd = &cobra.Command{ Use: "node", - Short: "RunE the tendermint node", + Short: "Run the tendermint node", PreRun: setConfigFlags, RunE: runNode, } diff --git a/rpc/tendermint/test/client_test.go b/rpc/tendermint/test/client_test.go index d6d616f0c..11ee61a56 100644 --- a/rpc/tendermint/test/client_test.go +++ b/rpc/tendermint/test/client_test.go @@ -67,8 +67,6 @@ func TestJSONBroadcastTxSync(t *testing.T) { } func testBroadcastTxSync(t *testing.T, client rpc.HTTPClient) { - // config.Set("block_size", 0) - // defer config.Set("block_size", -1) mem := node.MempoolReactor().Mempool initMemSize := mem.Size() tmResult := new(ctypes.TMResult) From fcf78a5da7cfce36d34156c464031f69f6af3f2c Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Tue, 25 Apr 2017 14:50:20 -0400 Subject: [PATCH 209/309] cleanup go-config/viper and some unnamed imports --- blockchain/reactor.go | 1 - cmd/tendermint/commands/root.go | 1 - cmd/tendermint/commands/run_node.go | 8 +-- config/tendermint/config.go | 18 +++---- config/tendermint_test/config.go | 2 - consensus/byzantine_test.go | 2 - consensus/common_test.go | 1 - consensus/replay.go | 19 ++++--- consensus/replay_file.go | 15 +++--- consensus/replay_test.go | 1 - consensus/state.go | 83 ++++++++++++++--------------- glide.lock | 18 +++---- glide.yaml | 14 +---- mempool/mempool.go | 1 - mempool/reactor.go | 1 - node/node.go | 1 - p2p/config.go | 4 +- p2p/switch.go | 11 ++-- p2p/switch_test.go | 9 ++-- proxy/app_conn_test.go | 22 ++++---- proxy/multi_app_conn.go | 1 - rpc/tendermint/core/pipe.go | 1 - rpc/tendermint/test/helpers.go | 1 - state/errors.go | 12 ++--- state/execution.go | 16 +++--- state/state.go | 17 +++--- test/test_libs.sh | 4 +- 27 files changed, 124 insertions(+), 160 deletions(-) diff --git a/blockchain/reactor.go b/blockchain/reactor.go index f45975e00..1ea5650ed 100644 --- a/blockchain/reactor.go +++ b/blockchain/reactor.go @@ -8,7 +8,6 @@ import ( "github.com/spf13/viper" - cfg "github.com/tendermint/go-config" "github.com/tendermint/go-wire" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/proxy" diff --git a/cmd/tendermint/commands/root.go b/cmd/tendermint/commands/root.go index 78d197289..de5b71bd1 100644 --- a/cmd/tendermint/commands/root.go +++ b/cmd/tendermint/commands/root.go @@ -2,7 +2,6 @@ package commands import ( "github.com/spf13/cobra" - "github.com/spf13/viper" tmcfg "github.com/tendermint/tendermint/config/tendermint" "github.com/tendermint/tmlibs/logger" diff --git a/cmd/tendermint/commands/run_node.go b/cmd/tendermint/commands/run_node.go index a4e4e69dd..b2b23af5c 100644 --- a/cmd/tendermint/commands/run_node.go +++ b/cmd/tendermint/commands/run_node.go @@ -7,9 +7,9 @@ import ( "github.com/spf13/cobra" - . "github.com/tendermint/tmlibs/common" "github.com/tendermint/tendermint/node" "github.com/tendermint/tendermint/types" + cmn "github.com/tendermint/tmlibs/common" ) var runNodeCmd = &cobra.Command{ @@ -90,11 +90,11 @@ func runNode(cmd *cobra.Command, args []string) error { // TODO: If Mintnet gets deprecated or genesis_file is // always available, remove. genDocFile := config.GetString("genesis_file") - if !FileExists(genDocFile) { - log.Notice(Fmt("Waiting for genesis file %v...", genDocFile)) + if !cmn.FileExists(genDocFile) { + log.Notice(cmn.Fmt("Waiting for genesis file %v...", genDocFile)) for { time.Sleep(time.Second) - if !FileExists(genDocFile) { + if !cmn.FileExists(genDocFile) { continue } jsonBlob, err := ioutil.ReadFile(genDocFile) diff --git a/config/tendermint/config.go b/config/tendermint/config.go index c3424d9a4..9011e0154 100644 --- a/config/tendermint/config.go +++ b/config/tendermint/config.go @@ -6,9 +6,7 @@ import ( "strings" "github.com/spf13/viper" - - cfg "github.com/tendermint/go-config" - . "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tmlibs/common" ) func getTMRoot(rootDir string) string { @@ -27,16 +25,16 @@ func getTMRoot(rootDir string) string { func initTMRoot(rootDir string) { rootDir = getTMRoot(rootDir) - EnsureDir(rootDir, 0700) - EnsureDir(rootDir+"/data", 0700) + cmn.EnsureDir(rootDir, 0700) + cmn.EnsureDir(rootDir+"/data", 0700) configFilePath := path.Join(rootDir, "config.toml") // Write default config file if missing. - if !FileExists(configFilePath) { + if !cmn.FileExists(configFilePath) { // Ask user for moniker // moniker := cfg.Prompt("Type hostname: ", "anonymous") - MustWriteFile(configFilePath, []byte(defaultConfig("anonymous")), 0644) + cmn.MustWriteFile(configFilePath, []byte(defaultConfig("anonymous")), 0644) } } @@ -50,16 +48,16 @@ func GetConfig(rootDir string) *viper.Viper { config.AddConfigPath(rootDir) err := config.ReadInConfig() if err != nil { - Exit(Fmt("Could not read config from directory %v: %v", rootDir, err)) + cmn.Exit(cmn.Fmt("Could not read config from directory %v: %v", rootDir, err)) } //config.WatchConfig() // Set defaults or panic if config.IsSet("chain_id") { - Exit("Cannot set 'chain_id' via config.toml") + cmn.Exit("Cannot set 'chain_id' via config.toml") } if config.IsSet("revision_file") { - Exit("Cannot set 'revision_file' via config.toml. It must match what's in the Makefile") + cmn.Exit("Cannot set 'revision_file' via config.toml. It must match what's in the Makefile") } //mapConfig.SetRequired("chain_id") // blows up if you try to use it before setting. config.SetDefault("genesis_file", rootDir+"/genesis.json") diff --git a/config/tendermint_test/config.go b/config/tendermint_test/config.go index 5ff8e78f6..1a87d5261 100644 --- a/config/tendermint_test/config.go +++ b/config/tendermint_test/config.go @@ -10,7 +10,6 @@ import ( "github.com/spf13/viper" - cfg "github.com/tendermint/go-config" . "github.com/tendermint/tmlibs/common" "github.com/tendermint/tmlibs/logger" ) @@ -46,7 +45,6 @@ func initTMRoot(rootDir string) { // Write default config file if missing. if !FileExists(configFilePath) { // Ask user for moniker - // moniker := cfg.Prompt("Type hostname: ", "anonymous") MustWriteFile(configFilePath, []byte(defaultConfig("anonymous")), 0644) } if !FileExists(genesisFilePath) { diff --git a/consensus/byzantine_test.go b/consensus/byzantine_test.go index d4cda4046..b9edf4635 100644 --- a/consensus/byzantine_test.go +++ b/consensus/byzantine_test.go @@ -8,8 +8,6 @@ import ( "github.com/spf13/viper" "github.com/tendermint/tendermint/config/tendermint_test" - - cfg "github.com/tendermint/go-config" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/types" . "github.com/tendermint/tmlibs/common" diff --git a/consensus/common_test.go b/consensus/common_test.go index 7acb54ad7..469fc9c6b 100644 --- a/consensus/common_test.go +++ b/consensus/common_test.go @@ -15,7 +15,6 @@ import ( abcicli "github.com/tendermint/abci/client" abci "github.com/tendermint/abci/types" - cfg "github.com/tendermint/go-config" bc "github.com/tendermint/tendermint/blockchain" "github.com/tendermint/tendermint/config/tendermint_test" mempl "github.com/tendermint/tendermint/mempool" diff --git a/consensus/replay.go b/consensus/replay.go index acbe44098..5bc0c2611 100644 --- a/consensus/replay.go +++ b/consensus/replay.go @@ -13,10 +13,9 @@ import ( "github.com/spf13/viper" abci "github.com/tendermint/abci/types" - cfg "github.com/tendermint/go-config" "github.com/tendermint/go-wire" auto "github.com/tendermint/tmlibs/autofile" - . "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tmlibs/common" "github.com/tendermint/tendermint/proxy" sm "github.com/tendermint/tendermint/state" @@ -110,7 +109,7 @@ func (cs *ConsensusState) catchupReplay(csHeight int) error { gr.Close() } if found { - return errors.New(Fmt("WAL should not contain #ENDHEIGHT %d.", csHeight)) + return errors.New(cmn.Fmt("WAL should not contain #ENDHEIGHT %d.", csHeight)) } // Search for last height marker @@ -145,7 +144,7 @@ func (cs *ConsensusState) catchupReplay(csHeight int) error { } // TODO (0.10.0): uncomment - // return errors.New(Fmt("Cannot replay height %d. WAL does not contain #ENDHEIGHT for %d.", csHeight, csHeight-1)) + // return errors.New(cmn.Fmt("Cannot replay height %d. WAL does not contain #ENDHEIGHT for %d.", csHeight, csHeight-1)) } log.Notice("Catchup by replaying consensus messages", "height", csHeight) @@ -223,7 +222,7 @@ func (h *Handshaker) Handshake(proxyApp proxy.AppConns) error { // handshake is done via info request on the query conn res, err := proxyApp.Query().InfoSync() if err != nil { - return errors.New(Fmt("Error calling Info: %v", err)) + return errors.New(cmn.Fmt("Error calling Info: %v", err)) } blockHeight := int(res.LastBlockHeight) // XXX: beware overflow @@ -240,7 +239,7 @@ func (h *Handshaker) Handshake(proxyApp proxy.AppConns) error { return nil } else if err != nil { - return errors.New(Fmt("Error on replay: %v", err)) + return errors.New(cmn.Fmt("Error on replay: %v", err)) } log.Notice("Completed ABCI Handshake - Tendermint and App are synced", "appHeight", blockHeight, "appHash", appHash) @@ -268,11 +267,11 @@ func (h *Handshaker) ReplayBlocks(appHash []byte, appBlockHeight int, proxyApp p } else if storeBlockHeight < stateBlockHeight { // the state should never be ahead of the store (this is under tendermint's control) - PanicSanity(Fmt("StateBlockHeight (%d) > StoreBlockHeight (%d)", stateBlockHeight, storeBlockHeight)) + cmn.PanicSanity(cmn.Fmt("StateBlockHeight (%d) > StoreBlockHeight (%d)", stateBlockHeight, storeBlockHeight)) } else if storeBlockHeight > stateBlockHeight+1 { // store should be at most one ahead of the state (this is under tendermint's control) - PanicSanity(Fmt("StoreBlockHeight (%d) > StateBlockHeight + 1 (%d)", storeBlockHeight, stateBlockHeight+1)) + cmn.PanicSanity(cmn.Fmt("StoreBlockHeight (%d) > StateBlockHeight + 1 (%d)", storeBlockHeight, stateBlockHeight+1)) } // Now either store is equal to state, or one ahead. @@ -315,7 +314,7 @@ func (h *Handshaker) ReplayBlocks(appHash []byte, appBlockHeight int, proxyApp p } - PanicSanity("Should never happen") + cmn.PanicSanity("Should never happen") return nil, nil } @@ -370,7 +369,7 @@ func (h *Handshaker) replayBlock(height int, proxyApp proxy.AppConnConsensus) ([ func (h *Handshaker) checkAppHash(appHash []byte) error { if !bytes.Equal(h.state.AppHash, appHash) { - panic(errors.New(Fmt("Tendermint state.AppHash does not match AppHash after replay. Got %X, expected %X", appHash, h.state.AppHash)).Error()) + panic(errors.New(cmn.Fmt("Tendermint state.AppHash does not match AppHash after replay. Got %X, expected %X", appHash, h.state.AppHash)).Error()) return nil } return nil diff --git a/consensus/replay_file.go b/consensus/replay_file.go index e5056ef0d..1d2a91f31 100644 --- a/consensus/replay_file.go +++ b/consensus/replay_file.go @@ -10,13 +10,12 @@ import ( "github.com/spf13/viper" - cfg "github.com/tendermint/go-config" bc "github.com/tendermint/tendermint/blockchain" mempl "github.com/tendermint/tendermint/mempool" "github.com/tendermint/tendermint/proxy" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" - . "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tmlibs/common" dbm "github.com/tendermint/tmlibs/db" ) @@ -27,7 +26,7 @@ func RunReplayFile(config *viper.Viper, walFile string, console bool) { consensusState := newConsensusStateForReplay(config) if err := consensusState.ReplayFile(walFile, console); err != nil { - Exit(Fmt("Error during consensus replay: %v", err)) + cmn.Exit(cmn.Fmt("Error during consensus replay: %v", err)) } } @@ -116,7 +115,7 @@ func (pb *playback) replayReset(count int, newStepCh chan interface{}) error { pb.fp = fp pb.scanner = bufio.NewScanner(fp) count = pb.count - count - log.Notice(Fmt("Reseting from %d to %d", pb.count, count)) + log.Notice(cmn.Fmt("Reseting from %d to %d", pb.count, count)) pb.count = 0 pb.cs = newCS for i := 0; pb.scanner.Scan() && i < count; i++ { @@ -151,9 +150,9 @@ func (pb *playback) replayConsoleLoop() int { bufReader := bufio.NewReader(os.Stdin) line, more, err := bufReader.ReadLine() if more { - Exit("input is too long") + cmn.Exit("input is too long") } else if err != nil { - Exit(err.Error()) + cmn.Exit(err.Error()) } tokens := strings.Split(string(line), " ") @@ -251,7 +250,7 @@ func newConsensusStateForReplay(config *viper.Viper) *ConsensusState { proxyApp := proxy.NewAppConns(config, proxy.DefaultClientCreator(config), NewHandshaker(config, state, blockStore)) _, err := proxyApp.Start() if err != nil { - Exit(Fmt("Error starting proxy app conns: %v", err)) + cmn.Exit(cmn.Fmt("Error starting proxy app conns: %v", err)) } // add the chainid to the global config @@ -260,7 +259,7 @@ func newConsensusStateForReplay(config *viper.Viper) *ConsensusState { // Make event switch eventSwitch := types.NewEventSwitch() if _, err := eventSwitch.Start(); err != nil { - Exit(Fmt("Failed to start event switch: %v", err)) + cmn.Exit(cmn.Fmt("Failed to start event switch: %v", err)) } mempool := mempl.NewMempool(config, proxyApp.Mempool()) diff --git a/consensus/replay_test.go b/consensus/replay_test.go index b78d5915f..e486af83e 100644 --- a/consensus/replay_test.go +++ b/consensus/replay_test.go @@ -15,7 +15,6 @@ import ( "github.com/spf13/viper" "github.com/tendermint/abci/example/dummy" - cfg "github.com/tendermint/go-config" "github.com/tendermint/go-crypto" "github.com/tendermint/go-wire" "github.com/tendermint/tendermint/config/tendermint_test" diff --git a/consensus/state.go b/consensus/state.go index 06c20db2a..28836a079 100644 --- a/consensus/state.go +++ b/consensus/state.go @@ -12,12 +12,11 @@ import ( "github.com/ebuchman/fail-test" "github.com/spf13/viper" - cfg "github.com/tendermint/go-config" "github.com/tendermint/go-wire" "github.com/tendermint/tendermint/proxy" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" - . "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tmlibs/common" ) //----------------------------------------------------------------------------- @@ -223,7 +222,7 @@ type PrivValidator interface { // Tracks consensus state across block heights and rounds. type ConsensusState struct { - BaseService + cmn.BaseService config *viper.Viper proxyAppConn proxy.AppConnConsensus @@ -277,7 +276,7 @@ func NewConsensusState(config *viper.Viper, state *sm.State, proxyAppConn proxy. // Don't call scheduleRound0 yet. // We do that upon Start(). cs.reconstructLastCommit(state) - cs.BaseService = *NewBaseService(log, "ConsensusState", cs) + cs.BaseService = *cmn.NewBaseService(log, "ConsensusState", cs) return cs } @@ -291,7 +290,7 @@ func (cs *ConsensusState) SetEventSwitch(evsw types.EventSwitch) { func (cs *ConsensusState) String() string { // better not to access shared variables - return Fmt("ConsensusState") //(H:%v R:%v S:%v", cs.Height, cs.Round, cs.Step) + return cmn.Fmt("ConsensusState") //(H:%v R:%v S:%v", cs.Height, cs.Round, cs.Step) } func (cs *ConsensusState) GetState() *sm.State { @@ -399,7 +398,7 @@ func (cs *ConsensusState) Wait() { // Open file to log all consensus messages and timeouts for deterministic accountability func (cs *ConsensusState) OpenWAL(walFile string) (err error) { - err = EnsureDir(path.Dir(walFile), 0700) + err = cmn.EnsureDir(path.Dir(walFile), 0700) if err != nil { log.Error("Error ensuring ConsensusState wal dir", "error", err.Error()) return err @@ -520,11 +519,11 @@ func (cs *ConsensusState) reconstructLastCommit(state *sm.State) { } added, err := lastPrecommits.AddVote(precommit) if !added || err != nil { - PanicCrisis(Fmt("Failed to reconstruct LastCommit: %v", err)) + cmn.PanicCrisis(cmn.Fmt("Failed to reconstruct LastCommit: %v", err)) } } if !lastPrecommits.HasTwoThirdsMajority() { - PanicSanity("Failed to reconstruct LastCommit: Does not have +2/3 maj") + cmn.PanicSanity("Failed to reconstruct LastCommit: Does not have +2/3 maj") } cs.LastCommit = lastPrecommits } @@ -533,13 +532,13 @@ func (cs *ConsensusState) reconstructLastCommit(state *sm.State) { // The round becomes 0 and cs.Step becomes RoundStepNewHeight. func (cs *ConsensusState) updateToState(state *sm.State) { if cs.CommitRound > -1 && 0 < cs.Height && cs.Height != state.LastBlockHeight { - PanicSanity(Fmt("updateToState() expected state height of %v but found %v", + cmn.PanicSanity(cmn.Fmt("updateToState() expected state height of %v but found %v", cs.Height, state.LastBlockHeight)) } if cs.state != nil && cs.state.LastBlockHeight+1 != cs.Height { // This might happen when someone else is mutating cs.state. // Someone forgot to pass in state.Copy() somewhere?! - PanicSanity(Fmt("Inconsistent cs.state.LastBlockHeight+1 %v vs cs.Height %v", + cmn.PanicSanity(cmn.Fmt("Inconsistent cs.state.LastBlockHeight+1 %v vs cs.Height %v", cs.state.LastBlockHeight+1, cs.Height)) } @@ -556,7 +555,7 @@ func (cs *ConsensusState) updateToState(state *sm.State) { lastPrecommits := (*types.VoteSet)(nil) if cs.CommitRound > -1 && cs.Votes != nil { if !cs.Votes.Precommits(cs.CommitRound).HasTwoThirdsMajority() { - PanicSanity("updateToState(state) called but last Precommit round didn't have +2/3") + cmn.PanicSanity("updateToState(state) called but last Precommit round didn't have +2/3") } lastPrecommits = cs.Votes.Precommits(cs.CommitRound) } @@ -724,7 +723,7 @@ func (cs *ConsensusState) handleTimeout(ti timeoutInfo, rs RoundState) { types.FireEventTimeoutWait(cs.evsw, cs.RoundStateEvent()) cs.enterNewRound(ti.Height, ti.Round+1) default: - panic(Fmt("Invalid timeout step: %v", ti.Step)) + panic(cmn.Fmt("Invalid timeout step: %v", ti.Step)) } } @@ -739,7 +738,7 @@ func (cs *ConsensusState) handleTimeout(ti timeoutInfo, rs RoundState) { // NOTE: cs.StartTime was already set for height. func (cs *ConsensusState) enterNewRound(height int, round int) { if cs.Height != height || round < cs.Round || (cs.Round == round && cs.Step != RoundStepNewHeight) { - log.Debug(Fmt("enterNewRound(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + log.Debug(cmn.Fmt("enterNewRound(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) return } @@ -747,7 +746,7 @@ func (cs *ConsensusState) enterNewRound(height int, round int) { log.Warn("Need to set a buffer and log.Warn() here for sanity.", "startTime", cs.StartTime, "now", now) } - log.Notice(Fmt("enterNewRound(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + log.Notice(cmn.Fmt("enterNewRound(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) // Increment validators if necessary validators := cs.Validators @@ -781,10 +780,10 @@ func (cs *ConsensusState) enterNewRound(height int, round int) { // Enter: from NewRound(height,round). func (cs *ConsensusState) enterPropose(height int, round int) { if cs.Height != height || round < cs.Round || (cs.Round == round && RoundStepPropose <= cs.Step) { - log.Debug(Fmt("enterPropose(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + log.Debug(cmn.Fmt("enterPropose(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) return } - log.Info(Fmt("enterPropose(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + log.Info(cmn.Fmt("enterPropose(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) defer func() { // Done enterPropose: @@ -851,7 +850,7 @@ func (cs *ConsensusState) defaultDecideProposal(height, round int) { cs.sendInternalMessage(msgInfo{&BlockPartMessage{cs.Height, cs.Round, part}, ""}) } log.Info("Signed proposal", "height", height, "round", round, "proposal", proposal) - log.Debug(Fmt("Signed proposal block: %v", block)) + log.Debug(cmn.Fmt("Signed proposal block: %v", block)) } else { if !cs.replayMode { log.Warn("enterPropose: Error signing proposal", "height", height, "round", round, "error", err) @@ -907,7 +906,7 @@ func (cs *ConsensusState) createProposalBlock() (block *types.Block, blockParts // Otherwise vote nil. func (cs *ConsensusState) enterPrevote(height int, round int) { if cs.Height != height || round < cs.Round || (cs.Round == round && RoundStepPrevote <= cs.Step) { - log.Debug(Fmt("enterPrevote(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + log.Debug(cmn.Fmt("enterPrevote(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) return } @@ -925,7 +924,7 @@ func (cs *ConsensusState) enterPrevote(height int, round int) { // TODO: catchup event? } - log.Info(Fmt("enterPrevote(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + log.Info(cmn.Fmt("enterPrevote(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) // Sign and broadcast vote as necessary cs.doPrevote(height, round) @@ -968,13 +967,13 @@ func (cs *ConsensusState) defaultDoPrevote(height int, round int) { // Enter: any +2/3 prevotes at next round. func (cs *ConsensusState) enterPrevoteWait(height int, round int) { if cs.Height != height || round < cs.Round || (cs.Round == round && RoundStepPrevoteWait <= cs.Step) { - log.Debug(Fmt("enterPrevoteWait(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + log.Debug(cmn.Fmt("enterPrevoteWait(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) return } if !cs.Votes.Prevotes(round).HasTwoThirdsAny() { - PanicSanity(Fmt("enterPrevoteWait(%v/%v), but Prevotes does not have any +2/3 votes", height, round)) + cmn.PanicSanity(cmn.Fmt("enterPrevoteWait(%v/%v), but Prevotes does not have any +2/3 votes", height, round)) } - log.Info(Fmt("enterPrevoteWait(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + log.Info(cmn.Fmt("enterPrevoteWait(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) defer func() { // Done enterPrevoteWait: @@ -994,11 +993,11 @@ func (cs *ConsensusState) enterPrevoteWait(height int, round int) { // else, precommit nil otherwise. func (cs *ConsensusState) enterPrecommit(height int, round int) { if cs.Height != height || round < cs.Round || (cs.Round == round && RoundStepPrecommit <= cs.Step) { - log.Debug(Fmt("enterPrecommit(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + log.Debug(cmn.Fmt("enterPrecommit(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) return } - log.Info(Fmt("enterPrecommit(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + log.Info(cmn.Fmt("enterPrecommit(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) defer func() { // Done enterPrecommit: @@ -1025,7 +1024,7 @@ func (cs *ConsensusState) enterPrecommit(height int, round int) { // the latest POLRound should be this round polRound, _ := cs.Votes.POLInfo() if polRound < round { - PanicSanity(Fmt("This POLRound should be %v but got %", round, polRound)) + cmn.PanicSanity(cmn.Fmt("This POLRound should be %v but got %", round, polRound)) } // +2/3 prevoted nil. Unlock and precommit nil. @@ -1059,7 +1058,7 @@ func (cs *ConsensusState) enterPrecommit(height int, round int) { log.Notice("enterPrecommit: +2/3 prevoted proposal block. Locking", "hash", blockID.Hash) // Validate the block. if err := cs.state.ValidateBlock(cs.ProposalBlock); err != nil { - PanicConsensus(Fmt("enterPrecommit: +2/3 prevoted for an invalid block: %v", err)) + cmn.PanicConsensus(cmn.Fmt("enterPrecommit: +2/3 prevoted for an invalid block: %v", err)) } cs.LockedRound = round cs.LockedBlock = cs.ProposalBlock @@ -1088,13 +1087,13 @@ func (cs *ConsensusState) enterPrecommit(height int, round int) { // Enter: any +2/3 precommits for next round. func (cs *ConsensusState) enterPrecommitWait(height int, round int) { if cs.Height != height || round < cs.Round || (cs.Round == round && RoundStepPrecommitWait <= cs.Step) { - log.Debug(Fmt("enterPrecommitWait(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + log.Debug(cmn.Fmt("enterPrecommitWait(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) return } if !cs.Votes.Precommits(round).HasTwoThirdsAny() { - PanicSanity(Fmt("enterPrecommitWait(%v/%v), but Precommits does not have any +2/3 votes", height, round)) + cmn.PanicSanity(cmn.Fmt("enterPrecommitWait(%v/%v), but Precommits does not have any +2/3 votes", height, round)) } - log.Info(Fmt("enterPrecommitWait(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + log.Info(cmn.Fmt("enterPrecommitWait(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) defer func() { // Done enterPrecommitWait: @@ -1110,10 +1109,10 @@ func (cs *ConsensusState) enterPrecommitWait(height int, round int) { // Enter: +2/3 precommits for block func (cs *ConsensusState) enterCommit(height int, commitRound int) { if cs.Height != height || RoundStepCommit <= cs.Step { - log.Debug(Fmt("enterCommit(%v/%v): Invalid args. Current step: %v/%v/%v", height, commitRound, cs.Height, cs.Round, cs.Step)) + log.Debug(cmn.Fmt("enterCommit(%v/%v): Invalid args. Current step: %v/%v/%v", height, commitRound, cs.Height, cs.Round, cs.Step)) return } - log.Info(Fmt("enterCommit(%v/%v). Current: %v/%v/%v", height, commitRound, cs.Height, cs.Round, cs.Step)) + log.Info(cmn.Fmt("enterCommit(%v/%v). Current: %v/%v/%v", height, commitRound, cs.Height, cs.Round, cs.Step)) defer func() { // Done enterCommit: @@ -1129,7 +1128,7 @@ func (cs *ConsensusState) enterCommit(height int, commitRound int) { blockID, ok := cs.Votes.Precommits(commitRound).TwoThirdsMajority() if !ok { - PanicSanity("RunActionCommit() expects +2/3 precommits") + cmn.PanicSanity("RunActionCommit() expects +2/3 precommits") } // The Locked* fields no longer matter. @@ -1156,7 +1155,7 @@ func (cs *ConsensusState) enterCommit(height int, commitRound int) { // If we have the block AND +2/3 commits for it, finalize. func (cs *ConsensusState) tryFinalizeCommit(height int) { if cs.Height != height { - PanicSanity(Fmt("tryFinalizeCommit() cs.Height: %v vs height: %v", cs.Height, height)) + cmn.PanicSanity(cmn.Fmt("tryFinalizeCommit() cs.Height: %v vs height: %v", cs.Height, height)) } blockID, ok := cs.Votes.Precommits(cs.CommitRound).TwoThirdsMajority() @@ -1177,7 +1176,7 @@ func (cs *ConsensusState) tryFinalizeCommit(height int) { // Increment height and goto RoundStepNewHeight func (cs *ConsensusState) finalizeCommit(height int) { if cs.Height != height || cs.Step != RoundStepCommit { - log.Debug(Fmt("finalizeCommit(%v): Invalid args. Current step: %v/%v/%v", height, cs.Height, cs.Round, cs.Step)) + log.Debug(cmn.Fmt("finalizeCommit(%v): Invalid args. Current step: %v/%v/%v", height, cs.Height, cs.Round, cs.Step)) return } @@ -1185,21 +1184,21 @@ func (cs *ConsensusState) finalizeCommit(height int) { block, blockParts := cs.ProposalBlock, cs.ProposalBlockParts if !ok { - PanicSanity(Fmt("Cannot finalizeCommit, commit does not have two thirds majority")) + cmn.PanicSanity(cmn.Fmt("Cannot finalizeCommit, commit does not have two thirds majority")) } if !blockParts.HasHeader(blockID.PartsHeader) { - PanicSanity(Fmt("Expected ProposalBlockParts header to be commit header")) + cmn.PanicSanity(cmn.Fmt("Expected ProposalBlockParts header to be commit header")) } if !block.HashesTo(blockID.Hash) { - PanicSanity(Fmt("Cannot finalizeCommit, ProposalBlock does not hash to commit hash")) + cmn.PanicSanity(cmn.Fmt("Cannot finalizeCommit, ProposalBlock does not hash to commit hash")) } if err := cs.state.ValidateBlock(block); err != nil { - PanicConsensus(Fmt("+2/3 committed an invalid block: %v", err)) + cmn.PanicConsensus(cmn.Fmt("+2/3 committed an invalid block: %v", err)) } - log.Notice(Fmt("Finalizing commit of block with %d txs", block.NumTxs), + log.Notice(cmn.Fmt("Finalizing commit of block with %d txs", block.NumTxs), "height", block.Height, "hash", block.Hash(), "root", block.AppHash) - log.Info(Fmt("%v", block)) + log.Info(cmn.Fmt("%v", block)) fail.Fail() // XXX @@ -1394,7 +1393,7 @@ func (cs *ConsensusState) addVote(vote *types.Vote, peerKey string) (added bool, } added, err = cs.LastCommit.AddVote(vote) if added { - log.Info(Fmt("Added to lastPrecommits: %v", cs.LastCommit.StringShort())) + log.Info(cmn.Fmt("Added to lastPrecommits: %v", cs.LastCommit.StringShort())) types.FireEventVote(cs.evsw, types.EventDataVote{vote}) // if we can skip timeoutCommit and have all the votes now, @@ -1475,7 +1474,7 @@ func (cs *ConsensusState) addVote(vote *types.Vote, peerKey string) (added bool, cs.enterPrecommitWait(height, vote.Round) } default: - PanicSanity(Fmt("Unexpected vote type %X", vote.Type)) // Should not happen. + cmn.PanicSanity(cmn.Fmt("Unexpected vote type %X", vote.Type)) // Should not happen. } } // Either duplicate, or error upon cs.Votes.AddByIndex() diff --git a/glide.lock b/glide.lock index 70da9fac1..7720c946b 100644 --- a/glide.lock +++ b/glide.lock @@ -1,12 +1,10 @@ -hash: 9096fc4e29eff8fac3708ed30deacac67b7a181f0192b177006105dccdb16686 -updated: 2017-04-21T18:39:37.154946943-04:00 +hash: 6f8962f6ca0e25b8e43bc6e496bd46c9ff3a79dcf789578efeeaee2fffc39c6e +updated: 2017-04-25T14:48:36.999444976-04:00 imports: - name: github.com/btcsuite/btcd version: 583684b21bfbde9b5fc4403916fd7c807feb0289 subpackages: - btcec -- name: github.com/BurntSushi/toml - version: 99064174e013895bbd9b025c31100bd1d9b590ca - name: github.com/davecgh/go-spew version: 6d212800a42e8ab5c146b8ace3490ee17e5225f9 subpackages: @@ -55,7 +53,7 @@ imports: - name: github.com/pelletier/go-buffruneio version: c37440a7cf42ac63b919c752ca73a85067e05992 - name: github.com/pelletier/go-toml - version: fe206efb84b2bc8e8cfafe6b4c1826622be969e3 + version: 13d49d4606eb801b8f01ae542b4afc4c6ee3d84a - name: github.com/pkg/errors version: 645ef00459ed84a119197bfb8d8205042c6df63d - name: github.com/pmezard/go-difflib @@ -67,7 +65,7 @@ imports: subpackages: - mem - name: github.com/spf13/cast - version: ce135a4ebeee6cfe9a26c93ee0d37825f26113c7 + version: acbeb36b902d72a7a4c18e8f3241075e7ab763e4 - name: github.com/spf13/cobra version: fcd0c5a1df88f5d6784cb4feead962c3f3d0b66c - name: github.com/spf13/jwalterweatherman @@ -75,7 +73,7 @@ imports: - name: github.com/spf13/pflag version: 9ff6c6923cfffbcd502984b8e0c80539a94968b7 - name: github.com/spf13/viper - version: 84f94806c67f59dd7ae87bc5351f7a9c94a4558d + version: 5d46e70da8c0b6f812e0b170b7a985753b5c63cb - name: github.com/stretchr/testify version: 69483b4bd14f5845b5a1e55bca19e954e827f1d0 subpackages: @@ -97,7 +95,7 @@ imports: - leveldb/table - leveldb/util - name: github.com/tendermint/abci - version: be61e273cebeb64866a83c578f92b22cf2169cdd + version: c709d3cc857929a8dd36a90da3640122d7e75770 subpackages: - client - example/counter @@ -109,10 +107,6 @@ imports: subpackages: - edwards25519 - extra25519 -- name: github.com/tendermint/go-common - version: 6af2364fa91ef2f3afc8ba0db33b66d9d3ae006c - subpackages: - - test - name: github.com/tendermint/go-crypto version: 9b95da8fa4187f6799558d89b271dc8ab6485615 - name: github.com/tendermint/go-wire diff --git a/glide.yaml b/glide.yaml index e4c2e4138..f06a16b3b 100644 --- a/glide.yaml +++ b/glide.yaml @@ -10,6 +10,7 @@ import: - package: github.com/gorilla/websocket - package: github.com/pkg/errors - package: github.com/spf13/cobra +- package: github.com/spf13/viper - package: github.com/stretchr/testify subpackages: - require @@ -19,8 +20,6 @@ import: - client - example/dummy - types -- package: github.com/tendermint/go-config - version: develop - package: github.com/tendermint/go-crypto version: develop - package: github.com/tendermint/go-wire @@ -39,17 +38,6 @@ import: - flowrate - logger - merkle -- package: github.com/gogo/protobuf - version: ^0.3 - subpackages: - - proto -- package: github.com/gorilla/websocket - version: ^1.1.0 -- package: github.com/spf13/cobra -- package: github.com/spf13/viper -- package: github.com/spf13/pflag -- package: github.com/pkg/errors - version: ^0.8.0 - package: golang.org/x/crypto subpackages: - nacl/box diff --git a/mempool/mempool.go b/mempool/mempool.go index 086a99e32..621f0931e 100644 --- a/mempool/mempool.go +++ b/mempool/mempool.go @@ -10,7 +10,6 @@ import ( "github.com/spf13/viper" abci "github.com/tendermint/abci/types" - cfg "github.com/tendermint/go-config" "github.com/tendermint/tendermint/proxy" "github.com/tendermint/tendermint/types" auto "github.com/tendermint/tmlibs/autofile" diff --git a/mempool/reactor.go b/mempool/reactor.go index d30fd1151..6bea53b0c 100644 --- a/mempool/reactor.go +++ b/mempool/reactor.go @@ -9,7 +9,6 @@ import ( "github.com/spf13/viper" abci "github.com/tendermint/abci/types" - cfg "github.com/tendermint/go-config" "github.com/tendermint/go-wire" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/types" diff --git a/node/node.go b/node/node.go index 17fb98bad..1c66c00e0 100644 --- a/node/node.go +++ b/node/node.go @@ -10,7 +10,6 @@ import ( "github.com/spf13/viper" abci "github.com/tendermint/abci/types" - cfg "github.com/tendermint/go-config" crypto "github.com/tendermint/go-crypto" wire "github.com/tendermint/go-wire" bc "github.com/tendermint/tendermint/blockchain" diff --git a/p2p/config.go b/p2p/config.go index a8b7e343b..2e70d16df 100644 --- a/p2p/config.go +++ b/p2p/config.go @@ -1,7 +1,7 @@ package p2p import ( - cfg "github.com/tendermint/go-config" + "github.com/spf13/viper" ) const ( @@ -24,7 +24,7 @@ const ( configFuzzProbSleep = "fuzz_prob_sleep" ) -func setConfigDefaults(config cfg.Config) { +func setConfigDefaults(config *viper.Viper) { // Switch default config config.SetDefault(configKeyDialTimeoutSeconds, 3) config.SetDefault(configKeyHandshakeTimeoutSeconds, 20) diff --git a/p2p/switch.go b/p2p/switch.go index 8c771df1c..7e9c0a9c6 100644 --- a/p2p/switch.go +++ b/p2p/switch.go @@ -7,7 +7,8 @@ import ( "net" "time" - cfg "github.com/tendermint/go-config" + "github.com/spf13/viper" + crypto "github.com/tendermint/go-crypto" "github.com/tendermint/log15" . "github.com/tendermint/tmlibs/common" @@ -61,7 +62,7 @@ incoming messages are received on the reactor. type Switch struct { BaseService - config cfg.Config + config *viper.Viper listeners []Listener reactors map[string]Reactor chDescs []*ChannelDescriptor @@ -80,7 +81,7 @@ var ( ErrSwitchMaxPeersPerIPRange = errors.New("IP range has too many peers") ) -func NewSwitch(config cfg.Config) *Switch { +func NewSwitch(config *viper.Viper) *Switch { setConfigDefaults(config) sw := &Switch{ @@ -529,7 +530,7 @@ func makeSwitch(i int, network, version string, initSwitch func(int, *Switch) *S privKey := crypto.GenPrivKeyEd25519() // new switch, add reactors // TODO: let the config be passed in? - s := initSwitch(i, NewSwitch(cfg.NewMapConfig(nil))) + s := initSwitch(i, NewSwitch(viper.New())) s.SetNodeInfo(&NodeInfo{ PubKey: privKey.PubKey().Unwrap().(crypto.PubKeyEd25519), Moniker: Fmt("switch%d", i), @@ -572,7 +573,7 @@ func (sw *Switch) addPeerWithConnectionAndConfig(conn net.Conn, config *PeerConf return nil } -func peerConfigFromGoConfig(config cfg.Config) *PeerConfig { +func peerConfigFromGoConfig(config *viper.Viper) *PeerConfig { return &PeerConfig{ AuthEnc: config.GetBool(configKeyAuthEnc), Fuzz: config.GetBool(configFuzzEnable), diff --git a/p2p/switch_test.go b/p2p/switch_test.go index 1f1fe69f0..38529d754 100644 --- a/p2p/switch_test.go +++ b/p2p/switch_test.go @@ -8,20 +8,21 @@ import ( "testing" "time" + "github.com/spf13/viper" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - . "github.com/tendermint/tmlibs/common" - cfg "github.com/tendermint/go-config" crypto "github.com/tendermint/go-crypto" wire "github.com/tendermint/go-wire" + . "github.com/tendermint/tmlibs/common" ) var ( - config cfg.Config + config *viper.Viper ) func init() { - config = cfg.NewMapConfig(nil) + config = viper.New() setConfigDefaults(config) } diff --git a/proxy/app_conn_test.go b/proxy/app_conn_test.go index 7c072625a..f9c6afc98 100644 --- a/proxy/app_conn_test.go +++ b/proxy/app_conn_test.go @@ -4,11 +4,11 @@ import ( "strings" "testing" - . "github.com/tendermint/tmlibs/common" abcicli "github.com/tendermint/abci/client" "github.com/tendermint/abci/example/dummy" "github.com/tendermint/abci/server" "github.com/tendermint/abci/types" + cmn "github.com/tendermint/tmlibs/common" ) //---------------------------------------- @@ -44,43 +44,43 @@ func (app *appConnTest) InfoSync() (types.ResponseInfo, error) { var SOCKET = "socket" func TestEcho(t *testing.T) { - sockPath := Fmt("unix:///tmp/echo_%v.sock", RandStr(6)) + sockPath := cmn.Fmt("unix:///tmp/echo_%v.sock", cmn.RandStr(6)) clientCreator := NewRemoteClientCreator(sockPath, SOCKET, true) // Start server s, err := server.NewSocketServer(sockPath, dummy.NewDummyApplication()) if err != nil { - Exit(err.Error()) + cmn.Exit(err.Error()) } defer s.Stop() // Start client cli, err := clientCreator.NewABCIClient() if err != nil { - Exit(err.Error()) + cmn.Exit(err.Error()) } proxy := NewAppConnTest(cli) t.Log("Connected") for i := 0; i < 1000; i++ { - proxy.EchoAsync(Fmt("echo-%v", i)) + proxy.EchoAsync(cmn.Fmt("echo-%v", i)) } proxy.FlushSync() } func BenchmarkEcho(b *testing.B) { b.StopTimer() // Initialize - sockPath := Fmt("unix:///tmp/echo_%v.sock", RandStr(6)) + sockPath := cmn.Fmt("unix:///tmp/echo_%v.sock", cmn.RandStr(6)) clientCreator := NewRemoteClientCreator(sockPath, SOCKET, true) // Start server s, err := server.NewSocketServer(sockPath, dummy.NewDummyApplication()) if err != nil { - Exit(err.Error()) + cmn.Exit(err.Error()) } defer s.Stop() // Start client cli, err := clientCreator.NewABCIClient() if err != nil { - Exit(err.Error()) + cmn.Exit(err.Error()) } proxy := NewAppConnTest(cli) b.Log("Connected") @@ -98,18 +98,18 @@ func BenchmarkEcho(b *testing.B) { } func TestInfo(t *testing.T) { - sockPath := Fmt("unix:///tmp/echo_%v.sock", RandStr(6)) + sockPath := cmn.Fmt("unix:///tmp/echo_%v.sock", cmn.RandStr(6)) clientCreator := NewRemoteClientCreator(sockPath, SOCKET, true) // Start server s, err := server.NewSocketServer(sockPath, dummy.NewDummyApplication()) if err != nil { - Exit(err.Error()) + cmn.Exit(err.Error()) } defer s.Stop() // Start client cli, err := clientCreator.NewABCIClient() if err != nil { - Exit(err.Error()) + cmn.Exit(err.Error()) } proxy := NewAppConnTest(cli) t.Log("Connected") diff --git a/proxy/multi_app_conn.go b/proxy/multi_app_conn.go index bb846c7fa..9f70713eb 100644 --- a/proxy/multi_app_conn.go +++ b/proxy/multi_app_conn.go @@ -2,7 +2,6 @@ package proxy import ( "github.com/spf13/viper" - cfg "github.com/tendermint/go-config" cmn "github.com/tendermint/tmlibs/common" ) diff --git a/rpc/tendermint/core/pipe.go b/rpc/tendermint/core/pipe.go index 6f4740902..b10ff4737 100644 --- a/rpc/tendermint/core/pipe.go +++ b/rpc/tendermint/core/pipe.go @@ -2,7 +2,6 @@ package core import ( "github.com/spf13/viper" - cfg "github.com/tendermint/go-config" crypto "github.com/tendermint/go-crypto" "github.com/tendermint/tendermint/consensus" diff --git a/rpc/tendermint/test/helpers.go b/rpc/tendermint/test/helpers.go index f89287670..4e281f8c3 100644 --- a/rpc/tendermint/test/helpers.go +++ b/rpc/tendermint/test/helpers.go @@ -15,7 +15,6 @@ import ( logger "github.com/tendermint/tmlibs/logger" abci "github.com/tendermint/abci/types" - cfg "github.com/tendermint/go-config" "github.com/tendermint/tendermint/config/tendermint_test" nm "github.com/tendermint/tendermint/node" "github.com/tendermint/tendermint/proxy" diff --git a/state/errors.go b/state/errors.go index 1ea7ed3d9..50c5a2c04 100644 --- a/state/errors.go +++ b/state/errors.go @@ -1,7 +1,7 @@ package state import ( - . "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tmlibs/common" ) type ( @@ -36,20 +36,20 @@ type ( ) func (e ErrUnknownBlock) Error() string { - return Fmt("Could not find block #%d", e.Height) + return cmn.Fmt("Could not find block #%d", e.Height) } func (e ErrBlockHashMismatch) Error() string { - return Fmt("App block hash (%X) does not match core block hash (%X) for height %d", e.AppHash, e.CoreHash, e.Height) + return cmn.Fmt("App block hash (%X) does not match core block hash (%X) for height %d", e.AppHash, e.CoreHash, e.Height) } func (e ErrAppBlockHeightTooHigh) Error() string { - return Fmt("App block height (%d) is higher than core (%d)", e.AppHeight, e.CoreHeight) + return cmn.Fmt("App block height (%d) is higher than core (%d)", e.AppHeight, e.CoreHeight) } func (e ErrLastStateMismatch) Error() string { - return Fmt("Latest tendermint block (%d) LastAppHash (%X) does not match app's AppHash (%X)", e.Height, e.Core, e.App) + return cmn.Fmt("Latest tendermint block (%d) LastAppHash (%X) does not match app's AppHash (%X)", e.Height, e.Core, e.App) } func (e ErrStateMismatch) Error() string { - return Fmt("State after replay does not match saved state. Got ----\n%v\nExpected ----\n%v\n", e.Got, e.Expected) + return cmn.Fmt("State after replay does not match saved state. Got ----\n%v\nExpected ----\n%v\n", e.Got, e.Expected) } diff --git a/state/execution.go b/state/execution.go index 643dd4d05..b06974cd8 100644 --- a/state/execution.go +++ b/state/execution.go @@ -6,11 +6,11 @@ import ( fail "github.com/ebuchman/fail-test" abci "github.com/tendermint/abci/types" - . "github.com/tendermint/tmlibs/common" crypto "github.com/tendermint/go-crypto" "github.com/tendermint/tendermint/proxy" "github.com/tendermint/tendermint/state/txindex" "github.com/tendermint/tendermint/types" + cmn "github.com/tendermint/tmlibs/common" ) //-------------------------------------------------- @@ -126,7 +126,7 @@ func updateValidators(validators *types.ValidatorSet, changedValidators []*abci. power := int64(v.Power) // mind the overflow from uint64 if power < 0 { - return errors.New(Fmt("Power (%d) overflows int64", v.Power)) + return errors.New(cmn.Fmt("Power (%d) overflows int64", v.Power)) } _, val := validators.GetByAddress(address) @@ -134,20 +134,20 @@ func updateValidators(validators *types.ValidatorSet, changedValidators []*abci. // add val added := validators.Add(types.NewValidator(pubkey, power)) if !added { - return errors.New(Fmt("Failed to add new validator %X with voting power %d", address, power)) + return errors.New(cmn.Fmt("Failed to add new validator %X with voting power %d", address, power)) } } else if v.Power == 0 { // remove val _, removed := validators.Remove(address) if !removed { - return errors.New(Fmt("Failed to remove validator %X)")) + return errors.New(cmn.Fmt("Failed to remove validator %X)")) } } else { // update val val.VotingPower = power updated := validators.Update(val) if !updated { - return errors.New(Fmt("Failed to update validator %X with voting power %d", address, power)) + return errors.New(cmn.Fmt("Failed to update validator %X with voting power %d", address, power)) } } } @@ -156,8 +156,8 @@ func updateValidators(validators *types.ValidatorSet, changedValidators []*abci. // return a bit array of validators that signed the last commit // NOTE: assumes commits have already been authenticated -func commitBitArrayFromBlock(block *types.Block) *BitArray { - signed := NewBitArray(len(block.LastCommit.Precommits)) +func commitBitArrayFromBlock(block *types.Block) *cmn.BitArray { + signed := cmn.NewBitArray(len(block.LastCommit.Precommits)) for i, precommit := range block.LastCommit.Precommits { if precommit != nil { signed.SetIndex(i, true) // val_.LastCommitHeight = block.Height - 1 @@ -187,7 +187,7 @@ func (s *State) validateBlock(block *types.Block) error { } } else { if len(block.LastCommit.Precommits) != s.LastValidators.Size() { - return errors.New(Fmt("Invalid block commit size. Expected %v, got %v", + return errors.New(cmn.Fmt("Invalid block commit size. Expected %v, got %v", s.LastValidators.Size(), len(block.LastCommit.Precommits))) } err := s.LastValidators.VerifyCommit( diff --git a/state/state.go b/state/state.go index 3055fb7b7..2625cbc71 100644 --- a/state/state.go +++ b/state/state.go @@ -8,8 +8,7 @@ import ( "github.com/spf13/viper" abci "github.com/tendermint/abci/types" - cfg "github.com/tendermint/go-config" - . "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tmlibs/common" dbm "github.com/tendermint/tmlibs/db" "github.com/tendermint/go-wire" @@ -66,7 +65,7 @@ func loadState(db dbm.DB, key []byte) *State { wire.ReadBinaryPtr(&s, r, 0, n, err) if *err != nil { // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED - Exit(Fmt("LoadState: Data has been corrupted or its spec has changed: %v\n", *err)) + cmn.Exit(cmn.Fmt("LoadState: Data has been corrupted or its spec has changed: %v\n", *err)) } // TODO: ensure that buf is completely read. } @@ -110,7 +109,7 @@ func (s *State) LoadABCIResponses() *ABCIResponses { wire.ReadBinaryPtr(abciResponses, r, 0, n, err) if *err != nil { // DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED - Exit(Fmt("LoadABCIResponses: Data has been corrupted or its spec has changed: %v\n", *err)) + cmn.Exit(cmn.Fmt("LoadABCIResponses: Data has been corrupted or its spec has changed: %v\n", *err)) } // TODO: ensure that buf is completely read. } @@ -125,7 +124,7 @@ func (s *State) Bytes() []byte { buf, n, err := new(bytes.Buffer), new(int), new(error) wire.WriteBinary(s, buf, n, err) if *err != nil { - PanicCrisis(*err) + cmn.PanicCrisis(*err) } return buf.Bytes() } @@ -205,7 +204,7 @@ func (a *ABCIResponses) Bytes() []byte { buf, n, err := new(bytes.Buffer), new(int), new(error) wire.WriteBinary(*a, buf, n, err) if *err != nil { - PanicCrisis(*err) + cmn.PanicCrisis(*err) } return buf.Bytes() } @@ -219,11 +218,11 @@ func (a *ABCIResponses) Bytes() []byte { func MakeGenesisStateFromFile(db dbm.DB, genDocFile string) *State { genDocJSON, err := ioutil.ReadFile(genDocFile) if err != nil { - Exit(Fmt("Couldn't read GenesisDoc file: %v", err)) + cmn.Exit(cmn.Fmt("Couldn't read GenesisDoc file: %v", err)) } genDoc, err := types.GenesisDocFromJSON(genDocJSON) if err != nil { - Exit(Fmt("Error reading GenesisDoc: %v", err)) + cmn.Exit(cmn.Fmt("Error reading GenesisDoc: %v", err)) } return MakeGenesisState(db, genDoc) } @@ -233,7 +232,7 @@ func MakeGenesisStateFromFile(db dbm.DB, genDocFile string) *State { // Used in tests. func MakeGenesisState(db dbm.DB, genDoc *types.GenesisDoc) *State { if len(genDoc.Validators) == 0 { - Exit(Fmt("The genesis file has no validators")) + cmn.Exit(cmn.Fmt("The genesis file has no validators")) } if genDoc.GenesisTime.IsZero() { diff --git a/test/test_libs.sh b/test/test_libs.sh index 1d57ae049..3f4315cd9 100644 --- a/test/test_libs.sh +++ b/test/test_libs.sh @@ -14,8 +14,8 @@ fi # some libs are tested with go, others with make # TODO: should be all make (post repo merge) -LIBS_GO_TEST=(tmlibs/clist tmlibs/common go-config go-crypto tmlibs/db tmlibs/events go-merkle tendermint/p2p) -LIBS_MAKE_TEST=(tendermint/rpc go-wire abci) +LIBS_GO_TEST=(tmlibs go-crypto) +LIBS_MAKE_TEST=(go-wire abci) for lib in "${LIBS_GO_TEST[@]}"; do From 2fcb2b9232ccd295c770111812e998c65903a2a9 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Tue, 25 Apr 2017 17:58:26 -0400 Subject: [PATCH 210/309] remove unsafe_set_config --- rpc/tendermint/core/routes.go | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/rpc/tendermint/core/routes.go b/rpc/tendermint/core/routes.go index 1ed874f28..7ed18ef7f 100644 --- a/rpc/tendermint/core/routes.go +++ b/rpc/tendermint/core/routes.go @@ -3,8 +3,8 @@ package core import ( data "github.com/tendermint/go-wire/data" rpc "github.com/tendermint/tendermint/rpc/server" - "github.com/tendermint/tendermint/rpc/types" ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" + "github.com/tendermint/tendermint/rpc/types" "github.com/tendermint/tendermint/types" ) @@ -39,7 +39,9 @@ var Routes = map[string]*rpc.RPCFunc{ // control API "dial_seeds": rpc.NewRPCFunc(UnsafeDialSeedsResult, "seeds"), "unsafe_flush_mempool": rpc.NewRPCFunc(UnsafeFlushMempool, ""), - "unsafe_set_config": rpc.NewRPCFunc(UnsafeSetConfigResult, "type,key,value"), + + // config is not in general thread safe. expose specifics if you need em + // "unsafe_set_config": rpc.NewRPCFunc(UnsafeSetConfigResult, "type,key,value"), // profiler API "unsafe_start_cpu_profiler": rpc.NewRPCFunc(UnsafeStartCPUProfilerResult, "filename"), From 098646c5ff604705b7b082a89227ee78f3547fed Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Tue, 25 Apr 2017 18:35:22 -0400 Subject: [PATCH 211/309] test: test_libs all use Makefile --- test/test_libs.sh | 20 +++----------------- 1 file changed, 3 insertions(+), 17 deletions(-) diff --git a/test/test_libs.sh b/test/test_libs.sh index 3f4315cd9..0a8485340 100644 --- a/test/test_libs.sh +++ b/test/test_libs.sh @@ -12,23 +12,8 @@ fi # libs we depend on #################### -# some libs are tested with go, others with make -# TODO: should be all make (post repo merge) -LIBS_GO_TEST=(tmlibs go-crypto) -LIBS_MAKE_TEST=(go-wire abci) - -for lib in "${LIBS_GO_TEST[@]}"; do - - # checkout vendored version of lib - bash scripts/glide/checkout.sh "$GLIDE" "$lib" - - echo "Testing $lib ..." - go test -v --race "github.com/tendermint/$lib/..." - if [[ "$?" != 0 ]]; then - echo "FAIL" - exit 1 - fi -done +# All libs should define `make test` and `make get_vendor_deps` +LIBS_TEST=(tmlibs go-wire go-crypto abci) DIR=$(pwd) for lib in "${LIBS_MAKE_TEST[@]}"; do @@ -38,6 +23,7 @@ for lib in "${LIBS_MAKE_TEST[@]}"; do echo "Testing $lib ..." cd "$GOPATH/src/github.com/tendermint/$lib" + make get_vendor_deps make test if [[ "$?" != 0 ]]; then echo "FAIL" From 9851265d4f26cadc251b5865a622058894aa1d89 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Tue, 25 Apr 2017 23:09:47 -0400 Subject: [PATCH 212/309] rpc: use HTTP error codes --- rpc/server/handlers.go | 20 ++++++++++---------- rpc/server/http_server.go | 11 +++++++++++ 2 files changed, 21 insertions(+), 10 deletions(-) diff --git a/rpc/server/handlers.go b/rpc/server/handlers.go index f5b3659d3..a0dbc487a 100644 --- a/rpc/server/handlers.go +++ b/rpc/server/handlers.go @@ -14,8 +14,8 @@ import ( "github.com/gorilla/websocket" "github.com/pkg/errors" - types "github.com/tendermint/tendermint/rpc/types" wire "github.com/tendermint/go-wire" + types "github.com/tendermint/tendermint/rpc/types" cmn "github.com/tendermint/tmlibs/common" events "github.com/tendermint/tmlibs/events" ) @@ -108,32 +108,32 @@ func makeJSONRPCHandler(funcMap map[string]*RPCFunc) http.HandlerFunc { var request types.RPCRequest err := json.Unmarshal(b, &request) if err != nil { - WriteRPCResponseHTTP(w, types.NewRPCResponse("", nil, fmt.Sprintf("Error unmarshalling request: %v", err.Error()))) + WriteRPCResponseHTTPError(w, http.StatusBadRequest, types.NewRPCResponse("", nil, fmt.Sprintf("Error unmarshalling request: %v", err.Error()))) return } if len(r.URL.Path) > 1 { - WriteRPCResponseHTTP(w, types.NewRPCResponse(request.ID, nil, fmt.Sprintf("Invalid JSONRPC endpoint %s", r.URL.Path))) + WriteRPCResponseHTTPError(w, http.StatusNotFound, types.NewRPCResponse(request.ID, nil, fmt.Sprintf("Invalid JSONRPC endpoint %s", r.URL.Path))) return } rpcFunc := funcMap[request.Method] if rpcFunc == nil { - WriteRPCResponseHTTP(w, types.NewRPCResponse(request.ID, nil, "RPC method unknown: "+request.Method)) + WriteRPCResponseHTTPError(w, http.StatusNotFound, types.NewRPCResponse(request.ID, nil, "RPC method unknown: "+request.Method)) return } if rpcFunc.ws { - WriteRPCResponseHTTP(w, types.NewRPCResponse(request.ID, nil, "RPC method is only for websockets: "+request.Method)) + WriteRPCResponseHTTPError(w, http.StatusMethodNotAllowed, types.NewRPCResponse(request.ID, nil, "RPC method is only for websockets: "+request.Method)) return } args, err := jsonParamsToArgsRPC(rpcFunc, request.Params) if err != nil { - WriteRPCResponseHTTP(w, types.NewRPCResponse(request.ID, nil, fmt.Sprintf("Error converting json params to arguments: %v", err.Error()))) + WriteRPCResponseHTTPError(w, http.StatusBadRequest, types.NewRPCResponse(request.ID, nil, fmt.Sprintf("Error converting json params to arguments: %v", err.Error()))) return } returns := rpcFunc.f.Call(args) log.Info("HTTPJSONRPC", "method", request.Method, "args", args, "returns", returns) result, err := unreflectResult(returns) if err != nil { - WriteRPCResponseHTTP(w, types.NewRPCResponse(request.ID, result, err.Error())) + WriteRPCResponseHTTPError(w, http.StatusInternalServerError, types.NewRPCResponse(request.ID, result, err.Error())) return } WriteRPCResponseHTTP(w, types.NewRPCResponse(request.ID, result, "")) @@ -221,7 +221,7 @@ func makeHTTPHandler(rpcFunc *RPCFunc) func(http.ResponseWriter, *http.Request) // Exception for websocket endpoints if rpcFunc.ws { return func(w http.ResponseWriter, r *http.Request) { - WriteRPCResponseHTTP(w, types.NewRPCResponse("", nil, "This RPC method is only for websockets")) + WriteRPCResponseHTTPError(w, http.StatusMethodNotAllowed, types.NewRPCResponse("", nil, "This RPC method is only for websockets")) } } // All other endpoints @@ -229,14 +229,14 @@ func makeHTTPHandler(rpcFunc *RPCFunc) func(http.ResponseWriter, *http.Request) log.Debug("HTTP HANDLER", "req", r) args, err := httpParamsToArgs(rpcFunc, r) if err != nil { - WriteRPCResponseHTTP(w, types.NewRPCResponse("", nil, fmt.Sprintf("Error converting http params to args: %v", err.Error()))) + WriteRPCResponseHTTPError(w, http.StatusBadRequest, types.NewRPCResponse("", nil, fmt.Sprintf("Error converting http params to args: %v", err.Error()))) return } returns := rpcFunc.f.Call(args) log.Info("HTTPRestRPC", "method", r.URL.Path, "args", args, "returns", returns) result, err := unreflectResult(returns) if err != nil { - WriteRPCResponseHTTP(w, types.NewRPCResponse("", nil, err.Error())) + WriteRPCResponseHTTPError(w, http.StatusInternalServerError, types.NewRPCResponse("", nil, err.Error())) return } WriteRPCResponseHTTP(w, types.NewRPCResponse("", result, "")) diff --git a/rpc/server/http_server.go b/rpc/server/http_server.go index a613be253..b30bc3606 100644 --- a/rpc/server/http_server.go +++ b/rpc/server/http_server.go @@ -46,6 +46,17 @@ func StartHTTPServer(listenAddr string, handler http.Handler) (listener net.List return listener, nil } +func WriteRPCResponseHTTPError(w http.ResponseWriter, httpCode int, res types.RPCResponse) { + jsonBytes, err := json.Marshal(res) + if err != nil { + panic(err) + } + + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(httpCode) + w.Write(jsonBytes) +} + func WriteRPCResponseHTTP(w http.ResponseWriter, res types.RPCResponse) { // jsonBytes := wire.JSONBytesPretty(res) jsonBytes, err := json.Marshal(res) From cc6dde96c12dddafe23173ad195034f3d4884423 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Wed, 26 Apr 2017 19:57:33 -0400 Subject: [PATCH 213/309] rpc -> rpc/lib and rpc/tendermint -> rpc --- benchmarks/codec_test.go | 2 +- benchmarks/simu/counter.go | 6 +++--- node/node.go | 8 ++++---- rpc/Dockerfile | 12 ------------ rpc/{tendermint => }/client/event_test.go | 2 +- rpc/{tendermint => }/client/helpers.go | 0 rpc/{tendermint => }/client/helpers_test.go | 6 +++--- rpc/{tendermint => }/client/httpclient.go | 4 ++-- rpc/{tendermint => }/client/interface.go | 2 +- rpc/{tendermint => }/client/localclient.go | 4 ++-- rpc/{tendermint => }/client/main_test.go | 2 +- rpc/{tendermint => }/client/mock/abci.go | 4 ++-- rpc/{tendermint => }/client/mock/abci_test.go | 4 ++-- rpc/{tendermint => }/client/mock/client.go | 6 +++--- rpc/{tendermint => }/client/mock/status.go | 4 ++-- rpc/{tendermint => }/client/mock/status_test.go | 4 ++-- rpc/{tendermint => }/client/rpc_test.go | 4 ++-- rpc/{tendermint => }/core/abci.go | 2 +- rpc/{tendermint => }/core/blocks.go | 2 +- rpc/{tendermint => }/core/consensus.go | 2 +- rpc/{tendermint => }/core/dev.go | 2 +- rpc/{tendermint => }/core/events.go | 4 ++-- rpc/{tendermint => }/core/log.go | 0 rpc/{tendermint => }/core/mempool.go | 2 +- rpc/{tendermint => }/core/net.go | 2 +- rpc/{tendermint => }/core/pipe.go | 0 rpc/{tendermint => }/core/routes.go | 6 +++--- rpc/{tendermint => }/core/status.go | 2 +- rpc/{tendermint => }/core/tx.go | 2 +- rpc/{tendermint => }/core/types/responses.go | 2 +- rpc/{tendermint => }/core/types/responses_test.go | 0 rpc/{tendermint => }/core/version.go | 0 rpc/{tendermint => }/grpc/api.go | 2 +- rpc/{tendermint => }/grpc/client_server.go | 0 rpc/{tendermint => }/grpc/compile.sh | 0 rpc/{tendermint => }/grpc/types.pb.go | 0 rpc/{tendermint => }/grpc/types.proto | 0 rpc/lib/Dockerfile | 12 ++++++++++++ rpc/{ => lib}/Makefile | 0 rpc/{ => lib}/README.md | 4 ++-- rpc/{ => lib}/circle.yml | 0 rpc/{ => lib}/client/args_test.go | 0 rpc/{ => lib}/client/http_client.go | 4 ++-- rpc/{ => lib}/client/log.go | 0 rpc/{ => lib}/client/ws_client.go | 2 +- rpc/{ => lib}/rpc_test.go | 6 +++--- rpc/{ => lib}/server/handlers.go | 2 +- rpc/{ => lib}/server/http_params.go | 0 rpc/{ => lib}/server/http_server.go | 4 ++-- rpc/{ => lib}/server/log.go | 0 rpc/{ => lib}/test/data.json | 0 rpc/{ => lib}/test/integration_test.sh | 0 rpc/{ => lib}/test/main.go | 2 +- rpc/{ => lib}/types/types.go | 0 rpc/{ => lib}/version.go | 0 rpc/{tendermint => }/test/client_test.go | 6 +++--- rpc/{tendermint => }/test/grpc_test.go | 2 +- rpc/{tendermint => }/test/helpers.go | 6 +++--- rpc/{tendermint => }/test/main_test.go | 0 test/app/grpc_client.go | 2 +- 60 files changed, 78 insertions(+), 78 deletions(-) delete mode 100644 rpc/Dockerfile rename rpc/{tendermint => }/client/event_test.go (96%) rename rpc/{tendermint => }/client/helpers.go (100%) rename rpc/{tendermint => }/client/helpers_test.go (90%) rename rpc/{tendermint => }/client/httpclient.go (98%) rename rpc/{tendermint => }/client/interface.go (97%) rename rpc/{tendermint => }/client/localclient.go (95%) rename rpc/{tendermint => }/client/main_test.go (87%) rename rpc/{tendermint => }/client/mock/abci.go (97%) rename rpc/{tendermint => }/client/mock/abci_test.go (97%) rename rpc/{tendermint => }/client/mock/client.go (95%) rename rpc/{tendermint => }/client/mock/status.go (89%) rename rpc/{tendermint => }/client/mock/status_test.go (88%) rename rpc/{tendermint => }/client/rpc_test.go (97%) rename rpc/{tendermint => }/core/abci.go (91%) rename rpc/{tendermint => }/core/blocks.go (96%) rename rpc/{tendermint => }/core/consensus.go (92%) rename rpc/{tendermint => }/core/dev.go (95%) rename rpc/{tendermint => }/core/events.go (89%) rename rpc/{tendermint => }/core/log.go (100%) rename rpc/{tendermint => }/core/mempool.go (98%) rename rpc/{tendermint => }/core/net.go (95%) rename rpc/{tendermint => }/core/pipe.go (100%) rename rpc/{tendermint => }/core/routes.go (96%) rename rpc/{tendermint => }/core/status.go (92%) rename rpc/{tendermint => }/core/tx.go (91%) rename rpc/{tendermint => }/core/types/responses.go (99%) rename rpc/{tendermint => }/core/types/responses_test.go (100%) rename rpc/{tendermint => }/core/version.go (100%) rename rpc/{tendermint => }/grpc/api.go (85%) rename rpc/{tendermint => }/grpc/client_server.go (100%) rename rpc/{tendermint => }/grpc/compile.sh (100%) rename rpc/{tendermint => }/grpc/types.pb.go (100%) rename rpc/{tendermint => }/grpc/types.proto (100%) create mode 100644 rpc/lib/Dockerfile rename rpc/{ => lib}/Makefile (100%) rename rpc/{ => lib}/README.md (95%) rename rpc/{ => lib}/circle.yml (100%) rename rpc/{ => lib}/client/args_test.go (100%) rename rpc/{ => lib}/client/http_client.go (96%) rename rpc/{ => lib}/client/log.go (100%) rename rpc/{ => lib}/client/ws_client.go (98%) rename rpc/{ => lib}/rpc_test.go (97%) rename rpc/{ => lib}/server/handlers.go (99%) rename rpc/{ => lib}/server/http_params.go (100%) rename rpc/{ => lib}/server/http_server.go (95%) rename rpc/{ => lib}/server/log.go (100%) rename rpc/{ => lib}/test/data.json (100%) rename rpc/{ => lib}/test/integration_test.sh (100%) rename rpc/{ => lib}/test/main.go (90%) rename rpc/{ => lib}/types/types.go (100%) rename rpc/{ => lib}/version.go (100%) rename rpc/{tendermint => }/test/client_test.go (98%) rename rpc/{tendermint => }/test/grpc_test.go (88%) rename rpc/{tendermint => }/test/helpers.go (96%) rename rpc/{tendermint => }/test/main_test.go (100%) diff --git a/benchmarks/codec_test.go b/benchmarks/codec_test.go index 205aec403..7162e63d0 100644 --- a/benchmarks/codec_test.go +++ b/benchmarks/codec_test.go @@ -7,7 +7,7 @@ import ( "github.com/tendermint/tendermint/p2p" "github.com/tendermint/go-wire" proto "github.com/tendermint/tendermint/benchmarks/proto" - ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" + ctypes "github.com/tendermint/tendermint/rpc/core/types" ) func BenchmarkEncodeStatusWire(b *testing.B) { diff --git a/benchmarks/simu/counter.go b/benchmarks/simu/counter.go index f384d3579..a22162b97 100644 --- a/benchmarks/simu/counter.go +++ b/benchmarks/simu/counter.go @@ -8,10 +8,10 @@ import ( "github.com/gorilla/websocket" . "github.com/tendermint/tmlibs/common" - "github.com/tendermint/tendermint/rpc/client" - "github.com/tendermint/tendermint/rpc/types" + "github.com/tendermint/tendermint/rpc/lib/client" + "github.com/tendermint/tendermint/rpc/lib/types" "github.com/tendermint/go-wire" - _ "github.com/tendermint/tendermint/rpc/tendermint/core/types" // Register RPCResponse > Result types + _ "github.com/tendermint/tendermint/rpc/core/types" // Register RPCResponse > Result types ) func main() { diff --git a/node/node.go b/node/node.go index 1c66c00e0..e34f8c726 100644 --- a/node/node.go +++ b/node/node.go @@ -17,10 +17,10 @@ import ( mempl "github.com/tendermint/tendermint/mempool" p2p "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/proxy" - rpc "github.com/tendermint/tendermint/rpc" - rpcserver "github.com/tendermint/tendermint/rpc/server" - rpccore "github.com/tendermint/tendermint/rpc/tendermint/core" - grpccore "github.com/tendermint/tendermint/rpc/tendermint/grpc" + rpccore "github.com/tendermint/tendermint/rpc/core" + grpccore "github.com/tendermint/tendermint/rpc/grpc" + rpc "github.com/tendermint/tendermint/rpc/lib" + rpcserver "github.com/tendermint/tendermint/rpc/lib/server" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/state/txindex" "github.com/tendermint/tendermint/state/txindex/kv" diff --git a/rpc/Dockerfile b/rpc/Dockerfile deleted file mode 100644 index c22412672..000000000 --- a/rpc/Dockerfile +++ /dev/null @@ -1,12 +0,0 @@ -FROM golang:latest - -RUN mkdir -p /go/src/github.com/tendermint/tendermint/rpc -WORKDIR /go/src/github.com/tendermint/tendermint/rpc - -COPY Makefile /go/src/github.com/tendermint/tendermint/rpc/ -# COPY glide.yaml /go/src/github.com/tendermint/tendermint/rpc/ -# COPY glide.lock /go/src/github.com/tendermint/tendermint/rpc/ - -COPY . /go/src/github.com/tendermint/tendermint/rpc - -RUN make get_deps diff --git a/rpc/tendermint/client/event_test.go b/rpc/client/event_test.go similarity index 96% rename from rpc/tendermint/client/event_test.go rename to rpc/client/event_test.go index a82a284f6..cc421ad90 100644 --- a/rpc/tendermint/client/event_test.go +++ b/rpc/client/event_test.go @@ -6,7 +6,7 @@ import ( "github.com/stretchr/testify/require" merktest "github.com/tendermint/merkleeyes/testutil" - "github.com/tendermint/tendermint/rpc/tendermint/client" + "github.com/tendermint/tendermint/rpc/client" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/client/helpers.go b/rpc/client/helpers.go similarity index 100% rename from rpc/tendermint/client/helpers.go rename to rpc/client/helpers.go diff --git a/rpc/tendermint/client/helpers_test.go b/rpc/client/helpers_test.go similarity index 90% rename from rpc/tendermint/client/helpers_test.go rename to rpc/client/helpers_test.go index 1057a21bd..fe1861224 100644 --- a/rpc/tendermint/client/helpers_test.go +++ b/rpc/client/helpers_test.go @@ -7,9 +7,9 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/rpc/tendermint/client" - "github.com/tendermint/tendermint/rpc/tendermint/client/mock" - ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" + "github.com/tendermint/tendermint/rpc/client" + "github.com/tendermint/tendermint/rpc/client/mock" + ctypes "github.com/tendermint/tendermint/rpc/core/types" ) func TestWaitForHeight(t *testing.T) { diff --git a/rpc/tendermint/client/httpclient.go b/rpc/client/httpclient.go similarity index 98% rename from rpc/tendermint/client/httpclient.go rename to rpc/client/httpclient.go index e8f404d22..8f3a4f019 100644 --- a/rpc/tendermint/client/httpclient.go +++ b/rpc/client/httpclient.go @@ -6,9 +6,9 @@ import ( "github.com/pkg/errors" data "github.com/tendermint/go-wire/data" events "github.com/tendermint/tmlibs/events" - "github.com/tendermint/tendermint/rpc/client" + "github.com/tendermint/tendermint/rpc/lib/client" wire "github.com/tendermint/go-wire" - ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" + ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/client/interface.go b/rpc/client/interface.go similarity index 97% rename from rpc/tendermint/client/interface.go rename to rpc/client/interface.go index 4726e00d9..0cd0f29bb 100644 --- a/rpc/tendermint/client/interface.go +++ b/rpc/client/interface.go @@ -21,7 +21,7 @@ package client import ( data "github.com/tendermint/go-wire/data" - ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" + ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/client/localclient.go b/rpc/client/localclient.go similarity index 95% rename from rpc/tendermint/client/localclient.go rename to rpc/client/localclient.go index 146d96597..f4eb00d78 100644 --- a/rpc/tendermint/client/localclient.go +++ b/rpc/client/localclient.go @@ -3,8 +3,8 @@ package client import ( data "github.com/tendermint/go-wire/data" nm "github.com/tendermint/tendermint/node" - "github.com/tendermint/tendermint/rpc/tendermint/core" - ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" + "github.com/tendermint/tendermint/rpc/core" + ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/client/main_test.go b/rpc/client/main_test.go similarity index 87% rename from rpc/tendermint/client/main_test.go rename to rpc/client/main_test.go index 494b565ae..5ec911e5d 100644 --- a/rpc/tendermint/client/main_test.go +++ b/rpc/client/main_test.go @@ -6,7 +6,7 @@ import ( meapp "github.com/tendermint/merkleeyes/app" nm "github.com/tendermint/tendermint/node" - rpctest "github.com/tendermint/tendermint/rpc/tendermint/test" + rpctest "github.com/tendermint/tendermint/rpc/test" ) var node *nm.Node diff --git a/rpc/tendermint/client/mock/abci.go b/rpc/client/mock/abci.go similarity index 97% rename from rpc/tendermint/client/mock/abci.go rename to rpc/client/mock/abci.go index d03728dbe..db9bd2c2b 100644 --- a/rpc/tendermint/client/mock/abci.go +++ b/rpc/client/mock/abci.go @@ -3,8 +3,8 @@ package mock import ( abci "github.com/tendermint/abci/types" data "github.com/tendermint/go-wire/data" - "github.com/tendermint/tendermint/rpc/tendermint/client" - ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" + "github.com/tendermint/tendermint/rpc/client" + ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/client/mock/abci_test.go b/rpc/client/mock/abci_test.go similarity index 97% rename from rpc/tendermint/client/mock/abci_test.go rename to rpc/client/mock/abci_test.go index 3fcca9692..57334f25f 100644 --- a/rpc/tendermint/client/mock/abci_test.go +++ b/rpc/client/mock/abci_test.go @@ -11,10 +11,10 @@ import ( "github.com/tendermint/abci/example/dummy" abci "github.com/tendermint/abci/types" data "github.com/tendermint/go-wire/data" - ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" + ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/types" - "github.com/tendermint/tendermint/rpc/tendermint/client/mock" + "github.com/tendermint/tendermint/rpc/client/mock" ) func TestABCIMock(t *testing.T) { diff --git a/rpc/tendermint/client/mock/client.go b/rpc/client/mock/client.go similarity index 95% rename from rpc/tendermint/client/mock/client.go rename to rpc/client/mock/client.go index b2a91b743..bf8d78dce 100644 --- a/rpc/tendermint/client/mock/client.go +++ b/rpc/client/mock/client.go @@ -17,9 +17,9 @@ import ( "reflect" data "github.com/tendermint/go-wire/data" - "github.com/tendermint/tendermint/rpc/tendermint/client" - "github.com/tendermint/tendermint/rpc/tendermint/core" - ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" + "github.com/tendermint/tendermint/rpc/client" + "github.com/tendermint/tendermint/rpc/core" + ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/client/mock/status.go b/rpc/client/mock/status.go similarity index 89% rename from rpc/tendermint/client/mock/status.go rename to rpc/client/mock/status.go index 82ec40987..af0f5335d 100644 --- a/rpc/tendermint/client/mock/status.go +++ b/rpc/client/mock/status.go @@ -1,8 +1,8 @@ package mock import ( - "github.com/tendermint/tendermint/rpc/tendermint/client" - ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" + "github.com/tendermint/tendermint/rpc/client" + ctypes "github.com/tendermint/tendermint/rpc/core/types" ) // StatusMock returns the result specified by the Call diff --git a/rpc/tendermint/client/mock/status_test.go b/rpc/client/mock/status_test.go similarity index 88% rename from rpc/tendermint/client/mock/status_test.go rename to rpc/client/mock/status_test.go index f5a2bc7f8..e4adf52ba 100644 --- a/rpc/tendermint/client/mock/status_test.go +++ b/rpc/client/mock/status_test.go @@ -6,9 +6,9 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" data "github.com/tendermint/go-wire/data" - ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" + ctypes "github.com/tendermint/tendermint/rpc/core/types" - "github.com/tendermint/tendermint/rpc/tendermint/client/mock" + "github.com/tendermint/tendermint/rpc/client/mock" ) func TestStatus(t *testing.T) { diff --git a/rpc/tendermint/client/rpc_test.go b/rpc/client/rpc_test.go similarity index 97% rename from rpc/tendermint/client/rpc_test.go rename to rpc/client/rpc_test.go index 95c583c97..d0cb7a47b 100644 --- a/rpc/tendermint/client/rpc_test.go +++ b/rpc/client/rpc_test.go @@ -8,8 +8,8 @@ import ( "github.com/stretchr/testify/require" "github.com/tendermint/merkleeyes/iavl" merktest "github.com/tendermint/merkleeyes/testutil" - "github.com/tendermint/tendermint/rpc/tendermint/client" - rpctest "github.com/tendermint/tendermint/rpc/tendermint/test" + "github.com/tendermint/tendermint/rpc/client" + rpctest "github.com/tendermint/tendermint/rpc/test" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/core/abci.go b/rpc/core/abci.go similarity index 91% rename from rpc/tendermint/core/abci.go rename to rpc/core/abci.go index e56b92d70..5c9fcfc25 100644 --- a/rpc/tendermint/core/abci.go +++ b/rpc/core/abci.go @@ -3,7 +3,7 @@ package core import ( abci "github.com/tendermint/abci/types" data "github.com/tendermint/go-wire/data" - ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" + ctypes "github.com/tendermint/tendermint/rpc/core/types" ) //----------------------------------------------------------------------------- diff --git a/rpc/tendermint/core/blocks.go b/rpc/core/blocks.go similarity index 96% rename from rpc/tendermint/core/blocks.go rename to rpc/core/blocks.go index aa102255f..ef3474127 100644 --- a/rpc/tendermint/core/blocks.go +++ b/rpc/core/blocks.go @@ -3,7 +3,7 @@ package core import ( "fmt" . "github.com/tendermint/tmlibs/common" - ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" + ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/core/consensus.go b/rpc/core/consensus.go similarity index 92% rename from rpc/tendermint/core/consensus.go rename to rpc/core/consensus.go index e62e61a0c..e2ccce442 100644 --- a/rpc/tendermint/core/consensus.go +++ b/rpc/core/consensus.go @@ -3,7 +3,7 @@ package core import ( "github.com/tendermint/go-wire" cm "github.com/tendermint/tendermint/consensus" - ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" + ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/core/dev.go b/rpc/core/dev.go similarity index 95% rename from rpc/tendermint/core/dev.go rename to rpc/core/dev.go index 2053d7363..43a989534 100644 --- a/rpc/tendermint/core/dev.go +++ b/rpc/core/dev.go @@ -6,7 +6,7 @@ import ( "runtime/pprof" "strconv" - ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" + ctypes "github.com/tendermint/tendermint/rpc/core/types" ) func UnsafeFlushMempool() (*ctypes.ResultUnsafeFlushMempool, error) { diff --git a/rpc/tendermint/core/events.go b/rpc/core/events.go similarity index 89% rename from rpc/tendermint/core/events.go rename to rpc/core/events.go index e12122e57..555673df5 100644 --- a/rpc/tendermint/core/events.go +++ b/rpc/core/events.go @@ -1,8 +1,8 @@ package core import ( - "github.com/tendermint/tendermint/rpc/types" - ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" + "github.com/tendermint/tendermint/rpc/lib/types" + ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/core/log.go b/rpc/core/log.go similarity index 100% rename from rpc/tendermint/core/log.go rename to rpc/core/log.go diff --git a/rpc/tendermint/core/mempool.go b/rpc/core/mempool.go similarity index 98% rename from rpc/tendermint/core/mempool.go rename to rpc/core/mempool.go index e3d82bf87..4adf75ce5 100644 --- a/rpc/tendermint/core/mempool.go +++ b/rpc/core/mempool.go @@ -6,7 +6,7 @@ import ( abci "github.com/tendermint/abci/types" data "github.com/tendermint/go-wire/data" - ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" + ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/core/net.go b/rpc/core/net.go similarity index 95% rename from rpc/tendermint/core/net.go rename to rpc/core/net.go index 499458230..31d9c34ea 100644 --- a/rpc/tendermint/core/net.go +++ b/rpc/core/net.go @@ -3,7 +3,7 @@ package core import ( "fmt" - ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" + ctypes "github.com/tendermint/tendermint/rpc/core/types" ) //----------------------------------------------------------------------------- diff --git a/rpc/tendermint/core/pipe.go b/rpc/core/pipe.go similarity index 100% rename from rpc/tendermint/core/pipe.go rename to rpc/core/pipe.go diff --git a/rpc/tendermint/core/routes.go b/rpc/core/routes.go similarity index 96% rename from rpc/tendermint/core/routes.go rename to rpc/core/routes.go index 7ed18ef7f..12694ab76 100644 --- a/rpc/tendermint/core/routes.go +++ b/rpc/core/routes.go @@ -2,9 +2,9 @@ package core import ( data "github.com/tendermint/go-wire/data" - rpc "github.com/tendermint/tendermint/rpc/server" - ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" - "github.com/tendermint/tendermint/rpc/types" + rpc "github.com/tendermint/tendermint/rpc/lib/server" + ctypes "github.com/tendermint/tendermint/rpc/core/types" + "github.com/tendermint/tendermint/rpc/lib/types" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/core/status.go b/rpc/core/status.go similarity index 92% rename from rpc/tendermint/core/status.go rename to rpc/core/status.go index 9dbfff86d..7493aeb0a 100644 --- a/rpc/tendermint/core/status.go +++ b/rpc/core/status.go @@ -2,7 +2,7 @@ package core import ( data "github.com/tendermint/go-wire/data" - ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" + ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/core/tx.go b/rpc/core/tx.go similarity index 91% rename from rpc/tendermint/core/tx.go rename to rpc/core/tx.go index 7d6a2deb8..7f3cdd037 100644 --- a/rpc/tendermint/core/tx.go +++ b/rpc/core/tx.go @@ -3,7 +3,7 @@ package core import ( "fmt" - ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" + ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/state/txindex/null" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/core/types/responses.go b/rpc/core/types/responses.go similarity index 99% rename from rpc/tendermint/core/types/responses.go rename to rpc/core/types/responses.go index f88b297e3..469e71061 100644 --- a/rpc/tendermint/core/types/responses.go +++ b/rpc/core/types/responses.go @@ -7,7 +7,7 @@ import ( "github.com/tendermint/go-crypto" data "github.com/tendermint/go-wire/data" "github.com/tendermint/tendermint/p2p" - "github.com/tendermint/tendermint/rpc/types" + "github.com/tendermint/tendermint/rpc/lib/types" "github.com/tendermint/go-wire" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/core/types/responses_test.go b/rpc/core/types/responses_test.go similarity index 100% rename from rpc/tendermint/core/types/responses_test.go rename to rpc/core/types/responses_test.go diff --git a/rpc/tendermint/core/version.go b/rpc/core/version.go similarity index 100% rename from rpc/tendermint/core/version.go rename to rpc/core/version.go diff --git a/rpc/tendermint/grpc/api.go b/rpc/grpc/api.go similarity index 85% rename from rpc/tendermint/grpc/api.go rename to rpc/grpc/api.go index f28169398..fab811c2e 100644 --- a/rpc/tendermint/grpc/api.go +++ b/rpc/grpc/api.go @@ -1,7 +1,7 @@ package core_grpc import ( - core "github.com/tendermint/tendermint/rpc/tendermint/core" + core "github.com/tendermint/tendermint/rpc/core" context "golang.org/x/net/context" ) diff --git a/rpc/tendermint/grpc/client_server.go b/rpc/grpc/client_server.go similarity index 100% rename from rpc/tendermint/grpc/client_server.go rename to rpc/grpc/client_server.go diff --git a/rpc/tendermint/grpc/compile.sh b/rpc/grpc/compile.sh similarity index 100% rename from rpc/tendermint/grpc/compile.sh rename to rpc/grpc/compile.sh diff --git a/rpc/tendermint/grpc/types.pb.go b/rpc/grpc/types.pb.go similarity index 100% rename from rpc/tendermint/grpc/types.pb.go rename to rpc/grpc/types.pb.go diff --git a/rpc/tendermint/grpc/types.proto b/rpc/grpc/types.proto similarity index 100% rename from rpc/tendermint/grpc/types.proto rename to rpc/grpc/types.proto diff --git a/rpc/lib/Dockerfile b/rpc/lib/Dockerfile new file mode 100644 index 000000000..a194711bf --- /dev/null +++ b/rpc/lib/Dockerfile @@ -0,0 +1,12 @@ +FROM golang:latest + +RUN mkdir -p /go/src/github.com/tendermint/tendermint/rpc/lib +WORKDIR /go/src/github.com/tendermint/tendermint/rpc/lib + +COPY Makefile /go/src/github.com/tendermint/tendermint/rpc/lib/ +# COPY glide.yaml /go/src/github.com/tendermint/tendermint/rpc/lib/ +# COPY glide.lock /go/src/github.com/tendermint/tendermint/rpc/lib/ + +COPY . /go/src/github.com/tendermint/tendermint/rpc/lib + +RUN make get_deps diff --git a/rpc/Makefile b/rpc/lib/Makefile similarity index 100% rename from rpc/Makefile rename to rpc/lib/Makefile diff --git a/rpc/README.md b/rpc/lib/README.md similarity index 95% rename from rpc/README.md rename to rpc/lib/README.md index f1ef7485a..75531963e 100644 --- a/rpc/README.md +++ b/rpc/lib/README.md @@ -1,6 +1,6 @@ -# tendermint/rpc +# tendermint/rpc/lib -[![CircleCI](https://circleci.com/gh/tendermint/tendermint/rpc.svg?style=svg)](https://circleci.com/gh/tendermint/tendermint/rpc) +[![CircleCI](https://circleci.com/gh/tendermint/tendermint/rpc/lib.svg?style=svg)](https://circleci.com/gh/tendermint/tendermint/rpc/lib) HTTP RPC server supporting calls via uri params, jsonrpc, and jsonrpc over websockets diff --git a/rpc/circle.yml b/rpc/lib/circle.yml similarity index 100% rename from rpc/circle.yml rename to rpc/lib/circle.yml diff --git a/rpc/client/args_test.go b/rpc/lib/client/args_test.go similarity index 100% rename from rpc/client/args_test.go rename to rpc/lib/client/args_test.go diff --git a/rpc/client/http_client.go b/rpc/lib/client/http_client.go similarity index 96% rename from rpc/client/http_client.go rename to rpc/lib/client/http_client.go index 38a7f20fc..45ff8b8ac 100644 --- a/rpc/client/http_client.go +++ b/rpc/lib/client/http_client.go @@ -13,7 +13,7 @@ import ( "github.com/pkg/errors" wire "github.com/tendermint/go-wire" - types "github.com/tendermint/tendermint/rpc/types" + types "github.com/tendermint/tendermint/rpc/lib/types" ) // HTTPClient is a common interface for JSONRPCClient and URIClient. @@ -27,7 +27,7 @@ func makeHTTPDialer(remoteAddr string) (string, func(string, string) (net.Conn, parts := strings.SplitN(remoteAddr, "://", 2) var protocol, address string if len(parts) != 2 { - log.Warn("WARNING (tendermint/rpc): Please use fully formed listening addresses, including the tcp:// or unix:// prefix") + log.Warn("WARNING (tendermint/rpc/lib): Please use fully formed listening addresses, including the tcp:// or unix:// prefix") protocol = types.SocketType(remoteAddr) address = remoteAddr } else { diff --git a/rpc/client/log.go b/rpc/lib/client/log.go similarity index 100% rename from rpc/client/log.go rename to rpc/lib/client/log.go diff --git a/rpc/client/ws_client.go b/rpc/lib/client/ws_client.go similarity index 98% rename from rpc/client/ws_client.go rename to rpc/lib/client/ws_client.go index 70522265f..ad922dd68 100644 --- a/rpc/client/ws_client.go +++ b/rpc/lib/client/ws_client.go @@ -9,7 +9,7 @@ import ( "github.com/gorilla/websocket" "github.com/pkg/errors" cmn "github.com/tendermint/tmlibs/common" - types "github.com/tendermint/tendermint/rpc/types" + types "github.com/tendermint/tendermint/rpc/lib/types" wire "github.com/tendermint/go-wire" ) diff --git a/rpc/rpc_test.go b/rpc/lib/rpc_test.go similarity index 97% rename from rpc/rpc_test.go rename to rpc/lib/rpc_test.go index ef8832a88..2ce19fa75 100644 --- a/rpc/rpc_test.go +++ b/rpc/lib/rpc_test.go @@ -13,9 +13,9 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" wire "github.com/tendermint/go-wire" - client "github.com/tendermint/tendermint/rpc/client" - server "github.com/tendermint/tendermint/rpc/server" - types "github.com/tendermint/tendermint/rpc/types" + client "github.com/tendermint/tendermint/rpc/lib/client" + server "github.com/tendermint/tendermint/rpc/lib/server" + types "github.com/tendermint/tendermint/rpc/lib/types" ) // Client and Server should work over tcp or unix sockets diff --git a/rpc/server/handlers.go b/rpc/lib/server/handlers.go similarity index 99% rename from rpc/server/handlers.go rename to rpc/lib/server/handlers.go index a0dbc487a..d7dffd402 100644 --- a/rpc/server/handlers.go +++ b/rpc/lib/server/handlers.go @@ -15,7 +15,7 @@ import ( "github.com/gorilla/websocket" "github.com/pkg/errors" wire "github.com/tendermint/go-wire" - types "github.com/tendermint/tendermint/rpc/types" + types "github.com/tendermint/tendermint/rpc/lib/types" cmn "github.com/tendermint/tmlibs/common" events "github.com/tendermint/tmlibs/events" ) diff --git a/rpc/server/http_params.go b/rpc/lib/server/http_params.go similarity index 100% rename from rpc/server/http_params.go rename to rpc/lib/server/http_params.go diff --git a/rpc/server/http_server.go b/rpc/lib/server/http_server.go similarity index 95% rename from rpc/server/http_server.go rename to rpc/lib/server/http_server.go index b30bc3606..ae0923c39 100644 --- a/rpc/server/http_server.go +++ b/rpc/lib/server/http_server.go @@ -12,7 +12,7 @@ import ( "time" "github.com/pkg/errors" - types "github.com/tendermint/tendermint/rpc/types" + types "github.com/tendermint/tendermint/rpc/lib/types" ) func StartHTTPServer(listenAddr string, handler http.Handler) (listener net.Listener, err error) { @@ -20,7 +20,7 @@ func StartHTTPServer(listenAddr string, handler http.Handler) (listener net.List var proto, addr string parts := strings.SplitN(listenAddr, "://", 2) if len(parts) != 2 { - log.Warn("WARNING (tendermint/rpc): Please use fully formed listening addresses, including the tcp:// or unix:// prefix") + log.Warn("WARNING (tendermint/rpc/lib): Please use fully formed listening addresses, including the tcp:// or unix:// prefix") // we used to allow addrs without tcp/unix prefix by checking for a colon // TODO: Deprecate proto = types.SocketType(listenAddr) diff --git a/rpc/server/log.go b/rpc/lib/server/log.go similarity index 100% rename from rpc/server/log.go rename to rpc/lib/server/log.go diff --git a/rpc/test/data.json b/rpc/lib/test/data.json similarity index 100% rename from rpc/test/data.json rename to rpc/lib/test/data.json diff --git a/rpc/test/integration_test.sh b/rpc/lib/test/integration_test.sh similarity index 100% rename from rpc/test/integration_test.sh rename to rpc/lib/test/integration_test.sh diff --git a/rpc/test/main.go b/rpc/lib/test/main.go similarity index 90% rename from rpc/test/main.go rename to rpc/lib/test/main.go index ea91fcfd0..8e63cdc38 100644 --- a/rpc/test/main.go +++ b/rpc/lib/test/main.go @@ -5,7 +5,7 @@ import ( "net/http" cmn "github.com/tendermint/tmlibs/common" - rpcserver "github.com/tendermint/tendermint/rpc/server" + rpcserver "github.com/tendermint/tendermint/rpc/lib/server" ) var routes = map[string]*rpcserver.RPCFunc{ diff --git a/rpc/types/types.go b/rpc/lib/types/types.go similarity index 100% rename from rpc/types/types.go rename to rpc/lib/types/types.go diff --git a/rpc/version.go b/rpc/lib/version.go similarity index 100% rename from rpc/version.go rename to rpc/lib/version.go diff --git a/rpc/tendermint/test/client_test.go b/rpc/test/client_test.go similarity index 98% rename from rpc/tendermint/test/client_test.go rename to rpc/test/client_test.go index 11ee61a56..67c88356d 100644 --- a/rpc/tendermint/test/client_test.go +++ b/rpc/test/client_test.go @@ -12,9 +12,9 @@ import ( "github.com/stretchr/testify/require" abci "github.com/tendermint/abci/types" - rpc "github.com/tendermint/tendermint/rpc/client" - "github.com/tendermint/tendermint/rpc/tendermint/core" - ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" + rpc "github.com/tendermint/tendermint/rpc/lib/client" + "github.com/tendermint/tendermint/rpc/core" + ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/state/txindex/null" "github.com/tendermint/tendermint/types" . "github.com/tendermint/tmlibs/common" diff --git a/rpc/tendermint/test/grpc_test.go b/rpc/test/grpc_test.go similarity index 88% rename from rpc/tendermint/test/grpc_test.go rename to rpc/test/grpc_test.go index 4fcc3e856..4935a09d9 100644 --- a/rpc/tendermint/test/grpc_test.go +++ b/rpc/test/grpc_test.go @@ -6,7 +6,7 @@ import ( "golang.org/x/net/context" "github.com/stretchr/testify/require" - "github.com/tendermint/tendermint/rpc/tendermint/grpc" + "github.com/tendermint/tendermint/rpc/grpc" ) //------------------------------------------- diff --git a/rpc/tendermint/test/helpers.go b/rpc/test/helpers.go similarity index 96% rename from rpc/tendermint/test/helpers.go rename to rpc/test/helpers.go index 4e281f8c3..311f05980 100644 --- a/rpc/tendermint/test/helpers.go +++ b/rpc/test/helpers.go @@ -18,9 +18,9 @@ import ( "github.com/tendermint/tendermint/config/tendermint_test" nm "github.com/tendermint/tendermint/node" "github.com/tendermint/tendermint/proxy" - client "github.com/tendermint/tendermint/rpc/client" - ctypes "github.com/tendermint/tendermint/rpc/tendermint/core/types" - core_grpc "github.com/tendermint/tendermint/rpc/tendermint/grpc" + client "github.com/tendermint/tendermint/rpc/lib/client" + ctypes "github.com/tendermint/tendermint/rpc/core/types" + core_grpc "github.com/tendermint/tendermint/rpc/grpc" "github.com/tendermint/tendermint/types" ) diff --git a/rpc/tendermint/test/main_test.go b/rpc/test/main_test.go similarity index 100% rename from rpc/tendermint/test/main_test.go rename to rpc/test/main_test.go diff --git a/test/app/grpc_client.go b/test/app/grpc_client.go index 7d55dcd71..e43b8ae39 100644 --- a/test/app/grpc_client.go +++ b/test/app/grpc_client.go @@ -8,7 +8,7 @@ import ( "golang.org/x/net/context" "github.com/tendermint/go-wire" - "github.com/tendermint/tendermint/rpc/tendermint/grpc" + "github.com/tendermint/tendermint/rpc/grpc" ) var grpcAddr = "tcp://localhost:36656" From 1310c7264750efa8939680536098ded9f9e8df74 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Wed, 26 Apr 2017 20:06:45 -0400 Subject: [PATCH 214/309] version bump and changelog --- CHANGELOG.md | 24 ++++++++++++++++++++++++ version/version.go | 6 +++--- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f74987fff..93fde7388 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,29 @@ # Changelog +## 0.10.0 (April 26, 2017) + +BREAKING CHANGES: + +- New JSON encoding for `go-crypto` types (using `go-wire/data`): + +``` +"pub_key": { + "type": "ed25519", + "data": "83DDF8775937A4A12A2704269E2729FCFCD491B933C4B0A7FFE37FE41D7760D0" +} +``` + +IMPROVEMENTS: + +- Merge `tendermint/go-p2p -> tendermint/tendermint/p2p` and `tendermint/go-rpc -> tendermint/tendermint/rpc/lib` +- Update paths for grand repo merge: + - `go-common -> tmlibs/common` + - `go-data -> go-wire/data` + - All other `go-*` libs, except `go-crypto`, merged under `tmlibs` +- Return HTTP status codes with errors for RPC responses +- Use `.Wrap()` and `.Unwarp()` instead of eg. `PubKeyS` for `go-crypto` types + + ## 0.9.2 (April 26, 2017) BUG FIXES: diff --git a/version/version.go b/version/version.go index b35a2daee..fab2a05b7 100644 --- a/version/version.go +++ b/version/version.go @@ -1,7 +1,7 @@ package version const Maj = "0" -const Min = "9" -const Fix = "2" +const Min = "10" +const Fix = "0" -const Version = "0.9.2" +const Version = "0.10.0" From 842609ddcb42fa5024bed0002e0446862a85e316 Mon Sep 17 00:00:00 2001 From: Adrian Brink Date: Thu, 27 Apr 2017 19:39:06 +0200 Subject: [PATCH 215/309] Send InitChain message from ABCI to Core on Genesis InitChain is send from the ABCI to the Core node when the ABCI app has no blocks stored. --- consensus/replay.go | 6 ++++++ types/protobuf.go | 8 ++++++++ 2 files changed, 14 insertions(+) diff --git a/consensus/replay.go b/consensus/replay.go index 5bc0c2611..0335ad153 100644 --- a/consensus/replay.go +++ b/consensus/replay.go @@ -257,6 +257,12 @@ func (h *Handshaker) ReplayBlocks(appHash []byte, appBlockHeight int, proxyApp p stateBlockHeight := h.state.LastBlockHeight log.Notice("ABCI Replay Blocks", "appHeight", appBlockHeight, "storeHeight", storeBlockHeight, "stateHeight", stateBlockHeight) + // If appBlockHeight == 0 it means that we are at genesis and hence should send InitChain + if appBlockHeight == 0 { + validators := types.TM2PB.Validators(h.state.Validators) + proxyApp.Consensus().InitChainSync(validators) + } + // First handle edge cases and constraints on the storeBlockHeight if storeBlockHeight == 0 { return appHash, h.checkAppHash(appHash) diff --git a/types/protobuf.go b/types/protobuf.go index 41b4c54bb..59994fea7 100644 --- a/types/protobuf.go +++ b/types/protobuf.go @@ -42,3 +42,11 @@ func (tm2pb) Validator(val *Validator) *types.Validator { Power: uint64(val.VotingPower), } } + +func (tm2pb) Validators(vals *ValidatorSet) []*types.Validator { + validators := make([]*types.Validator, len(vals.Validators)) + for i, val := range vals.Validators { + validators[i] = TM2PB.Validator(val) + } + return validators +} From 495283e2d4700d48bd9917810ba45fcbff59c370 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Thu, 27 Apr 2017 18:29:38 -0400 Subject: [PATCH 216/309] fix replay tests and update test wals for InitChain --- consensus/replay.go | 8 +- consensus/replay_test.go | 20 +++-- consensus/test_data/build.sh | 18 ++-- consensus/test_data/empty_block.cswal | 18 ++-- consensus/test_data/many_blocks.cswal | 118 ++++++++++++------------- consensus/test_data/small_block1.cswal | 18 ++-- consensus/test_data/small_block2.cswal | 27 +++--- 7 files changed, 114 insertions(+), 113 deletions(-) diff --git a/consensus/replay.go b/consensus/replay.go index 0335ad153..ecb29e3d5 100644 --- a/consensus/replay.go +++ b/consensus/replay.go @@ -215,8 +215,6 @@ func (h *Handshaker) NBlocks() int { return h.nBlocks } -var ErrReplayLastBlockTimeout = errors.New("Timed out waiting for last block to be replayed") - // TODO: retry the handshake/replay if it fails ? func (h *Handshaker) Handshake(proxyApp proxy.AppConns) error { // handshake is done via info request on the query conn @@ -234,11 +232,7 @@ func (h *Handshaker) Handshake(proxyApp proxy.AppConns) error { // replay blocks up to the latest in the blockstore _, err = h.ReplayBlocks(appHash, blockHeight, proxyApp) - if err == ErrReplayLastBlockTimeout { - log.Warn("Failed to sync via handshake. Trying other means. If they fail, please increase the timeout_handshake parameter") - return nil - - } else if err != nil { + if err != nil { return errors.New(cmn.Fmt("Error on replay: %v", err)) } diff --git a/consensus/replay_test.go b/consensus/replay_test.go index e486af83e..e6335f699 100644 --- a/consensus/replay_test.go +++ b/consensus/replay_test.go @@ -53,7 +53,7 @@ var baseStepChanges = []int{3, 6, 8} var testCases = []*testCase{ newTestCase("empty_block", baseStepChanges), // empty block (has 1 block part) newTestCase("small_block1", baseStepChanges), // small block with txs in 1 block part - newTestCase("small_block2", []int{3, 10, 12}), // small block with txs across 5 smaller block parts + newTestCase("small_block2", []int{3, 11, 13}), // small block with txs across 6 smaller block parts } type testCase struct { @@ -386,6 +386,10 @@ func buildAppStateFromChain(proxyApp proxy.AppConns, if _, err := proxyApp.Start(); err != nil { panic(err) } + + validators := types.TM2PB.Validators(state.Validators) + proxyApp.Consensus().InitChainSync(validators) + defer proxyApp.Stop() switch mode { case 0: @@ -417,6 +421,9 @@ func buildTMStateFromChain(config *viper.Viper, state *sm.State, chain []*types. } defer proxyApp.Stop() + validators := types.TM2PB.Validators(state.Validators) + proxyApp.Consensus().InitChainSync(validators) + var latestAppHash []byte switch mode { @@ -604,13 +611,10 @@ func makeBlockchain(t *testing.T, chainID string, nBlocks int, privVal *types.Pr // fresh state and mock store func stateAndStore(config *viper.Viper, pubKey crypto.PubKey) (*sm.State, *mockBlockStore) { stateDB := dbm.NewMemDB() - return sm.MakeGenesisState(stateDB, &types.GenesisDoc{ - ChainID: config.GetString("chain_id"), - Validators: []types.GenesisValidator{ - types.GenesisValidator{pubKey, 10000, "test"}, - }, - AppHash: nil, - }), NewMockBlockStore(config) + + state := sm.MakeGenesisStateFromFile(stateDB, config.GetString("genesis_file")) + store := NewMockBlockStore(config) + return state, store } //---------------------------------- diff --git a/consensus/test_data/build.sh b/consensus/test_data/build.sh index 93a74b8ba..d50c26296 100755 --- a/consensus/test_data/build.sh +++ b/consensus/test_data/build.sh @@ -13,19 +13,21 @@ fi # TODO: eventually we should replace with `tendermint init --test` DIR_TO_COPY=$HOME/.tendermint_test/consensus_state_test -rm -rf "$HOME/.tendermint" -cp -r "$DIR_TO_COPY" "$HOME/.tendermint" +TMHOME="$HOME/.tendermint" +rm -rf "$TMHOME" +cp -r "$DIR_TO_COPY" "$TMHOME" +cp $TMHOME/config.toml $TMHOME/config.toml.bak function reset(){ - rm -rf "$HOME/.tendermint/data" - tendermint unsafe_reset_priv_validator + tendermint unsafe_reset_all + cp $TMHOME/config.toml.bak $TMHOME/config.toml } reset # empty block function empty_block(){ -tendermint node --proxy_app=dummy &> /dev/null & +tendermint node --proxy_app=persistent_dummy &> /dev/null & sleep 5 killall tendermint @@ -41,7 +43,7 @@ reset function many_blocks(){ bash scripts/txs/random.sh 1000 36657 &> /dev/null & PID=$! -tendermint node --proxy_app=dummy &> /dev/null & +tendermint node --proxy_app=persistent_dummy &> /dev/null & sleep 7 killall tendermint kill -9 $PID @@ -56,7 +58,7 @@ reset function small_block1(){ bash scripts/txs/random.sh 1000 36657 &> /dev/null & PID=$! -tendermint node --proxy_app=dummy &> /dev/null & +tendermint node --proxy_app=persistent_dummy &> /dev/null & sleep 10 killall tendermint kill -9 $PID @@ -73,7 +75,7 @@ echo "" >> ~/.tendermint/config.toml echo "block_part_size = 512" >> ~/.tendermint/config.toml bash scripts/txs/random.sh 1000 36657 &> /dev/null & PID=$! -tendermint node --proxy_app=dummy &> /dev/null & +tendermint node --proxy_app=persistent_dummy &> /dev/null & sleep 5 killall tendermint kill -9 $PID diff --git a/consensus/test_data/empty_block.cswal b/consensus/test_data/empty_block.cswal index aa5b232c9..a7e5e79e4 100644 --- a/consensus/test_data/empty_block.cswal +++ b/consensus/test_data/empty_block.cswal @@ -1,10 +1,10 @@ #ENDHEIGHT: 0 -{"time":"2016-12-18T05:05:33.502Z","msg":[3,{"duration":974084551,"height":1,"round":0,"step":1}]} -{"time":"2016-12-18T05:05:33.505Z","msg":[1,{"height":1,"round":0,"step":"RoundStepPropose"}]} -{"time":"2016-12-18T05:05:33.505Z","msg":[2,{"msg":[17,{"Proposal":{"height":1,"round":0,"block_parts_header":{"total":1,"hash":"71D2DA2336A9F84C22A28FF6C67F35F3478FC0AF"},"pol_round":-1,"pol_block_id":{"hash":"","parts":{"total":0,"hash":""}},"signature":[1,"62C0F2BCCB491399EEDAF8E85837ADDD4E25BAB7A84BFC4F0E88594531FBC6D4755DEC7E6427F04AD7EB8BB89502762AB4380C7BBA93A4C297E6180EC78E3504"]}}],"peer_key":""}]} -{"time":"2016-12-18T05:05:33.506Z","msg":[2,{"msg":[19,{"Height":1,"Round":0,"Part":{"index":0,"bytes":"0101010F74656E6465726D696E745F74657374010114914148D83E0DC00000000000000114354594CBFC1A7BCA1AD0050ED6AA010023EADA390001000100000000","proof":{"aunts":[]}}}],"peer_key":""}]} -{"time":"2016-12-18T05:05:33.508Z","msg":[1,{"height":1,"round":0,"step":"RoundStepPrevote"}]} -{"time":"2016-12-18T05:05:33.508Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":1,"round":0,"type":1,"block_id":{"hash":"3E83DF89A01C5F104912E095F32451C202F34717","parts":{"total":1,"hash":"71D2DA2336A9F84C22A28FF6C67F35F3478FC0AF"}},"signature":[1,"B64D0BB64B2E9AAFDD4EBEA679644F77AE774D69E3E2E1B042AB15FE4F84B1427AC6C8A25AFF58EA22011AE567FEA49D2EE7354382E915AD85BF40C58FA6130C"]}}],"peer_key":""}]} -{"time":"2016-12-18T05:05:33.509Z","msg":[1,{"height":1,"round":0,"step":"RoundStepPrecommit"}]} -{"time":"2016-12-18T05:05:33.509Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":1,"round":0,"type":2,"block_id":{"hash":"3E83DF89A01C5F104912E095F32451C202F34717","parts":{"total":1,"hash":"71D2DA2336A9F84C22A28FF6C67F35F3478FC0AF"}},"signature":[1,"D83E968392D1BF09821E0D05079DAB5491CABD89BE128BD1CF573ED87148BA84667A56C0A069EFC90760F25EDAC62BC324DBB12EA63F44E6CB2D3500FE5E640F"]}}],"peer_key":""}]} -{"time":"2016-12-18T05:05:33.509Z","msg":[1,{"height":1,"round":0,"step":"RoundStepCommit"}]} +{"time":"2017-04-27T22:24:01.346Z","msg":[3,{"duration":972946821,"height":1,"round":0,"step":1}]} +{"time":"2017-04-27T22:24:01.349Z","msg":[1,{"height":1,"round":0,"step":"RoundStepPropose"}]} +{"time":"2017-04-27T22:24:01.349Z","msg":[2,{"msg":[17,{"Proposal":{"height":1,"round":0,"block_parts_header":{"total":1,"hash":"ACED4A95DDEBD24E66A681F7EAB4CA22C4B8546D"},"pol_round":-1,"pol_block_id":{"hash":"","parts":{"total":0,"hash":""}},"signature":[1,"E785764AED6D92D7CC65C0A3A4ED9C8465198A05142C3E6C7F3EF601FDCD3A604900B77B7B87C046221EF99FD038A960398385BD5BBAA50EE4F86DE757B8F704"]}}],"peer_key":""}]} +{"time":"2017-04-27T22:24:01.350Z","msg":[2,{"msg":[19,{"Height":1,"Round":0,"Part":{"index":0,"bytes":"0101010F74656E6465726D696E745F74657374010114B96165CF4496C00000000000000114354594CBFC1A7BCA1AD0050ED6AA010023EADA390001000100000000","proof":{"aunts":[]}}}],"peer_key":""}]} +{"time":"2017-04-27T22:24:01.351Z","msg":[1,{"height":1,"round":0,"step":"RoundStepPrevote"}]} +{"time":"2017-04-27T22:24:01.351Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":1,"round":0,"type":1,"block_id":{"hash":"F3BBFBE7E4A5D619E2C498C3D1B912883786DD71","parts":{"total":1,"hash":"ACED4A95DDEBD24E66A681F7EAB4CA22C4B8546D"}},"signature":[1,"35C937C78D061ECDC3770982A1330C9AA7F6FEF00835C43DEB50B8FCF69A3EEF221E675EE5E469114F64E4FBBABA414EB9170E1025FC47D3F0EADE46767D2E00"]}}],"peer_key":""}]} +{"time":"2017-04-27T22:24:01.352Z","msg":[1,{"height":1,"round":0,"step":"RoundStepPrecommit"}]} +{"time":"2017-04-27T22:24:01.352Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":1,"round":0,"type":2,"block_id":{"hash":"F3BBFBE7E4A5D619E2C498C3D1B912883786DD71","parts":{"total":1,"hash":"ACED4A95DDEBD24E66A681F7EAB4CA22C4B8546D"}},"signature":[1,"D1A7D27FCD5D352F3A3EDA8DE368520BC5B796662E32BCD8D91CDB8209A88DAF37CB7C4C93143D3C12B37C1435229268098CFFD0AD1400D88DA7606454692301"]}}],"peer_key":""}]} +{"time":"2017-04-27T22:24:01.352Z","msg":[1,{"height":1,"round":0,"step":"RoundStepCommit"}]} diff --git a/consensus/test_data/many_blocks.cswal b/consensus/test_data/many_blocks.cswal index fd103cb1e..9ceee2cfd 100644 --- a/consensus/test_data/many_blocks.cswal +++ b/consensus/test_data/many_blocks.cswal @@ -1,65 +1,65 @@ #ENDHEIGHT: 0 -{"time":"2017-02-17T23:54:19.013Z","msg":[3,{"duration":969121813,"height":1,"round":0,"step":1}]} -{"time":"2017-02-17T23:54:19.014Z","msg":[1,{"height":1,"round":0,"step":"RoundStepPropose"}]} -{"time":"2017-02-17T23:54:19.014Z","msg":[2,{"msg":[17,{"Proposal":{"height":1,"round":0,"block_parts_header":{"total":1,"hash":"2E32C8D500E936D27A47FCE3FF4BE7C1AFB3FAE1"},"pol_round":-1,"pol_block_id":{"hash":"","parts":{"total":0,"hash":""}},"signature":[1,"105A5A834E9AE2FA2191CAB5CB20D63594BA7859BD3EB92F055C8A35476D71F0D89F9FD5B0FF030D021533C71A81BF6E8F026BF4A37FC637CF38CA35291A9D00"]}}],"peer_key":""}]} -{"time":"2017-02-17T23:54:19.015Z","msg":[2,{"msg":[19,{"Height":1,"Round":0,"Part":{"index":0,"bytes":"0101010F74656E6465726D696E745F74657374010114A438480B084B40017600000000011477134726D7D54ABC03516888951EBC652413B20B0114354594CBFC1A7BCA1AD0050ED6AA010023EADA3900010176011A3631363236333634333133313344363436333632363133313331011A3631363236333634333133323344363436333632363133313332011A3631363236333634333133333344363436333632363133313333011A3631363236333634333133343344363436333632363133313334011A3631363236333634333133353344363436333632363133313335011A3631363236333634333133363344363436333632363133313336011A3631363236333634333133373344363436333632363133313337011A3631363236333634333133383344363436333632363133313338011A3631363236333634333133393344363436333632363133313339011A3631363236333634333233303344363436333632363133323330011A3631363236333634333233313344363436333632363133323331011A3631363236333634333233323344363436333632363133323332011A3631363236333634333233333344363436333632363133323333011A3631363236333634333233343344363436333632363133323334011A3631363236333634333233353344363436333632363133323335011A3631363236333634333233363344363436333632363133323336011A3631363236333634333233373344363436333632363133323337011A3631363236333634333233383344363436333632363133323338011A3631363236333634333233393344363436333632363133323339011A3631363236333634333333303344363436333632363133333330011A3631363236333634333333313344363436333632363133333331011A3631363236333634333333323344363436333632363133333332011A3631363236333634333333333344363436333632363133333333011A3631363236333634333333343344363436333632363133333334011A3631363236333634333333353344363436333632363133333335011A3631363236333634333333363344363436333632363133333336011A3631363236333634333333373344363436333632363133333337011A3631363236333634333333383344363436333632363133333338011A3631363236333634333333393344363436333632363133333339011A3631363236333634333433303344363436333632363133343330011A3631363236333634333433313344363436333632363133343331011A3631363236333634333433323344363436333632363133343332011A3631363236333634333433333344363436333632363133343333011A3631363236333634333433343344363436333632363133343334011A3631363236333634333433353344363436333632363133343335011A3631363236333634333433363344363436333632363133343336011A3631363236333634333433373344363436333632363133343337011A3631363236333634333433383344363436333632363133343338011A3631363236333634333433393344363436333632363133343339011A3631363236333634333533303344363436333632363133353330011A3631363236333634333533313344363436333632363133353331011A3631363236333634333533323344363436333632363133353332011A3631363236333634333533333344363436333632363133353333011A3631363236333634333533343344363436333632363133353334011A3631363236333634333533353344363436333632363133353335011A3631363236333634333533363344363436333632363133353336011A3631363236333634333533373344363436333632363133353337011A3631363236333634333533383344363436333632363133353338011A3631363236333634333533393344363436333632363133353339011A3631363236333634333633303344363436333632363133363330011A3631363236333634333633313344363436333632363133363331011A3631363236333634333633323344363436333632363133363332011A3631363236333634333633333344363436333632363133363333011A3631363236333634333633343344363436333632363133363334011A3631363236333634333633353344363436333632363133363335011A3631363236333634333633363344363436333632363133363336011A3631363236333634333633373344363436333632363133363337011A3631363236333634333633383344363436333632363133363338011A3631363236333634333633393344363436333632363133363339011A3631363236333634333733303344363436333632363133373330011A3631363236333634333733313344363436333632363133373331011A3631363236333634333733323344363436333632363133373332011A3631363236333634333733333344363436333632363133373333011A3631363236333634333733343344363436333632363133373334011A3631363236333634333733353344363436333632363133373335011A3631363236333634333733363344363436333632363133373336011A3631363236333634333733373344363436333632363133373337011A3631363236333634333733383344363436333632363133373338011A3631363236333634333733393344363436333632363133373339011A3631363236333634333833303344363436333632363133383330011A3631363236333634333833313344363436333632363133383331011A3631363236333634333833323344363436333632363133383332011A3631363236333634333833333344363436333632363133383333011A3631363236333634333833343344363436333632363133383334011A3631363236333634333833353344363436333632363133383335011A3631363236333634333833363344363436333632363133383336011A3631363236333634333833373344363436333632363133383337011A3631363236333634333833383344363436333632363133383338011A3631363236333634333833393344363436333632363133383339011A3631363236333634333933303344363436333632363133393330011A3631363236333634333933313344363436333632363133393331011A3631363236333634333933323344363436333632363133393332011A3631363236333634333933333344363436333632363133393333011A3631363236333634333933343344363436333632363133393334011A3631363236333634333933353344363436333632363133393335011A3631363236333634333933363344363436333632363133393336011A3631363236333634333933373344363436333632363133393337011A3631363236333634333933383344363436333632363133393338011A3631363236333634333933393344363436333632363133393339011E363136323633363433313330333033443634363336323631333133303330011E363136323633363433313330333133443634363336323631333133303331011E363136323633363433313330333233443634363336323631333133303332011E363136323633363433313330333333443634363336323631333133303333011E363136323633363433313330333433443634363336323631333133303334011E363136323633363433313330333533443634363336323631333133303335011E363136323633363433313330333633443634363336323631333133303336011E363136323633363433313330333733443634363336323631333133303337011E363136323633363433313330333833443634363336323631333133303338011E363136323633363433313330333933443634363336323631333133303339011E363136323633363433313331333033443634363336323631333133313330011E363136323633363433313331333133443634363336323631333133313331011E363136323633363433313331333233443634363336323631333133313332011E363136323633363433313331333333443634363336323631333133313333011E363136323633363433313331333433443634363336323631333133313334011E363136323633363433313331333533443634363336323631333133313335011E363136323633363433313331333633443634363336323631333133313336011E363136323633363433313331333733443634363336323631333133313337011E363136323633363433313331333833443634363336323631333133313338011E363136323633363433313331333933443634363336323631333133313339011E363136323633363433313332333033443634363336323631333133323330011E363136323633363433313332333133443634363336323631333133323331011E363136323633363433313332333233443634363336323631333133323332011E363136323633363433313332333333443634363336323631333133323333011E363136323633363433313332333433443634363336323631333133323334011E363136323633363433313332333533443634363336323631333133323335011E363136323633363433313332333633443634363336323631333133323336011E363136323633363433313332333733443634363336323631333133323337011E3631363236333634333133323338334436343633363236313331333233380100000000","proof":{"aunts":[]}}}],"peer_key":""}]} -{"time":"2017-02-17T23:54:19.016Z","msg":[1,{"height":1,"round":0,"step":"RoundStepPrevote"}]} -{"time":"2017-02-17T23:54:19.016Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":1,"round":0,"type":1,"block_id":{"hash":"3F32EE37F9EA674A2173CAD651836A8EE628B5C7","parts":{"total":1,"hash":"2E32C8D500E936D27A47FCE3FF4BE7C1AFB3FAE1"}},"signature":[1,"31851DA0008AFF4223245EDFCCF1AD7BE96F8D66F8BD02D87F06B2F800A9405413861877D08798F0F6297D29936F5380B352C82212D2EC6F0E194A8C22A1EB0E"]}}],"peer_key":""}]} -{"time":"2017-02-17T23:54:19.016Z","msg":[1,{"height":1,"round":0,"step":"RoundStepPrecommit"}]} -{"time":"2017-02-17T23:54:19.016Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":1,"round":0,"type":2,"block_id":{"hash":"3F32EE37F9EA674A2173CAD651836A8EE628B5C7","parts":{"total":1,"hash":"2E32C8D500E936D27A47FCE3FF4BE7C1AFB3FAE1"}},"signature":[1,"2B1070A5AB9305612A3AE74A8036D82B5E49E0DBBFBC7D723DB985CC8A8E72A52FF8E34D85273FEB8B901945CA541FA5142C3C4D43A04E9205ACECF53FD19B01"]}}],"peer_key":""}]} -{"time":"2017-02-17T23:54:19.017Z","msg":[1,{"height":1,"round":0,"step":"RoundStepCommit"}]} +{"time":"2017-04-27T22:24:06.395Z","msg":[3,{"duration":974643085,"height":1,"round":0,"step":1}]} +{"time":"2017-04-27T22:24:06.397Z","msg":[1,{"height":1,"round":0,"step":"RoundStepPropose"}]} +{"time":"2017-04-27T22:24:06.397Z","msg":[2,{"msg":[17,{"Proposal":{"height":1,"round":0,"block_parts_header":{"total":1,"hash":"218DFAADA5F4A3E0DC3060379E80C45FBB5A0442"},"pol_round":-1,"pol_block_id":{"hash":"","parts":{"total":0,"hash":""}},"signature":[1,"B361A5602D9C36058CFE7C5F2E1B6E9DA6D1FAD5F1FBD50F03C1DCA3B80F8374018D04B8785AEC8B464E792189F832BFF5C0B82CCE93D6B3F9B04DE8DBCA1D09"]}}],"peer_key":""}]} +{"time":"2017-04-27T22:24:06.397Z","msg":[2,{"msg":[19,{"Height":1,"Round":0,"Part":{"index":0,"bytes":"0101010F74656E6465726D696E745F74657374010114B96166FC26F4C0015F0000000001140830F265BD1DF6413337508DE45DB36552AE9A520114354594CBFC1A7BCA1AD0050ED6AA010023EADA390001015F011636313632363336343339334436343633363236313339011A3631363236333634333133303344363436333632363133313330011A3631363236333634333133313344363436333632363133313331011A3631363236333634333133323344363436333632363133313332011A3631363236333634333133333344363436333632363133313333011A3631363236333634333133343344363436333632363133313334011A3631363236333634333133353344363436333632363133313335011A3631363236333634333133363344363436333632363133313336011A3631363236333634333133373344363436333632363133313337011A3631363236333634333133383344363436333632363133313338011A3631363236333634333133393344363436333632363133313339011A3631363236333634333233303344363436333632363133323330011A3631363236333634333233313344363436333632363133323331011A3631363236333634333233323344363436333632363133323332011A3631363236333634333233333344363436333632363133323333011A3631363236333634333233343344363436333632363133323334011A3631363236333634333233353344363436333632363133323335011A3631363236333634333233363344363436333632363133323336011A3631363236333634333233373344363436333632363133323337011A3631363236333634333233383344363436333632363133323338011A3631363236333634333233393344363436333632363133323339011A3631363236333634333333303344363436333632363133333330011A3631363236333634333333313344363436333632363133333331011A3631363236333634333333323344363436333632363133333332011A3631363236333634333333333344363436333632363133333333011A3631363236333634333333343344363436333632363133333334011A3631363236333634333333353344363436333632363133333335011A3631363236333634333333363344363436333632363133333336011A3631363236333634333333373344363436333632363133333337011A3631363236333634333333383344363436333632363133333338011A3631363236333634333333393344363436333632363133333339011A3631363236333634333433303344363436333632363133343330011A3631363236333634333433313344363436333632363133343331011A3631363236333634333433323344363436333632363133343332011A3631363236333634333433333344363436333632363133343333011A3631363236333634333433343344363436333632363133343334011A3631363236333634333433353344363436333632363133343335011A3631363236333634333433363344363436333632363133343336011A3631363236333634333433373344363436333632363133343337011A3631363236333634333433383344363436333632363133343338011A3631363236333634333433393344363436333632363133343339011A3631363236333634333533303344363436333632363133353330011A3631363236333634333533313344363436333632363133353331011A3631363236333634333533323344363436333632363133353332011A3631363236333634333533333344363436333632363133353333011A3631363236333634333533343344363436333632363133353334011A3631363236333634333533353344363436333632363133353335011A3631363236333634333533363344363436333632363133353336011A3631363236333634333533373344363436333632363133353337011A3631363236333634333533383344363436333632363133353338011A3631363236333634333533393344363436333632363133353339011A3631363236333634333633303344363436333632363133363330011A3631363236333634333633313344363436333632363133363331011A3631363236333634333633323344363436333632363133363332011A3631363236333634333633333344363436333632363133363333011A3631363236333634333633343344363436333632363133363334011A3631363236333634333633353344363436333632363133363335011A3631363236333634333633363344363436333632363133363336011A3631363236333634333633373344363436333632363133363337011A3631363236333634333633383344363436333632363133363338011A3631363236333634333633393344363436333632363133363339011A3631363236333634333733303344363436333632363133373330011A3631363236333634333733313344363436333632363133373331011A3631363236333634333733323344363436333632363133373332011A3631363236333634333733333344363436333632363133373333011A3631363236333634333733343344363436333632363133373334011A3631363236333634333733353344363436333632363133373335011A3631363236333634333733363344363436333632363133373336011A3631363236333634333733373344363436333632363133373337011A3631363236333634333733383344363436333632363133373338011A3631363236333634333733393344363436333632363133373339011A3631363236333634333833303344363436333632363133383330011A3631363236333634333833313344363436333632363133383331011A3631363236333634333833323344363436333632363133383332011A3631363236333634333833333344363436333632363133383333011A3631363236333634333833343344363436333632363133383334011A3631363236333634333833353344363436333632363133383335011A3631363236333634333833363344363436333632363133383336011A3631363236333634333833373344363436333632363133383337011A3631363236333634333833383344363436333632363133383338011A3631363236333634333833393344363436333632363133383339011A3631363236333634333933303344363436333632363133393330011A3631363236333634333933313344363436333632363133393331011A3631363236333634333933323344363436333632363133393332011A3631363236333634333933333344363436333632363133393333011A3631363236333634333933343344363436333632363133393334011A3631363236333634333933353344363436333632363133393335011A3631363236333634333933363344363436333632363133393336011A3631363236333634333933373344363436333632363133393337011A3631363236333634333933383344363436333632363133393338011A3631363236333634333933393344363436333632363133393339011E363136323633363433313330333033443634363336323631333133303330011E363136323633363433313330333133443634363336323631333133303331011E363136323633363433313330333233443634363336323631333133303332011E3631363236333634333133303333334436343633363236313331333033330100000000","proof":{"aunts":[]}}}],"peer_key":""}]} +{"time":"2017-04-27T22:24:06.399Z","msg":[1,{"height":1,"round":0,"step":"RoundStepPrevote"}]} +{"time":"2017-04-27T22:24:06.399Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":1,"round":0,"type":1,"block_id":{"hash":"B83D2AF62DBCA00412CD21152645411609DB51D4","parts":{"total":1,"hash":"218DFAADA5F4A3E0DC3060379E80C45FBB5A0442"}},"signature":[1,"50FC03CD17799A619D2AD2AE1004D44DDB774D37D1CBB085240C28E08791FCCC8DBAFACEE4BA967681D331B32E88AC6DE4862DD20D39999C20C6D0DFAF155C02"]}}],"peer_key":""}]} +{"time":"2017-04-27T22:24:06.400Z","msg":[1,{"height":1,"round":0,"step":"RoundStepPrecommit"}]} +{"time":"2017-04-27T22:24:06.400Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":1,"round":0,"type":2,"block_id":{"hash":"B83D2AF62DBCA00412CD21152645411609DB51D4","parts":{"total":1,"hash":"218DFAADA5F4A3E0DC3060379E80C45FBB5A0442"}},"signature":[1,"BD9AE0AE7B54DB3C7D4913FFEC54A29E3AC11DFFF77F59CF0411C47ADB863C1C2D44BB3B84EA1093ED01E6C19063294CA3E36D1920CD627A60F934216D2B3B02"]}}],"peer_key":""}]} +{"time":"2017-04-27T22:24:06.401Z","msg":[1,{"height":1,"round":0,"step":"RoundStepCommit"}]} #ENDHEIGHT: 1 -{"time":"2017-02-17T23:54:19.019Z","msg":[1,{"height":2,"round":0,"step":"RoundStepNewHeight"}]} -{"time":"2017-02-17T23:54:20.017Z","msg":[3,{"duration":998073370,"height":2,"round":0,"step":1}]} -{"time":"2017-02-17T23:54:20.018Z","msg":[1,{"height":2,"round":0,"step":"RoundStepPropose"}]} -{"time":"2017-02-17T23:54:20.018Z","msg":[2,{"msg":[17,{"Proposal":{"height":2,"round":0,"block_parts_header":{"total":1,"hash":"D008E9014CDDEA8EC95E1E99E21333241BD52DFC"},"pol_round":-1,"pol_block_id":{"hash":"","parts":{"total":0,"hash":""}},"signature":[1,"03E06975CD5A83E2B6AADC82F0C5965BE13CCB589912B7CBEF847BDBED6E8EAEE0901C02FAE8BC96B269C4750E5BA5C351C587537E3C063358A7D769007D8509"]}}],"peer_key":""}]} -{"time":"2017-02-17T23:54:20.019Z","msg":[2,{"msg":[19,{"Height":2,"Round":0,"Part":{"index":0,"bytes":"0101010F74656E6465726D696E745F74657374010214A4384846E01E40018101143F32EE37F9EA674A2173CAD651836A8EE628B5C7010101142E32C8D500E936D27A47FCE3FF4BE7C1AFB3FAE101142F7319866C6844639F566F5A201DE2C339EAF8670114A0DC0254E5A6831C03FB4E1BE09CB26AEAC5C73D0114354594CBFC1A7BCA1AD0050ED6AA010023EADA39011402B7F5E97ED0892197CF5779CA6B904B10C87E10010181011E363136323633363433313332333933443634363336323631333133323339011E363136323633363433313333333033443634363336323631333133333330011E363136323633363433313333333133443634363336323631333133333331011E363136323633363433313333333233443634363336323631333133333332011E363136323633363433313333333333443634363336323631333133333333011E363136323633363433313333333433443634363336323631333133333334011E363136323633363433313333333533443634363336323631333133333335011E363136323633363433313333333633443634363336323631333133333336011E363136323633363433313333333733443634363336323631333133333337011E363136323633363433313333333833443634363336323631333133333338011E363136323633363433313333333933443634363336323631333133333339011E363136323633363433313334333033443634363336323631333133343330011E363136323633363433313334333133443634363336323631333133343331011E363136323633363433313334333233443634363336323631333133343332011E363136323633363433313334333333443634363336323631333133343333011E363136323633363433313334333433443634363336323631333133343334011E363136323633363433313334333533443634363336323631333133343335011E363136323633363433313334333633443634363336323631333133343336011E363136323633363433313334333733443634363336323631333133343337011E363136323633363433313334333833443634363336323631333133343338011E363136323633363433313334333933443634363336323631333133343339011E363136323633363433313335333033443634363336323631333133353330011E363136323633363433313335333133443634363336323631333133353331011E363136323633363433313335333233443634363336323631333133353332011E363136323633363433313335333333443634363336323631333133353333011E363136323633363433313335333433443634363336323631333133353334011E363136323633363433313335333533443634363336323631333133353335011E363136323633363433313335333633443634363336323631333133353336011E363136323633363433313335333733443634363336323631333133353337011E363136323633363433313335333833443634363336323631333133353338011E363136323633363433313335333933443634363336323631333133353339011E363136323633363433313336333033443634363336323631333133363330011E363136323633363433313336333133443634363336323631333133363331011E363136323633363433313336333233443634363336323631333133363332011E363136323633363433313336333333443634363336323631333133363333011E363136323633363433313336333433443634363336323631333133363334011E363136323633363433313336333533443634363336323631333133363335011E363136323633363433313336333633443634363336323631333133363336011E363136323633363433313336333733443634363336323631333133363337011E363136323633363433313336333833443634363336323631333133363338011E363136323633363433313336333933443634363336323631333133363339011E363136323633363433313337333033443634363336323631333133373330011E363136323633363433313337333133443634363336323631333133373331011E363136323633363433313337333233443634363336323631333133373332011E363136323633363433313337333333443634363336323631333133373333011E363136323633363433313337333433443634363336323631333133373334011E363136323633363433313337333533443634363336323631333133373335011E363136323633363433313337333633443634363336323631333133373336011E363136323633363433313337333733443634363336323631333133373337011E363136323633363433313337333833443634363336323631333133373338011E363136323633363433313337333933443634363336323631333133373339011E363136323633363433313338333033443634363336323631333133383330011E363136323633363433313338333133443634363336323631333133383331011E363136323633363433313338333233443634363336323631333133383332011E363136323633363433313338333333443634363336323631333133383333011E363136323633363433313338333433443634363336323631333133383334011E363136323633363433313338333533443634363336323631333133383335011E363136323633363433313338333633443634363336323631333133383336011E363136323633363433313338333733443634363336323631333133383337011E363136323633363433313338333833443634363336323631333133383338011E363136323633363433313338333933443634363336323631333133383339011E363136323633363433313339333033443634363336323631333133393330011E363136323633363433313339333133443634363336323631333133393331011E363136323633363433313339333233443634363336323631333133393332011E363136323633363433313339333333443634363336323631333133393333011E363136323633363433313339333433443634363336323631333133393334011E363136323633363433313339333533443634363336323631333133393335011E363136323633363433313339333633443634363336323631333133393336011E363136323633363433313339333733443634363336323631333133393337011E363136323633363433313339333833443634363336323631333133393338011E363136323633363433313339333933443634363336323631333133393339011E363136323633363433323330333033443634363336323631333233303330011E363136323633363433323330333133443634363336323631333233303331011E363136323633363433323330333233443634363336323631333233303332011E363136323633363433323330333333443634363336323631333233303333011E363136323633363433323330333433443634363336323631333233303334011E363136323633363433323330333533443634363336323631333233303335011E363136323633363433323330333633443634363336323631333233303336011E363136323633363433323330333733443634363336323631333233303337011E363136323633363433323330333833443634363336323631333233303338011E363136323633363433323330333933443634363336323631333233303339011E363136323633363433323331333033443634363336323631333233313330011E363136323633363433323331333133443634363336323631333233313331011E363136323633363433323331333233443634363336323631333233313332011E363136323633363433323331333333443634363336323631333233313333011E363136323633363433323331333433443634363336323631333233313334011E363136323633363433323331333533443634363336323631333233313335011E363136323633363433323331333633443634363336323631333233313336011E363136323633363433323331333733443634363336323631333233313337011E363136323633363433323331333833443634363336323631333233313338011E363136323633363433323331333933443634363336323631333233313339011E363136323633363433323332333033443634363336323631333233323330011E363136323633363433323332333133443634363336323631333233323331011E363136323633363433323332333233443634363336323631333233323332011E363136323633363433323332333333443634363336323631333233323333011E363136323633363433323332333433443634363336323631333233323334011E363136323633363433323332333533443634363336323631333233323335011E363136323633363433323332333633443634363336323631333233323336011E363136323633363433323332333733443634363336323631333233323337011E363136323633363433323332333833443634363336323631333233323338011E363136323633363433323332333933443634363336323631333233323339011E363136323633363433323333333033443634363336323631333233333330011E363136323633363433323333333133443634363336323631333233333331011E363136323633363433323333333233443634363336323631333233333332011E363136323633363433323333333333443634363336323631333233333333011E363136323633363433323333333433443634363336323631333233333334011E363136323633363433323333333533443634363336323631333233333335011E363136323633363433323333333633443634363336323631333233333336011E363136323633363433323333333733443634363336323631333233333337011E363136323633363433323333333833443634363336323631333233333338011E363136323633363433323333333933443634363336323631333233333339011E363136323633363433323334333033443634363336323631333233343330011E363136323633363433323334333133443634363336323631333233343331011E363136323633363433323334333233443634363336323631333233343332011E363136323633363433323334333333443634363336323631333233343333011E363136323633363433323334333433443634363336323631333233343334011E363136323633363433323334333533443634363336323631333233343335011E363136323633363433323334333633443634363336323631333233343336011E363136323633363433323334333733443634363336323631333233343337011E363136323633363433323334333833443634363336323631333233343338011E363136323633363433323334333933443634363336323631333233343339011E363136323633363433323335333033443634363336323631333233353330011E363136323633363433323335333133443634363336323631333233353331011E363136323633363433323335333233443634363336323631333233353332011E363136323633363433323335333333443634363336323631333233353333011E363136323633363433323335333433443634363336323631333233353334011E363136323633363433323335333533443634363336323631333233353335011E363136323633363433323335333633443634363336323631333233353336011E3631363236333634333233353337334436343633363236313332333533370101143F32EE37F9EA674A2173CAD651836A8EE628B5C7010101142E32C8D500E936D27A47FCE3FF4BE7C1AFB3FAE10101010114D028C9981F7A87F3093672BF0D5B0E2A1B3ED456000101000201143F32EE37F9EA674A2173CAD651836A8EE628B5C7010101142E32C8D500E936D27A47FCE3FF4BE7C1AFB3FAE1012B1070A5AB9305612A3AE74A8036D82B5E49E0DBBFBC7D723DB985CC8A8E72A52FF8E34D85273FEB8B901945CA541FA5142C3C4D43A04E9205ACECF53FD19B01","proof":{"aunts":[]}}}],"peer_key":""}]} -{"time":"2017-02-17T23:54:20.020Z","msg":[1,{"height":2,"round":0,"step":"RoundStepPrevote"}]} -{"time":"2017-02-17T23:54:20.020Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":2,"round":0,"type":1,"block_id":{"hash":"32310D174A99844713693C9815D2CA660364E028","parts":{"total":1,"hash":"D008E9014CDDEA8EC95E1E99E21333241BD52DFC"}},"signature":[1,"E0289DE621820D9236632B4862BB4D1518A4B194C5AE8194192F375C9A52775A54A7F172A5D7A2014E404A1C3AFA386923E7A20329AFDDFA14655881C04A1A02"]}}],"peer_key":""}]} -{"time":"2017-02-17T23:54:20.021Z","msg":[1,{"height":2,"round":0,"step":"RoundStepPrecommit"}]} -{"time":"2017-02-17T23:54:20.021Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":2,"round":0,"type":2,"block_id":{"hash":"32310D174A99844713693C9815D2CA660364E028","parts":{"total":1,"hash":"D008E9014CDDEA8EC95E1E99E21333241BD52DFC"}},"signature":[1,"AA9F03D0707752301D7CBFCF4F0BCDBD666A46C1CAED3910BD64A3C5C2874AAF328172646C951C5E2FD962359C382A3CBBA2C73EC9B533668C6386995B83EC08"]}}],"peer_key":""}]} -{"time":"2017-02-17T23:54:20.022Z","msg":[1,{"height":2,"round":0,"step":"RoundStepCommit"}]} +{"time":"2017-04-27T22:24:06.406Z","msg":[1,{"height":2,"round":0,"step":"RoundStepNewHeight"}]} +{"time":"2017-04-27T22:24:07.401Z","msg":[3,{"duration":994141766,"height":2,"round":0,"step":1}]} +{"time":"2017-04-27T22:24:07.402Z","msg":[1,{"height":2,"round":0,"step":"RoundStepPropose"}]} +{"time":"2017-04-27T22:24:07.403Z","msg":[2,{"msg":[17,{"Proposal":{"height":2,"round":0,"block_parts_header":{"total":1,"hash":"C693ABE80F5819FA5DA4666CBB74B7C865CE3C70"},"pol_round":-1,"pol_block_id":{"hash":"","parts":{"total":0,"hash":""}},"signature":[1,"C2E469C27D63A29609ABA5D3A74BEC10E6D6CD6310FBFAF50E0989AEBEBD7EF86A7EBEF7028662BA97A8402E899588E047F784D642D19852ED01B46CD8240C01"]}}],"peer_key":""}]} +{"time":"2017-04-27T22:24:07.403Z","msg":[2,{"msg":[19,{"Height":2,"Round":0,"Part":{"index":0,"bytes":"0101010F74656E6465726D696E745F74657374010214B96167381D4C4001690114B83D2AF62DBCA00412CD21152645411609DB51D401010114218DFAADA5F4A3E0DC3060379E80C45FBB5A04420114F737D0E2D410564390CFEC68118549248848A5DA011417B6D1FF1D4D334EA682CF10572C9682866F6D840114354594CBFC1A7BCA1AD0050ED6AA010023EADA39011455F568A46B4C2A3816103A3AA8845222C0941FDE010169011E363136323633363433313330333433443634363336323631333133303334011E363136323633363433313330333533443634363336323631333133303335011E363136323633363433313330333633443634363336323631333133303336011E363136323633363433313330333733443634363336323631333133303337011E363136323633363433313330333833443634363336323631333133303338011E363136323633363433313330333933443634363336323631333133303339011E363136323633363433313331333033443634363336323631333133313330011E363136323633363433313331333133443634363336323631333133313331011E363136323633363433313331333233443634363336323631333133313332011E363136323633363433313331333333443634363336323631333133313333011E363136323633363433313331333433443634363336323631333133313334011E363136323633363433313331333533443634363336323631333133313335011E363136323633363433313331333633443634363336323631333133313336011E363136323633363433313331333733443634363336323631333133313337011E363136323633363433313331333833443634363336323631333133313338011E363136323633363433313331333933443634363336323631333133313339011E363136323633363433313332333033443634363336323631333133323330011E363136323633363433313332333133443634363336323631333133323331011E363136323633363433313332333233443634363336323631333133323332011E363136323633363433313332333333443634363336323631333133323333011E363136323633363433313332333433443634363336323631333133323334011E363136323633363433313332333533443634363336323631333133323335011E363136323633363433313332333633443634363336323631333133323336011E363136323633363433313332333733443634363336323631333133323337011E363136323633363433313332333833443634363336323631333133323338011E363136323633363433313332333933443634363336323631333133323339011E363136323633363433313333333033443634363336323631333133333330011E363136323633363433313333333133443634363336323631333133333331011E363136323633363433313333333233443634363336323631333133333332011E363136323633363433313333333333443634363336323631333133333333011E363136323633363433313333333433443634363336323631333133333334011E363136323633363433313333333533443634363336323631333133333335011E363136323633363433313333333633443634363336323631333133333336011E363136323633363433313333333733443634363336323631333133333337011E363136323633363433313333333833443634363336323631333133333338011E363136323633363433313333333933443634363336323631333133333339011E363136323633363433313334333033443634363336323631333133343330011E363136323633363433313334333133443634363336323631333133343331011E363136323633363433313334333233443634363336323631333133343332011E363136323633363433313334333333443634363336323631333133343333011E363136323633363433313334333433443634363336323631333133343334011E363136323633363433313334333533443634363336323631333133343335011E363136323633363433313334333633443634363336323631333133343336011E363136323633363433313334333733443634363336323631333133343337011E363136323633363433313334333833443634363336323631333133343338011E363136323633363433313334333933443634363336323631333133343339011E363136323633363433313335333033443634363336323631333133353330011E363136323633363433313335333133443634363336323631333133353331011E363136323633363433313335333233443634363336323631333133353332011E363136323633363433313335333333443634363336323631333133353333011E363136323633363433313335333433443634363336323631333133353334011E363136323633363433313335333533443634363336323631333133353335011E363136323633363433313335333633443634363336323631333133353336011E363136323633363433313335333733443634363336323631333133353337011E363136323633363433313335333833443634363336323631333133353338011E363136323633363433313335333933443634363336323631333133353339011E363136323633363433313336333033443634363336323631333133363330011E363136323633363433313336333133443634363336323631333133363331011E363136323633363433313336333233443634363336323631333133363332011E363136323633363433313336333333443634363336323631333133363333011E363136323633363433313336333433443634363336323631333133363334011E363136323633363433313336333533443634363336323631333133363335011E363136323633363433313336333633443634363336323631333133363336011E363136323633363433313336333733443634363336323631333133363337011E363136323633363433313336333833443634363336323631333133363338011E363136323633363433313336333933443634363336323631333133363339011E363136323633363433313337333033443634363336323631333133373330011E363136323633363433313337333133443634363336323631333133373331011E363136323633363433313337333233443634363336323631333133373332011E363136323633363433313337333333443634363336323631333133373333011E363136323633363433313337333433443634363336323631333133373334011E363136323633363433313337333533443634363336323631333133373335011E363136323633363433313337333633443634363336323631333133373336011E363136323633363433313337333733443634363336323631333133373337011E363136323633363433313337333833443634363336323631333133373338011E363136323633363433313337333933443634363336323631333133373339011E363136323633363433313338333033443634363336323631333133383330011E363136323633363433313338333133443634363336323631333133383331011E363136323633363433313338333233443634363336323631333133383332011E363136323633363433313338333333443634363336323631333133383333011E363136323633363433313338333433443634363336323631333133383334011E363136323633363433313338333533443634363336323631333133383335011E363136323633363433313338333633443634363336323631333133383336011E363136323633363433313338333733443634363336323631333133383337011E363136323633363433313338333833443634363336323631333133383338011E363136323633363433313338333933443634363336323631333133383339011E363136323633363433313339333033443634363336323631333133393330011E363136323633363433313339333133443634363336323631333133393331011E363136323633363433313339333233443634363336323631333133393332011E363136323633363433313339333333443634363336323631333133393333011E363136323633363433313339333433443634363336323631333133393334011E363136323633363433313339333533443634363336323631333133393335011E363136323633363433313339333633443634363336323631333133393336011E363136323633363433313339333733443634363336323631333133393337011E363136323633363433313339333833443634363336323631333133393338011E363136323633363433313339333933443634363336323631333133393339011E363136323633363433323330333033443634363336323631333233303330011E363136323633363433323330333133443634363336323631333233303331011E363136323633363433323330333233443634363336323631333233303332011E363136323633363433323330333333443634363336323631333233303333011E363136323633363433323330333433443634363336323631333233303334011E363136323633363433323330333533443634363336323631333233303335011E363136323633363433323330333633443634363336323631333233303336011E363136323633363433323330333733443634363336323631333233303337011E363136323633363433323330333833443634363336323631333233303338010114B83D2AF62DBCA00412CD21152645411609DB51D401010114218DFAADA5F4A3E0DC3060379E80C45FBB5A04420101010114D028C9981F7A87F3093672BF0D5B0E2A1B3ED45600010100020114B83D2AF62DBCA00412CD21152645411609DB51D401010114218DFAADA5F4A3E0DC3060379E80C45FBB5A044201BD9AE0AE7B54DB3C7D4913FFEC54A29E3AC11DFFF77F59CF0411C47ADB863C1C2D44BB3B84EA1093ED01E6C19063294CA3E36D1920CD627A60F934216D2B3B02","proof":{"aunts":[]}}}],"peer_key":""}]} +{"time":"2017-04-27T22:24:07.405Z","msg":[1,{"height":2,"round":0,"step":"RoundStepPrevote"}]} +{"time":"2017-04-27T22:24:07.405Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":2,"round":0,"type":1,"block_id":{"hash":"BDB3BB45AF3B0CD2373E3690A684A00008A65526","parts":{"total":1,"hash":"C693ABE80F5819FA5DA4666CBB74B7C865CE3C70"}},"signature":[1,"FBBDB1360C3A2196A4149AEBB0E23512CF032FE9E98CB18EEA8CC71BB1F5482D4936B97B7D91965D6C00C230A54CA4CE4C6339716550D3B70E2DE79EE8DB0006"]}}],"peer_key":""}]} +{"time":"2017-04-27T22:24:07.406Z","msg":[1,{"height":2,"round":0,"step":"RoundStepPrecommit"}]} +{"time":"2017-04-27T22:24:07.406Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":2,"round":0,"type":2,"block_id":{"hash":"BDB3BB45AF3B0CD2373E3690A684A00008A65526","parts":{"total":1,"hash":"C693ABE80F5819FA5DA4666CBB74B7C865CE3C70"}},"signature":[1,"84FC5E25CECBCBB85D30E3B8BD6BAD674DB2D452EC53E04BB890C2FDC1DEE8EC4FA00234D64F4CD74DE4574DE7061B9985D4655009410FF40AD7CE7515215004"]}}],"peer_key":""}]} +{"time":"2017-04-27T22:24:07.407Z","msg":[1,{"height":2,"round":0,"step":"RoundStepCommit"}]} #ENDHEIGHT: 2 -{"time":"2017-02-17T23:54:20.025Z","msg":[1,{"height":3,"round":0,"step":"RoundStepNewHeight"}]} -{"time":"2017-02-17T23:54:21.022Z","msg":[3,{"duration":997103974,"height":3,"round":0,"step":1}]} -{"time":"2017-02-17T23:54:21.024Z","msg":[1,{"height":3,"round":0,"step":"RoundStepPropose"}]} -{"time":"2017-02-17T23:54:21.024Z","msg":[2,{"msg":[17,{"Proposal":{"height":3,"round":0,"block_parts_header":{"total":1,"hash":"2E5DE5777A5AD899CD2531304F42A470509DE989"},"pol_round":-1,"pol_block_id":{"hash":"","parts":{"total":0,"hash":""}},"signature":[1,"5F6A6A8097BD6A1780568C7E064D932BC1F941E1D5AC408DE970C4EEDCCD939C0F163466D20F0E98A7599792341441422980C09D23E03009BD9CE565673C9704"]}}],"peer_key":""}]} -{"time":"2017-02-17T23:54:21.024Z","msg":[2,{"msg":[19,{"Height":3,"Round":0,"Part":{"index":0,"bytes":"0101010F74656E6465726D696E745F74657374010314A4384882C73380017C011432310D174A99844713693C9815D2CA660364E02801010114D008E9014CDDEA8EC95E1E99E21333241BD52DFC0114ABAB9E28967792BDA02172D3CB99DA99A696738E0114513B0891921FB0A5F6471950AFE2598445153CFF0114354594CBFC1A7BCA1AD0050ED6AA010023EADA3901141FBD44B8259B2A6632F08F88BE5EC8C203075CD001017C011E363136323633363433323335333833443634363336323631333233353338011E363136323633363433323335333933443634363336323631333233353339011E363136323633363433323336333033443634363336323631333233363330011E363136323633363433323336333133443634363336323631333233363331011E363136323633363433323336333233443634363336323631333233363332011E363136323633363433323336333333443634363336323631333233363333011E363136323633363433323336333433443634363336323631333233363334011E363136323633363433323336333533443634363336323631333233363335011E363136323633363433323336333633443634363336323631333233363336011E363136323633363433323336333733443634363336323631333233363337011E363136323633363433323336333833443634363336323631333233363338011E363136323633363433323336333933443634363336323631333233363339011E363136323633363433323337333033443634363336323631333233373330011E363136323633363433323337333133443634363336323631333233373331011E363136323633363433323337333233443634363336323631333233373332011E363136323633363433323337333333443634363336323631333233373333011E363136323633363433323337333433443634363336323631333233373334011E363136323633363433323337333533443634363336323631333233373335011E363136323633363433323337333633443634363336323631333233373336011E363136323633363433323337333733443634363336323631333233373337011E363136323633363433323337333833443634363336323631333233373338011E363136323633363433323337333933443634363336323631333233373339011E363136323633363433323338333033443634363336323631333233383330011E363136323633363433323338333133443634363336323631333233383331011E363136323633363433323338333233443634363336323631333233383332011E363136323633363433323338333333443634363336323631333233383333011E363136323633363433323338333433443634363336323631333233383334011E363136323633363433323338333533443634363336323631333233383335011E363136323633363433323338333633443634363336323631333233383336011E363136323633363433323338333733443634363336323631333233383337011E363136323633363433323338333833443634363336323631333233383338011E363136323633363433323338333933443634363336323631333233383339011E363136323633363433323339333033443634363336323631333233393330011E363136323633363433323339333133443634363336323631333233393331011E363136323633363433323339333233443634363336323631333233393332011E363136323633363433323339333333443634363336323631333233393333011E363136323633363433323339333433443634363336323631333233393334011E363136323633363433323339333533443634363336323631333233393335011E363136323633363433323339333633443634363336323631333233393336011E363136323633363433323339333733443634363336323631333233393337011E363136323633363433323339333833443634363336323631333233393338011E363136323633363433323339333933443634363336323631333233393339011E363136323633363433333330333033443634363336323631333333303330011E363136323633363433333330333133443634363336323631333333303331011E363136323633363433333330333233443634363336323631333333303332011E363136323633363433333330333333443634363336323631333333303333011E363136323633363433333330333433443634363336323631333333303334011E363136323633363433333330333533443634363336323631333333303335011E363136323633363433333330333633443634363336323631333333303336011E363136323633363433333330333733443634363336323631333333303337011E363136323633363433333330333833443634363336323631333333303338011E363136323633363433333330333933443634363336323631333333303339011E363136323633363433333331333033443634363336323631333333313330011E363136323633363433333331333133443634363336323631333333313331011E363136323633363433333331333233443634363336323631333333313332011E363136323633363433333331333333443634363336323631333333313333011E363136323633363433333331333433443634363336323631333333313334011E363136323633363433333331333533443634363336323631333333313335011E363136323633363433333331333633443634363336323631333333313336011E363136323633363433333331333733443634363336323631333333313337011E363136323633363433333331333833443634363336323631333333313338011E363136323633363433333331333933443634363336323631333333313339011E363136323633363433333332333033443634363336323631333333323330011E363136323633363433333332333133443634363336323631333333323331011E363136323633363433333332333233443634363336323631333333323332011E363136323633363433333332333333443634363336323631333333323333011E363136323633363433333332333433443634363336323631333333323334011E363136323633363433333332333533443634363336323631333333323335011E363136323633363433333332333633443634363336323631333333323336011E363136323633363433333332333733443634363336323631333333323337011E363136323633363433333332333833443634363336323631333333323338011E363136323633363433333332333933443634363336323631333333323339011E363136323633363433333333333033443634363336323631333333333330011E363136323633363433333333333133443634363336323631333333333331011E363136323633363433333333333233443634363336323631333333333332011E363136323633363433333333333333443634363336323631333333333333011E363136323633363433333333333433443634363336323631333333333334011E363136323633363433333333333533443634363336323631333333333335011E363136323633363433333333333633443634363336323631333333333336011E363136323633363433333333333733443634363336323631333333333337011E363136323633363433333333333833443634363336323631333333333338011E363136323633363433333333333933443634363336323631333333333339011E363136323633363433333334333033443634363336323631333333343330011E363136323633363433333334333133443634363336323631333333343331011E363136323633363433333334333233443634363336323631333333343332011E363136323633363433333334333333443634363336323631333333343333011E363136323633363433333334333433443634363336323631333333343334011E363136323633363433333334333533443634363336323631333333343335011E363136323633363433333334333633443634363336323631333333343336011E363136323633363433333334333733443634363336323631333333343337011E363136323633363433333334333833443634363336323631333333343338011E363136323633363433333334333933443634363336323631333333343339011E363136323633363433333335333033443634363336323631333333353330011E363136323633363433333335333133443634363336323631333333353331011E363136323633363433333335333233443634363336323631333333353332011E363136323633363433333335333333443634363336323631333333353333011E363136323633363433333335333433443634363336323631333333353334011E363136323633363433333335333533443634363336323631333333353335011E363136323633363433333335333633443634363336323631333333353336011E363136323633363433333335333733443634363336323631333333353337011E363136323633363433333335333833443634363336323631333333353338011E363136323633363433333335333933443634363336323631333333353339011E363136323633363433333336333033443634363336323631333333363330011E363136323633363433333336333133443634363336323631333333363331011E363136323633363433333336333233443634363336323631333333363332011E363136323633363433333336333333443634363336323631333333363333011E363136323633363433333336333433443634363336323631333333363334011E363136323633363433333336333533443634363336323631333333363335011E363136323633363433333336333633443634363336323631333333363336011E363136323633363433333336333733443634363336323631333333363337011E363136323633363433333336333833443634363336323631333333363338011E363136323633363433333336333933443634363336323631333333363339011E363136323633363433333337333033443634363336323631333333373330011E363136323633363433333337333133443634363336323631333333373331011E363136323633363433333337333233443634363336323631333333373332011E363136323633363433333337333333443634363336323631333333373333011E363136323633363433333337333433443634363336323631333333373334011E363136323633363433333337333533443634363336323631333333373335011E363136323633363433333337333633443634363336323631333333373336011E363136323633363433333337333733443634363336323631333333373337011E363136323633363433333337333833443634363336323631333333373338011E363136323633363433333337333933443634363336323631333333373339011E363136323633363433333338333033443634363336323631333333383330011E36313632363336343333333833313344363436333632363133333338333101011432310D174A99844713693C9815D2CA660364E02801010114D008E9014CDDEA8EC95E1E99E21333241BD52DFC0101010114D028C9981F7A87F3093672BF0D5B0E2A1B3ED4560001020002011432310D174A99844713693C9815D2CA660364E02801010114D008E9014CDDEA8EC95E1E99E21333241BD52DFC01AA9F03D0707752301D7CBFCF4F0BCDBD666A46C1CAED3910BD64A3C5C2874AAF328172646C951C5E2FD962359C382A3CBBA2C73EC9B533668C6386995B83EC08","proof":{"aunts":[]}}}],"peer_key":""}]} -{"time":"2017-02-17T23:54:21.026Z","msg":[1,{"height":3,"round":0,"step":"RoundStepPrevote"}]} -{"time":"2017-02-17T23:54:21.026Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":3,"round":0,"type":1,"block_id":{"hash":"37AF6866DA8C3167CFC280FAE47B6ED441B00D5B","parts":{"total":1,"hash":"2E5DE5777A5AD899CD2531304F42A470509DE989"}},"signature":[1,"F0AAB604A8CE724453A378BBC66142C418464C3C0EC3EB2E15A1CB7524A92B9F36BE8A191238A4D317F542D999DF698B5C2A28D754240524FF8CCADA0947DE00"]}}],"peer_key":""}]} -{"time":"2017-02-17T23:54:21.028Z","msg":[1,{"height":3,"round":0,"step":"RoundStepPrecommit"}]} -{"time":"2017-02-17T23:54:21.028Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":3,"round":0,"type":2,"block_id":{"hash":"37AF6866DA8C3167CFC280FAE47B6ED441B00D5B","parts":{"total":1,"hash":"2E5DE5777A5AD899CD2531304F42A470509DE989"}},"signature":[1,"C900519E305EC03392E7D197D5FAB535DB240C9C0BA5375A1679C75BAAA07C7410C0EF43CF97D98F2C08A1D739667D5ACFF6233A1FAE75D3DA275AEA422EFD0F"]}}],"peer_key":""}]} -{"time":"2017-02-17T23:54:21.028Z","msg":[1,{"height":3,"round":0,"step":"RoundStepCommit"}]} +{"time":"2017-04-27T22:24:07.418Z","msg":[1,{"height":3,"round":0,"step":"RoundStepNewHeight"}]} +{"time":"2017-04-27T22:24:08.407Z","msg":[3,{"duration":988837269,"height":3,"round":0,"step":1}]} +{"time":"2017-04-27T22:24:08.408Z","msg":[1,{"height":3,"round":0,"step":"RoundStepPropose"}]} +{"time":"2017-04-27T22:24:08.408Z","msg":[2,{"msg":[17,{"Proposal":{"height":3,"round":0,"block_parts_header":{"total":1,"hash":"F2291A94D838F8E222FEFA8550B57D64CE1383B1"},"pol_round":-1,"pol_block_id":{"hash":"","parts":{"total":0,"hash":""}},"signature":[1,"389595237F4AFD5DAADA25139227AA54C38DB653ADAB9062BEF3450DAB9A9FF359776C24A8B983600D83118A74906778331BF783927F2C00BE21FC956633EF04"]}}],"peer_key":""}]} +{"time":"2017-04-27T22:24:08.408Z","msg":[2,{"msg":[19,{"Height":3,"Round":0,"Part":{"index":0,"bytes":"0101010F74656E6465726D696E745F74657374010314B961677413A3C0015C0114BDB3BB45AF3B0CD2373E3690A684A00008A6552601010114C693ABE80F5819FA5DA4666CBB74B7C865CE3C70011448506FCD69C61430F5E1F7854303F93AE49A63440114EBCA4C0F8D8B0BFB8AB6C6CADCD1ECC6F086B8C90114354594CBFC1A7BCA1AD0050ED6AA010023EADA390114D71F486E836237FDDFFA4EEFDAD138F8298D6FF701015C011E363136323633363433323330333933443634363336323631333233303339011E363136323633363433323331333033443634363336323631333233313330011E363136323633363433323331333133443634363336323631333233313331011E363136323633363433323331333233443634363336323631333233313332011E363136323633363433323331333333443634363336323631333233313333011E363136323633363433323331333433443634363336323631333233313334011E363136323633363433323331333533443634363336323631333233313335011E363136323633363433323331333633443634363336323631333233313336011E363136323633363433323331333733443634363336323631333233313337011E363136323633363433323331333833443634363336323631333233313338011E363136323633363433323331333933443634363336323631333233313339011E363136323633363433323332333033443634363336323631333233323330011E363136323633363433323332333133443634363336323631333233323331011E363136323633363433323332333233443634363336323631333233323332011E363136323633363433323332333333443634363336323631333233323333011E363136323633363433323332333433443634363336323631333233323334011E363136323633363433323332333533443634363336323631333233323335011E363136323633363433323332333633443634363336323631333233323336011E363136323633363433323332333733443634363336323631333233323337011E363136323633363433323332333833443634363336323631333233323338011E363136323633363433323332333933443634363336323631333233323339011E363136323633363433323333333033443634363336323631333233333330011E363136323633363433323333333133443634363336323631333233333331011E363136323633363433323333333233443634363336323631333233333332011E363136323633363433323333333333443634363336323631333233333333011E363136323633363433323333333433443634363336323631333233333334011E363136323633363433323333333533443634363336323631333233333335011E363136323633363433323333333633443634363336323631333233333336011E363136323633363433323333333733443634363336323631333233333337011E363136323633363433323333333833443634363336323631333233333338011E363136323633363433323333333933443634363336323631333233333339011E363136323633363433323334333033443634363336323631333233343330011E363136323633363433323334333133443634363336323631333233343331011E363136323633363433323334333233443634363336323631333233343332011E363136323633363433323334333333443634363336323631333233343333011E363136323633363433323334333433443634363336323631333233343334011E363136323633363433323334333533443634363336323631333233343335011E363136323633363433323334333633443634363336323631333233343336011E363136323633363433323334333733443634363336323631333233343337011E363136323633363433323334333833443634363336323631333233343338011E363136323633363433323334333933443634363336323631333233343339011E363136323633363433323335333033443634363336323631333233353330011E363136323633363433323335333133443634363336323631333233353331011E363136323633363433323335333233443634363336323631333233353332011E363136323633363433323335333333443634363336323631333233353333011E363136323633363433323335333433443634363336323631333233353334011E363136323633363433323335333533443634363336323631333233353335011E363136323633363433323335333633443634363336323631333233353336011E363136323633363433323335333733443634363336323631333233353337011E363136323633363433323335333833443634363336323631333233353338011E363136323633363433323335333933443634363336323631333233353339011E363136323633363433323336333033443634363336323631333233363330011E363136323633363433323336333133443634363336323631333233363331011E363136323633363433323336333233443634363336323631333233363332011E363136323633363433323336333333443634363336323631333233363333011E363136323633363433323336333433443634363336323631333233363334011E363136323633363433323336333533443634363336323631333233363335011E363136323633363433323336333633443634363336323631333233363336011E363136323633363433323336333733443634363336323631333233363337011E363136323633363433323336333833443634363336323631333233363338011E363136323633363433323336333933443634363336323631333233363339011E363136323633363433323337333033443634363336323631333233373330011E363136323633363433323337333133443634363336323631333233373331011E363136323633363433323337333233443634363336323631333233373332011E363136323633363433323337333333443634363336323631333233373333011E363136323633363433323337333433443634363336323631333233373334011E363136323633363433323337333533443634363336323631333233373335011E363136323633363433323337333633443634363336323631333233373336011E363136323633363433323337333733443634363336323631333233373337011E363136323633363433323337333833443634363336323631333233373338011E363136323633363433323337333933443634363336323631333233373339011E363136323633363433323338333033443634363336323631333233383330011E363136323633363433323338333133443634363336323631333233383331011E363136323633363433323338333233443634363336323631333233383332011E363136323633363433323338333333443634363336323631333233383333011E363136323633363433323338333433443634363336323631333233383334011E363136323633363433323338333533443634363336323631333233383335011E363136323633363433323338333633443634363336323631333233383336011E363136323633363433323338333733443634363336323631333233383337011E363136323633363433323338333833443634363336323631333233383338011E363136323633363433323338333933443634363336323631333233383339011E363136323633363433323339333033443634363336323631333233393330011E363136323633363433323339333133443634363336323631333233393331011E363136323633363433323339333233443634363336323631333233393332011E363136323633363433323339333333443634363336323631333233393333011E363136323633363433323339333433443634363336323631333233393334011E363136323633363433323339333533443634363336323631333233393335011E363136323633363433323339333633443634363336323631333233393336011E363136323633363433323339333733443634363336323631333233393337011E363136323633363433323339333833443634363336323631333233393338011E363136323633363433323339333933443634363336323631333233393339011E363136323633363433333330333033443634363336323631333333303330010114BDB3BB45AF3B0CD2373E3690A684A00008A6552601010114C693ABE80F5819FA5DA4666CBB74B7C865CE3C700101010114D028C9981F7A87F3093672BF0D5B0E2A1B3ED45600010200020114BDB3BB45AF3B0CD2373E3690A684A00008A6552601010114C693ABE80F5819FA5DA4666CBB74B7C865CE3C700184FC5E25CECBCBB85D30E3B8BD6BAD674DB2D452EC53E04BB890C2FDC1DEE8EC4FA00234D64F4CD74DE4574DE7061B9985D4655009410FF40AD7CE7515215004","proof":{"aunts":[]}}}],"peer_key":""}]} +{"time":"2017-04-27T22:24:08.409Z","msg":[1,{"height":3,"round":0,"step":"RoundStepPrevote"}]} +{"time":"2017-04-27T22:24:08.409Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":3,"round":0,"type":1,"block_id":{"hash":"A3B20D0D88B8A58ABC78F145D3A499C8FA178377","parts":{"total":1,"hash":"F2291A94D838F8E222FEFA8550B57D64CE1383B1"}},"signature":[1,"BB4CC7A065FE45E9C65ECD4EC8A3A6ED8873128AA2A386B359782EEAAFD58832261E5F365D31428D24DDC311972A7C8410570357D52E23E68F55B821B136D204"]}}],"peer_key":""}]} +{"time":"2017-04-27T22:24:08.410Z","msg":[1,{"height":3,"round":0,"step":"RoundStepPrecommit"}]} +{"time":"2017-04-27T22:24:08.410Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":3,"round":0,"type":2,"block_id":{"hash":"A3B20D0D88B8A58ABC78F145D3A499C8FA178377","parts":{"total":1,"hash":"F2291A94D838F8E222FEFA8550B57D64CE1383B1"}},"signature":[1,"280EE69579077AAD01C686F04FEFE839D5025DF5CFC646DDD177632966E16F0CB59E9C26ED850D8F8E6EDE4D0E7A1CC13AF418608F77C5E6B55B3966E8A69D02"]}}],"peer_key":""}]} +{"time":"2017-04-27T22:24:08.410Z","msg":[1,{"height":3,"round":0,"step":"RoundStepCommit"}]} #ENDHEIGHT: 3 -{"time":"2017-02-17T23:54:21.032Z","msg":[1,{"height":4,"round":0,"step":"RoundStepNewHeight"}]} -{"time":"2017-02-17T23:54:22.028Z","msg":[3,{"duration":996302067,"height":4,"round":0,"step":1}]} -{"time":"2017-02-17T23:54:22.030Z","msg":[1,{"height":4,"round":0,"step":"RoundStepPropose"}]} -{"time":"2017-02-17T23:54:22.030Z","msg":[2,{"msg":[17,{"Proposal":{"height":4,"round":0,"block_parts_header":{"total":1,"hash":"24CEBCBEB833F56D47AD14354071B3B7A243068A"},"pol_round":-1,"pol_block_id":{"hash":"","parts":{"total":0,"hash":""}},"signature":[1,"CAECE2342987295CCB562C9B6AB0E296D0ECDBE0B40CDB5260B32DF07E07E7F30C4E815B76BC04B8E830143409E598F7BA24699F5B5A01A6237221C948A0920C"]}}],"peer_key":""}]} -{"time":"2017-02-17T23:54:22.030Z","msg":[2,{"msg":[19,{"Height":4,"Round":0,"Part":{"index":0,"bytes":"0101010F74656E6465726D696E745F74657374010414A43848BECCCD400169011437AF6866DA8C3167CFC280FAE47B6ED441B00D5B010101142E5DE5777A5AD899CD2531304F42A470509DE9890114EA4CCD80AE261EF694AF4292F8AF5659FB66317301144FFC4AAC3EDFBB81DA9E9DDEC9D6A205AD49049E0114354594CBFC1A7BCA1AD0050ED6AA010023EADA390114E7563C252781F893D7A191A31566713888CCA3B2010169011E363136323633363433333338333233443634363336323631333333383332011E363136323633363433333338333333443634363336323631333333383333011E363136323633363433333338333433443634363336323631333333383334011E363136323633363433333338333533443634363336323631333333383335011E363136323633363433333338333633443634363336323631333333383336011E363136323633363433333338333733443634363336323631333333383337011E363136323633363433333338333833443634363336323631333333383338011E363136323633363433333338333933443634363336323631333333383339011E363136323633363433333339333033443634363336323631333333393330011E363136323633363433333339333133443634363336323631333333393331011E363136323633363433333339333233443634363336323631333333393332011E363136323633363433333339333333443634363336323631333333393333011E363136323633363433333339333433443634363336323631333333393334011E363136323633363433333339333533443634363336323631333333393335011E363136323633363433333339333633443634363336323631333333393336011E363136323633363433333339333733443634363336323631333333393337011E363136323633363433333339333833443634363336323631333333393338011E363136323633363433333339333933443634363336323631333333393339011E363136323633363433343330333033443634363336323631333433303330011E363136323633363433343330333133443634363336323631333433303331011E363136323633363433343330333233443634363336323631333433303332011E363136323633363433343330333333443634363336323631333433303333011E363136323633363433343330333433443634363336323631333433303334011E363136323633363433343330333533443634363336323631333433303335011E363136323633363433343330333633443634363336323631333433303336011E363136323633363433343330333733443634363336323631333433303337011E363136323633363433343330333833443634363336323631333433303338011E363136323633363433343330333933443634363336323631333433303339011E363136323633363433343331333033443634363336323631333433313330011E363136323633363433343331333133443634363336323631333433313331011E363136323633363433343331333233443634363336323631333433313332011E363136323633363433343331333333443634363336323631333433313333011E363136323633363433343331333433443634363336323631333433313334011E363136323633363433343331333533443634363336323631333433313335011E363136323633363433343331333633443634363336323631333433313336011E363136323633363433343331333733443634363336323631333433313337011E363136323633363433343331333833443634363336323631333433313338011E363136323633363433343331333933443634363336323631333433313339011E363136323633363433343332333033443634363336323631333433323330011E363136323633363433343332333133443634363336323631333433323331011E363136323633363433343332333233443634363336323631333433323332011E363136323633363433343332333333443634363336323631333433323333011E363136323633363433343332333433443634363336323631333433323334011E363136323633363433343332333533443634363336323631333433323335011E363136323633363433343332333633443634363336323631333433323336011E363136323633363433343332333733443634363336323631333433323337011E363136323633363433343332333833443634363336323631333433323338011E363136323633363433343332333933443634363336323631333433323339011E363136323633363433343333333033443634363336323631333433333330011E363136323633363433343333333133443634363336323631333433333331011E363136323633363433343333333233443634363336323631333433333332011E363136323633363433343333333333443634363336323631333433333333011E363136323633363433343333333433443634363336323631333433333334011E363136323633363433343333333533443634363336323631333433333335011E363136323633363433343333333633443634363336323631333433333336011E363136323633363433343333333733443634363336323631333433333337011E363136323633363433343333333833443634363336323631333433333338011E363136323633363433343333333933443634363336323631333433333339011E363136323633363433343334333033443634363336323631333433343330011E363136323633363433343334333133443634363336323631333433343331011E363136323633363433343334333233443634363336323631333433343332011E363136323633363433343334333333443634363336323631333433343333011E363136323633363433343334333433443634363336323631333433343334011E363136323633363433343334333533443634363336323631333433343335011E363136323633363433343334333633443634363336323631333433343336011E363136323633363433343334333733443634363336323631333433343337011E363136323633363433343334333833443634363336323631333433343338011E363136323633363433343334333933443634363336323631333433343339011E363136323633363433343335333033443634363336323631333433353330011E363136323633363433343335333133443634363336323631333433353331011E363136323633363433343335333233443634363336323631333433353332011E363136323633363433343335333333443634363336323631333433353333011E363136323633363433343335333433443634363336323631333433353334011E363136323633363433343335333533443634363336323631333433353335011E363136323633363433343335333633443634363336323631333433353336011E363136323633363433343335333733443634363336323631333433353337011E363136323633363433343335333833443634363336323631333433353338011E363136323633363433343335333933443634363336323631333433353339011E363136323633363433343336333033443634363336323631333433363330011E363136323633363433343336333133443634363336323631333433363331011E363136323633363433343336333233443634363336323631333433363332011E363136323633363433343336333333443634363336323631333433363333011E363136323633363433343336333433443634363336323631333433363334011E363136323633363433343336333533443634363336323631333433363335011E363136323633363433343336333633443634363336323631333433363336011E363136323633363433343336333733443634363336323631333433363337011E363136323633363433343336333833443634363336323631333433363338011E363136323633363433343336333933443634363336323631333433363339011E363136323633363433343337333033443634363336323631333433373330011E363136323633363433343337333133443634363336323631333433373331011E363136323633363433343337333233443634363336323631333433373332011E363136323633363433343337333333443634363336323631333433373333011E363136323633363433343337333433443634363336323631333433373334011E363136323633363433343337333533443634363336323631333433373335011E363136323633363433343337333633443634363336323631333433373336011E363136323633363433343337333733443634363336323631333433373337011E363136323633363433343337333833443634363336323631333433373338011E363136323633363433343337333933443634363336323631333433373339011E363136323633363433343338333033443634363336323631333433383330011E363136323633363433343338333133443634363336323631333433383331011E363136323633363433343338333233443634363336323631333433383332011E363136323633363433343338333333443634363336323631333433383333011E363136323633363433343338333433443634363336323631333433383334011E363136323633363433343338333533443634363336323631333433383335011E36313632363336343334333833363344363436333632363133343338333601011437AF6866DA8C3167CFC280FAE47B6ED441B00D5B010101142E5DE5777A5AD899CD2531304F42A470509DE9890101010114D028C9981F7A87F3093672BF0D5B0E2A1B3ED4560001030002011437AF6866DA8C3167CFC280FAE47B6ED441B00D5B010101142E5DE5777A5AD899CD2531304F42A470509DE98901C900519E305EC03392E7D197D5FAB535DB240C9C0BA5375A1679C75BAAA07C7410C0EF43CF97D98F2C08A1D739667D5ACFF6233A1FAE75D3DA275AEA422EFD0F","proof":{"aunts":[]}}}],"peer_key":""}]} -{"time":"2017-02-17T23:54:22.032Z","msg":[1,{"height":4,"round":0,"step":"RoundStepPrevote"}]} -{"time":"2017-02-17T23:54:22.032Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":4,"round":0,"type":1,"block_id":{"hash":"04715E223BF4327FFA9B0D5AD849B74A099D5DEC","parts":{"total":1,"hash":"24CEBCBEB833F56D47AD14354071B3B7A243068A"}},"signature":[1,"B1BFF3641FE1931C78A792540384B9D4CFC3D9008FD4988B24FAD872326C2A380A34F37610C6E076FA5B4DB9E4B3166B703B0429AF0BF1ABCCDB7B2EDB3C8F08"]}}],"peer_key":""}]} -{"time":"2017-02-17T23:54:22.033Z","msg":[1,{"height":4,"round":0,"step":"RoundStepPrecommit"}]} -{"time":"2017-02-17T23:54:22.033Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":4,"round":0,"type":2,"block_id":{"hash":"04715E223BF4327FFA9B0D5AD849B74A099D5DEC","parts":{"total":1,"hash":"24CEBCBEB833F56D47AD14354071B3B7A243068A"}},"signature":[1,"F544743F17479A61F94B0F68C63D254BD60493D78E818D48A5859133619AEE5E92C47CAD89C654DF64E0911C3152091E047555D5F14655D95B9681AE9B336505"]}}],"peer_key":""}]} -{"time":"2017-02-17T23:54:22.034Z","msg":[1,{"height":4,"round":0,"step":"RoundStepCommit"}]} +{"time":"2017-04-27T22:24:08.416Z","msg":[1,{"height":4,"round":0,"step":"RoundStepNewHeight"}]} +{"time":"2017-04-27T22:24:09.410Z","msg":[3,{"duration":994206152,"height":4,"round":0,"step":1}]} +{"time":"2017-04-27T22:24:09.412Z","msg":[1,{"height":4,"round":0,"step":"RoundStepPropose"}]} +{"time":"2017-04-27T22:24:09.412Z","msg":[2,{"msg":[17,{"Proposal":{"height":4,"round":0,"block_parts_header":{"total":1,"hash":"ACB46B8913F0203EB579A9977AF6AF85B6E89705"},"pol_round":-1,"pol_block_id":{"hash":"","parts":{"total":0,"hash":""}},"signature":[1,"7DA37CE6B6BA2FE24C702D00B13B2A15505B0E364FD0824ED16EFD38B196381E9CA1F7BFAC649A978C0851D2DB4CD146FA0E43E5F1D2EAF21E5B58335840200E"]}}],"peer_key":""}]} +{"time":"2017-04-27T22:24:09.412Z","msg":[2,{"msg":[19,{"Height":4,"Round":0,"Part":{"index":0,"bytes":"0101010F74656E6465726D696E745F74657374010414B96167AFDC3480016E0114A3B20D0D88B8A58ABC78F145D3A499C8FA17837701010114F2291A94D838F8E222FEFA8550B57D64CE1383B101142B23CB9F3751854AB6B5D0DDF931F437274D25CD011450FE04FF5EE5EB1132C047965AE65A4BA54ED79E0114354594CBFC1A7BCA1AD0050ED6AA010023EADA3901148A5CA2966F0F895BF9664CB052DEA4B76DE51FA101016E011E363136323633363433333330333133443634363336323631333333303331011E363136323633363433333330333233443634363336323631333333303332011E363136323633363433333330333333443634363336323631333333303333011E363136323633363433333330333433443634363336323631333333303334011E363136323633363433333330333533443634363336323631333333303335011E363136323633363433333330333633443634363336323631333333303336011E363136323633363433333330333733443634363336323631333333303337011E363136323633363433333330333833443634363336323631333333303338011E363136323633363433333330333933443634363336323631333333303339011E363136323633363433333331333033443634363336323631333333313330011E363136323633363433333331333133443634363336323631333333313331011E363136323633363433333331333233443634363336323631333333313332011E363136323633363433333331333333443634363336323631333333313333011E363136323633363433333331333433443634363336323631333333313334011E363136323633363433333331333533443634363336323631333333313335011E363136323633363433333331333633443634363336323631333333313336011E363136323633363433333331333733443634363336323631333333313337011E363136323633363433333331333833443634363336323631333333313338011E363136323633363433333331333933443634363336323631333333313339011E363136323633363433333332333033443634363336323631333333323330011E363136323633363433333332333133443634363336323631333333323331011E363136323633363433333332333233443634363336323631333333323332011E363136323633363433333332333333443634363336323631333333323333011E363136323633363433333332333433443634363336323631333333323334011E363136323633363433333332333533443634363336323631333333323335011E363136323633363433333332333633443634363336323631333333323336011E363136323633363433333332333733443634363336323631333333323337011E363136323633363433333332333833443634363336323631333333323338011E363136323633363433333332333933443634363336323631333333323339011E363136323633363433333333333033443634363336323631333333333330011E363136323633363433333333333133443634363336323631333333333331011E363136323633363433333333333233443634363336323631333333333332011E363136323633363433333333333333443634363336323631333333333333011E363136323633363433333333333433443634363336323631333333333334011E363136323633363433333333333533443634363336323631333333333335011E363136323633363433333333333633443634363336323631333333333336011E363136323633363433333333333733443634363336323631333333333337011E363136323633363433333333333833443634363336323631333333333338011E363136323633363433333333333933443634363336323631333333333339011E363136323633363433333334333033443634363336323631333333343330011E363136323633363433333334333133443634363336323631333333343331011E363136323633363433333334333233443634363336323631333333343332011E363136323633363433333334333333443634363336323631333333343333011E363136323633363433333334333433443634363336323631333333343334011E363136323633363433333334333533443634363336323631333333343335011E363136323633363433333334333633443634363336323631333333343336011E363136323633363433333334333733443634363336323631333333343337011E363136323633363433333334333833443634363336323631333333343338011E363136323633363433333334333933443634363336323631333333343339011E363136323633363433333335333033443634363336323631333333353330011E363136323633363433333335333133443634363336323631333333353331011E363136323633363433333335333233443634363336323631333333353332011E363136323633363433333335333333443634363336323631333333353333011E363136323633363433333335333433443634363336323631333333353334011E363136323633363433333335333533443634363336323631333333353335011E363136323633363433333335333633443634363336323631333333353336011E363136323633363433333335333733443634363336323631333333353337011E363136323633363433333335333833443634363336323631333333353338011E363136323633363433333335333933443634363336323631333333353339011E363136323633363433333336333033443634363336323631333333363330011E363136323633363433333336333133443634363336323631333333363331011E363136323633363433333336333233443634363336323631333333363332011E363136323633363433333336333333443634363336323631333333363333011E363136323633363433333336333433443634363336323631333333363334011E363136323633363433333336333533443634363336323631333333363335011E363136323633363433333336333633443634363336323631333333363336011E363136323633363433333336333733443634363336323631333333363337011E363136323633363433333336333833443634363336323631333333363338011E363136323633363433333336333933443634363336323631333333363339011E363136323633363433333337333033443634363336323631333333373330011E363136323633363433333337333133443634363336323631333333373331011E363136323633363433333337333233443634363336323631333333373332011E363136323633363433333337333333443634363336323631333333373333011E363136323633363433333337333433443634363336323631333333373334011E363136323633363433333337333533443634363336323631333333373335011E363136323633363433333337333633443634363336323631333333373336011E363136323633363433333337333733443634363336323631333333373337011E363136323633363433333337333833443634363336323631333333373338011E363136323633363433333337333933443634363336323631333333373339011E363136323633363433333338333033443634363336323631333333383330011E363136323633363433333338333133443634363336323631333333383331011E363136323633363433333338333233443634363336323631333333383332011E363136323633363433333338333333443634363336323631333333383333011E363136323633363433333338333433443634363336323631333333383334011E363136323633363433333338333533443634363336323631333333383335011E363136323633363433333338333633443634363336323631333333383336011E363136323633363433333338333733443634363336323631333333383337011E363136323633363433333338333833443634363336323631333333383338011E363136323633363433333338333933443634363336323631333333383339011E363136323633363433333339333033443634363336323631333333393330011E363136323633363433333339333133443634363336323631333333393331011E363136323633363433333339333233443634363336323631333333393332011E363136323633363433333339333333443634363336323631333333393333011E363136323633363433333339333433443634363336323631333333393334011E363136323633363433333339333533443634363336323631333333393335011E363136323633363433333339333633443634363336323631333333393336011E363136323633363433333339333733443634363336323631333333393337011E363136323633363433333339333833443634363336323631333333393338011E363136323633363433333339333933443634363336323631333333393339011E363136323633363433343330333033443634363336323631333433303330011E363136323633363433343330333133443634363336323631333433303331011E363136323633363433343330333233443634363336323631333433303332011E363136323633363433343330333333443634363336323631333433303333011E363136323633363433343330333433443634363336323631333433303334011E363136323633363433343330333533443634363336323631333433303335011E363136323633363433343330333633443634363336323631333433303336011E363136323633363433343330333733443634363336323631333433303337011E363136323633363433343330333833443634363336323631333433303338011E363136323633363433343330333933443634363336323631333433303339011E363136323633363433343331333033443634363336323631333433313330010114A3B20D0D88B8A58ABC78F145D3A499C8FA17837701010114F2291A94D838F8E222FEFA8550B57D64CE1383B10101010114D028C9981F7A87F3093672BF0D5B0E2A1B3ED45600010300020114A3B20D0D88B8A58ABC78F145D3A499C8FA17837701010114F2291A94D838F8E222FEFA8550B57D64CE1383B101280EE69579077AAD01C686F04FEFE839D5025DF5CFC646DDD177632966E16F0CB59E9C26ED850D8F8E6EDE4D0E7A1CC13AF418608F77C5E6B55B3966E8A69D02","proof":{"aunts":[]}}}],"peer_key":""}]} +{"time":"2017-04-27T22:24:09.414Z","msg":[1,{"height":4,"round":0,"step":"RoundStepPrevote"}]} +{"time":"2017-04-27T22:24:09.414Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":4,"round":0,"type":1,"block_id":{"hash":"C3918AEACFA8BECF3695D10CC738D6182276CCEA","parts":{"total":1,"hash":"ACB46B8913F0203EB579A9977AF6AF85B6E89705"}},"signature":[1,"2ACD2A20D31464F1A39F82E02EA023C63C5BBBAF12320652CE09A94B07956950B6425C576675E5E3A0BF2E41312527434CD03E7A255F71999D56310AD665EC04"]}}],"peer_key":""}]} +{"time":"2017-04-27T22:24:09.416Z","msg":[1,{"height":4,"round":0,"step":"RoundStepPrecommit"}]} +{"time":"2017-04-27T22:24:09.416Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":4,"round":0,"type":2,"block_id":{"hash":"C3918AEACFA8BECF3695D10CC738D6182276CCEA","parts":{"total":1,"hash":"ACB46B8913F0203EB579A9977AF6AF85B6E89705"}},"signature":[1,"B9E1E611ADE3C020AC6041DB974D7A124CC0BCDF580517697D01B07D7B90AAA186F2F237C0D048BFE384EC75EFA65E56B8E9BE086AEBED74B1C5132CFA119207"]}}],"peer_key":""}]} +{"time":"2017-04-27T22:24:09.417Z","msg":[1,{"height":4,"round":0,"step":"RoundStepCommit"}]} #ENDHEIGHT: 4 -{"time":"2017-02-17T23:54:22.036Z","msg":[1,{"height":5,"round":0,"step":"RoundStepNewHeight"}]} -{"time":"2017-02-17T23:54:23.034Z","msg":[3,{"duration":997096276,"height":5,"round":0,"step":1}]} -{"time":"2017-02-17T23:54:23.035Z","msg":[1,{"height":5,"round":0,"step":"RoundStepPropose"}]} -{"time":"2017-02-17T23:54:23.035Z","msg":[2,{"msg":[17,{"Proposal":{"height":5,"round":0,"block_parts_header":{"total":1,"hash":"A52BAA9C2E52E633A1605F4B930205613E3E7A2F"},"pol_round":-1,"pol_block_id":{"hash":"","parts":{"total":0,"hash":""}},"signature":[1,"32A96AA44440B6FDB28B590A029649CE37B0F1091B9E648658E910207BB2F96E4936102C63F3908942F1A45F52C01231680593FB3E53B8B29BF588A613116A0B"]}}],"peer_key":""}]} -{"time":"2017-02-17T23:54:23.035Z","msg":[2,{"msg":[19,{"Height":5,"Round":0,"Part":{"index":0,"bytes":"0101010F74656E6465726D696E745F74657374010514A43848FAB3E280017A011404715E223BF4327FFA9B0D5AD849B74A099D5DEC0101011424CEBCBEB833F56D47AD14354071B3B7A243068A01144C1EF483E19426AC412E12F33E1D814FD019279801146440978BB85314393E824F6BBAFEE59FA1A5E30A0114354594CBFC1A7BCA1AD0050ED6AA010023EADA390114845C15D3FE4AA16021B85CD0F18E0188A673E73E01017A011E363136323633363433343338333733443634363336323631333433383337011E363136323633363433343338333833443634363336323631333433383338011E363136323633363433343338333933443634363336323631333433383339011E363136323633363433343339333033443634363336323631333433393330011E363136323633363433343339333133443634363336323631333433393331011E363136323633363433343339333233443634363336323631333433393332011E363136323633363433343339333333443634363336323631333433393333011E363136323633363433343339333433443634363336323631333433393334011E363136323633363433343339333533443634363336323631333433393335011E363136323633363433343339333633443634363336323631333433393336011E363136323633363433343339333733443634363336323631333433393337011E363136323633363433343339333833443634363336323631333433393338011E363136323633363433343339333933443634363336323631333433393339011E363136323633363433353330333033443634363336323631333533303330011E363136323633363433353330333133443634363336323631333533303331011E363136323633363433353330333233443634363336323631333533303332011E363136323633363433353330333333443634363336323631333533303333011E363136323633363433353330333433443634363336323631333533303334011E363136323633363433353330333533443634363336323631333533303335011E363136323633363433353330333633443634363336323631333533303336011E363136323633363433353330333733443634363336323631333533303337011E363136323633363433353330333833443634363336323631333533303338011E363136323633363433353330333933443634363336323631333533303339011E363136323633363433353331333033443634363336323631333533313330011E363136323633363433353331333133443634363336323631333533313331011E363136323633363433353331333233443634363336323631333533313332011E363136323633363433353331333333443634363336323631333533313333011E363136323633363433353331333433443634363336323631333533313334011E363136323633363433353331333533443634363336323631333533313335011E363136323633363433353331333633443634363336323631333533313336011E363136323633363433353331333733443634363336323631333533313337011E363136323633363433353331333833443634363336323631333533313338011E363136323633363433353331333933443634363336323631333533313339011E363136323633363433353332333033443634363336323631333533323330011E363136323633363433353332333133443634363336323631333533323331011E363136323633363433353332333233443634363336323631333533323332011E363136323633363433353332333333443634363336323631333533323333011E363136323633363433353332333433443634363336323631333533323334011E363136323633363433353332333533443634363336323631333533323335011E363136323633363433353332333633443634363336323631333533323336011E363136323633363433353332333733443634363336323631333533323337011E363136323633363433353332333833443634363336323631333533323338011E363136323633363433353332333933443634363336323631333533323339011E363136323633363433353333333033443634363336323631333533333330011E363136323633363433353333333133443634363336323631333533333331011E363136323633363433353333333233443634363336323631333533333332011E363136323633363433353333333333443634363336323631333533333333011E363136323633363433353333333433443634363336323631333533333334011E363136323633363433353333333533443634363336323631333533333335011E363136323633363433353333333633443634363336323631333533333336011E363136323633363433353333333733443634363336323631333533333337011E363136323633363433353333333833443634363336323631333533333338011E363136323633363433353333333933443634363336323631333533333339011E363136323633363433353334333033443634363336323631333533343330011E363136323633363433353334333133443634363336323631333533343331011E363136323633363433353334333233443634363336323631333533343332011E363136323633363433353334333333443634363336323631333533343333011E363136323633363433353334333433443634363336323631333533343334011E363136323633363433353334333533443634363336323631333533343335011E363136323633363433353334333633443634363336323631333533343336011E363136323633363433353334333733443634363336323631333533343337011E363136323633363433353334333833443634363336323631333533343338011E363136323633363433353334333933443634363336323631333533343339011E363136323633363433353335333033443634363336323631333533353330011E363136323633363433353335333133443634363336323631333533353331011E363136323633363433353335333233443634363336323631333533353332011E363136323633363433353335333333443634363336323631333533353333011E363136323633363433353335333433443634363336323631333533353334011E363136323633363433353335333533443634363336323631333533353335011E363136323633363433353335333633443634363336323631333533353336011E363136323633363433353335333733443634363336323631333533353337011E363136323633363433353335333833443634363336323631333533353338011E363136323633363433353335333933443634363336323631333533353339011E363136323633363433353336333033443634363336323631333533363330011E363136323633363433353336333133443634363336323631333533363331011E363136323633363433353336333233443634363336323631333533363332011E363136323633363433353336333333443634363336323631333533363333011E363136323633363433353336333433443634363336323631333533363334011E363136323633363433353336333533443634363336323631333533363335011E363136323633363433353336333633443634363336323631333533363336011E363136323633363433353336333733443634363336323631333533363337011E363136323633363433353336333833443634363336323631333533363338011E363136323633363433353336333933443634363336323631333533363339011E363136323633363433353337333033443634363336323631333533373330011E363136323633363433353337333133443634363336323631333533373331011E363136323633363433353337333233443634363336323631333533373332011E363136323633363433353337333333443634363336323631333533373333011E363136323633363433353337333433443634363336323631333533373334011E363136323633363433353337333533443634363336323631333533373335011E363136323633363433353337333633443634363336323631333533373336011E363136323633363433353337333733443634363336323631333533373337011E363136323633363433353337333833443634363336323631333533373338011E363136323633363433353337333933443634363336323631333533373339011E363136323633363433353338333033443634363336323631333533383330011E363136323633363433353338333133443634363336323631333533383331011E363136323633363433353338333233443634363336323631333533383332011E363136323633363433353338333333443634363336323631333533383333011E363136323633363433353338333433443634363336323631333533383334011E363136323633363433353338333533443634363336323631333533383335011E363136323633363433353338333633443634363336323631333533383336011E363136323633363433353338333733443634363336323631333533383337011E363136323633363433353338333833443634363336323631333533383338011E363136323633363433353338333933443634363336323631333533383339011E363136323633363433353339333033443634363336323631333533393330011E363136323633363433353339333133443634363336323631333533393331011E363136323633363433353339333233443634363336323631333533393332011E363136323633363433353339333333443634363336323631333533393333011E363136323633363433353339333433443634363336323631333533393334011E363136323633363433353339333533443634363336323631333533393335011E363136323633363433353339333633443634363336323631333533393336011E363136323633363433353339333733443634363336323631333533393337011E363136323633363433353339333833443634363336323631333533393338011E363136323633363433353339333933443634363336323631333533393339011E363136323633363433363330333033443634363336323631333633303330011E363136323633363433363330333133443634363336323631333633303331011E363136323633363433363330333233443634363336323631333633303332011E363136323633363433363330333333443634363336323631333633303333011E363136323633363433363330333433443634363336323631333633303334011E363136323633363433363330333533443634363336323631333633303335011E363136323633363433363330333633443634363336323631333633303336011E363136323633363433363330333733443634363336323631333633303337011E36313632363336343336333033383344363436333632363133363330333801011404715E223BF4327FFA9B0D5AD849B74A099D5DEC0101011424CEBCBEB833F56D47AD14354071B3B7A243068A0101010114D028C9981F7A87F3093672BF0D5B0E2A1B3ED4560001040002011404715E223BF4327FFA9B0D5AD849B74A099D5DEC0101011424CEBCBEB833F56D47AD14354071B3B7A243068A01F544743F17479A61F94B0F68C63D254BD60493D78E818D48A5859133619AEE5E92C47CAD89C654DF64E0911C3152091E047555D5F14655D95B9681AE9B336505","proof":{"aunts":[]}}}],"peer_key":""}]} -{"time":"2017-02-17T23:54:23.037Z","msg":[1,{"height":5,"round":0,"step":"RoundStepPrevote"}]} -{"time":"2017-02-17T23:54:23.037Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":5,"round":0,"type":1,"block_id":{"hash":"FDC6D837995BEBBBFCBF3E7D7CF44F8FDA448543","parts":{"total":1,"hash":"A52BAA9C2E52E633A1605F4B930205613E3E7A2F"}},"signature":[1,"684AB4918389E06ADD5DCC4EFCCD0464EAE2BC4212344D88694706837A4D47D484747C7B5906537181E0FBD35EF78EDF673E8492C6E875BB33934456A8254B03"]}}],"peer_key":""}]} -{"time":"2017-02-17T23:54:23.038Z","msg":[1,{"height":5,"round":0,"step":"RoundStepPrecommit"}]} -{"time":"2017-02-17T23:54:23.038Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":5,"round":0,"type":2,"block_id":{"hash":"FDC6D837995BEBBBFCBF3E7D7CF44F8FDA448543","parts":{"total":1,"hash":"A52BAA9C2E52E633A1605F4B930205613E3E7A2F"}},"signature":[1,"DF51D23D5D2C57598F67791D953A6C2D9FC5865A3048ADA4469B37500D2996B95732E0DC6F99EAEAEA12B4818CE355C7B701D16857D2AC767D740C2E30E9260C"]}}],"peer_key":""}]} -{"time":"2017-02-17T23:54:23.038Z","msg":[1,{"height":5,"round":0,"step":"RoundStepCommit"}]} +{"time":"2017-04-27T22:24:09.431Z","msg":[1,{"height":5,"round":0,"step":"RoundStepNewHeight"}]} +{"time":"2017-04-27T22:24:10.417Z","msg":[3,{"duration":985803235,"height":5,"round":0,"step":1}]} +{"time":"2017-04-27T22:24:10.418Z","msg":[1,{"height":5,"round":0,"step":"RoundStepPropose"}]} +{"time":"2017-04-27T22:24:10.418Z","msg":[2,{"msg":[17,{"Proposal":{"height":5,"round":0,"block_parts_header":{"total":1,"hash":"DC0AAD92EA45834EB90563B51F5FCB8F6CE6A6B2"},"pol_round":-1,"pol_block_id":{"hash":"","parts":{"total":0,"hash":""}},"signature":[1,"F7799D9885B354FF90772DA770768624E311398DA0FEF0E28C02934AAE32D0D183BEEB304022EC721FED3FE429C7F184F1A22EE6E83E1DC5D5C66500C138EF05"]}}],"peer_key":""}]} +{"time":"2017-04-27T22:24:10.419Z","msg":[2,{"msg":[19,{"Height":5,"Round":0,"Part":{"index":0,"bytes":"0101010F74656E6465726D696E745F74657374010514B96167EBE1CE40016B0114C3918AEACFA8BECF3695D10CC738D6182276CCEA01010114ACB46B8913F0203EB579A9977AF6AF85B6E897050114D4A14D12F28D02E3B707954EE2D8B1794C45FBDB0114EB7BE3102D05EFCE8D70D4033995393C3D6A6ECA0114354594CBFC1A7BCA1AD0050ED6AA010023EADA3901145DC8B2DF900A8E6A1DC37B2EE9D4B8860070759A01016B011E363136323633363433343331333133443634363336323631333433313331011E363136323633363433343331333233443634363336323631333433313332011E363136323633363433343331333333443634363336323631333433313333011E363136323633363433343331333433443634363336323631333433313334011E363136323633363433343331333533443634363336323631333433313335011E363136323633363433343331333633443634363336323631333433313336011E363136323633363433343331333733443634363336323631333433313337011E363136323633363433343331333833443634363336323631333433313338011E363136323633363433343331333933443634363336323631333433313339011E363136323633363433343332333033443634363336323631333433323330011E363136323633363433343332333133443634363336323631333433323331011E363136323633363433343332333233443634363336323631333433323332011E363136323633363433343332333333443634363336323631333433323333011E363136323633363433343332333433443634363336323631333433323334011E363136323633363433343332333533443634363336323631333433323335011E363136323633363433343332333633443634363336323631333433323336011E363136323633363433343332333733443634363336323631333433323337011E363136323633363433343332333833443634363336323631333433323338011E363136323633363433343332333933443634363336323631333433323339011E363136323633363433343333333033443634363336323631333433333330011E363136323633363433343333333133443634363336323631333433333331011E363136323633363433343333333233443634363336323631333433333332011E363136323633363433343333333333443634363336323631333433333333011E363136323633363433343333333433443634363336323631333433333334011E363136323633363433343333333533443634363336323631333433333335011E363136323633363433343333333633443634363336323631333433333336011E363136323633363433343333333733443634363336323631333433333337011E363136323633363433343333333833443634363336323631333433333338011E363136323633363433343333333933443634363336323631333433333339011E363136323633363433343334333033443634363336323631333433343330011E363136323633363433343334333133443634363336323631333433343331011E363136323633363433343334333233443634363336323631333433343332011E363136323633363433343334333333443634363336323631333433343333011E363136323633363433343334333433443634363336323631333433343334011E363136323633363433343334333533443634363336323631333433343335011E363136323633363433343334333633443634363336323631333433343336011E363136323633363433343334333733443634363336323631333433343337011E363136323633363433343334333833443634363336323631333433343338011E363136323633363433343334333933443634363336323631333433343339011E363136323633363433343335333033443634363336323631333433353330011E363136323633363433343335333133443634363336323631333433353331011E363136323633363433343335333233443634363336323631333433353332011E363136323633363433343335333333443634363336323631333433353333011E363136323633363433343335333433443634363336323631333433353334011E363136323633363433343335333533443634363336323631333433353335011E363136323633363433343335333633443634363336323631333433353336011E363136323633363433343335333733443634363336323631333433353337011E363136323633363433343335333833443634363336323631333433353338011E363136323633363433343335333933443634363336323631333433353339011E363136323633363433343336333033443634363336323631333433363330011E363136323633363433343336333133443634363336323631333433363331011E363136323633363433343336333233443634363336323631333433363332011E363136323633363433343336333333443634363336323631333433363333011E363136323633363433343336333433443634363336323631333433363334011E363136323633363433343336333533443634363336323631333433363335011E363136323633363433343336333633443634363336323631333433363336011E363136323633363433343336333733443634363336323631333433363337011E363136323633363433343336333833443634363336323631333433363338011E363136323633363433343336333933443634363336323631333433363339011E363136323633363433343337333033443634363336323631333433373330011E363136323633363433343337333133443634363336323631333433373331011E363136323633363433343337333233443634363336323631333433373332011E363136323633363433343337333333443634363336323631333433373333011E363136323633363433343337333433443634363336323631333433373334011E363136323633363433343337333533443634363336323631333433373335011E363136323633363433343337333633443634363336323631333433373336011E363136323633363433343337333733443634363336323631333433373337011E363136323633363433343337333833443634363336323631333433373338011E363136323633363433343337333933443634363336323631333433373339011E363136323633363433343338333033443634363336323631333433383330011E363136323633363433343338333133443634363336323631333433383331011E363136323633363433343338333233443634363336323631333433383332011E363136323633363433343338333333443634363336323631333433383333011E363136323633363433343338333433443634363336323631333433383334011E363136323633363433343338333533443634363336323631333433383335011E363136323633363433343338333633443634363336323631333433383336011E363136323633363433343338333733443634363336323631333433383337011E363136323633363433343338333833443634363336323631333433383338011E363136323633363433343338333933443634363336323631333433383339011E363136323633363433343339333033443634363336323631333433393330011E363136323633363433343339333133443634363336323631333433393331011E363136323633363433343339333233443634363336323631333433393332011E363136323633363433343339333333443634363336323631333433393333011E363136323633363433343339333433443634363336323631333433393334011E363136323633363433343339333533443634363336323631333433393335011E363136323633363433343339333633443634363336323631333433393336011E363136323633363433343339333733443634363336323631333433393337011E363136323633363433343339333833443634363336323631333433393338011E363136323633363433343339333933443634363336323631333433393339011E363136323633363433353330333033443634363336323631333533303330011E363136323633363433353330333133443634363336323631333533303331011E363136323633363433353330333233443634363336323631333533303332011E363136323633363433353330333333443634363336323631333533303333011E363136323633363433353330333433443634363336323631333533303334011E363136323633363433353330333533443634363336323631333533303335011E363136323633363433353330333633443634363336323631333533303336011E363136323633363433353330333733443634363336323631333533303337011E363136323633363433353330333833443634363336323631333533303338011E363136323633363433353330333933443634363336323631333533303339011E363136323633363433353331333033443634363336323631333533313330011E363136323633363433353331333133443634363336323631333533313331011E363136323633363433353331333233443634363336323631333533313332011E363136323633363433353331333333443634363336323631333533313333011E363136323633363433353331333433443634363336323631333533313334011E363136323633363433353331333533443634363336323631333533313335011E363136323633363433353331333633443634363336323631333533313336011E363136323633363433353331333733443634363336323631333533313337010114C3918AEACFA8BECF3695D10CC738D6182276CCEA01010114ACB46B8913F0203EB579A9977AF6AF85B6E897050101010114D028C9981F7A87F3093672BF0D5B0E2A1B3ED45600010400020114C3918AEACFA8BECF3695D10CC738D6182276CCEA01010114ACB46B8913F0203EB579A9977AF6AF85B6E8970501B9E1E611ADE3C020AC6041DB974D7A124CC0BCDF580517697D01B07D7B90AAA186F2F237C0D048BFE384EC75EFA65E56B8E9BE086AEBED74B1C5132CFA119207","proof":{"aunts":[]}}}],"peer_key":""}]} +{"time":"2017-04-27T22:24:10.420Z","msg":[1,{"height":5,"round":0,"step":"RoundStepPrevote"}]} +{"time":"2017-04-27T22:24:10.420Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":5,"round":0,"type":1,"block_id":{"hash":"29C2401351653BDD300FDA82FF670747DEE0D6BD","parts":{"total":1,"hash":"DC0AAD92EA45834EB90563B51F5FCB8F6CE6A6B2"}},"signature":[1,"3C5A5D4A84520A495F1239FD3B166C1F38226578C0BEF7F7953B2995BF274C5A5A7A222E2433BE8DA08321F838C69C4FDC8A3767D072D3CCD260F435F4065E0E"]}}],"peer_key":""}]} +{"time":"2017-04-27T22:24:10.421Z","msg":[1,{"height":5,"round":0,"step":"RoundStepPrecommit"}]} +{"time":"2017-04-27T22:24:10.421Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":5,"round":0,"type":2,"block_id":{"hash":"29C2401351653BDD300FDA82FF670747DEE0D6BD","parts":{"total":1,"hash":"DC0AAD92EA45834EB90563B51F5FCB8F6CE6A6B2"}},"signature":[1,"5FFD69406ABEE706DD424F69E6D2A94A7ED8566D4A2A936A160BF7C574B7371C53CDC75B739D173EC456ECBBC84A4745CAAAB55D9CEA0BD4AD91FB04A8300406"]}}],"peer_key":""}]} +{"time":"2017-04-27T22:24:10.422Z","msg":[1,{"height":5,"round":0,"step":"RoundStepCommit"}]} #ENDHEIGHT: 5 -{"time":"2017-02-17T23:54:23.041Z","msg":[1,{"height":6,"round":0,"step":"RoundStepNewHeight"}]} -{"time":"2017-02-17T23:54:24.038Z","msg":[3,{"duration":997341910,"height":6,"round":0,"step":1}]} -{"time":"2017-02-17T23:54:24.040Z","msg":[1,{"height":6,"round":0,"step":"RoundStepPropose"}]} -{"time":"2017-02-17T23:54:24.040Z","msg":[2,{"msg":[17,{"Proposal":{"height":6,"round":0,"block_parts_header":{"total":1,"hash":"EA1E4111198195006BF7C23322B1051BE6C11582"},"pol_round":-1,"pol_block_id":{"hash":"","parts":{"total":0,"hash":""}},"signature":[1,"571309E5959472CF453B83BB00F75BFAE9ACA8981279CBCBF19FD1A104BAD544D43A4F67FC54C17C9D51CEE821E4F514A1742FA5220EFF432C334D81B03B4C08"]}}],"peer_key":""}]} -{"time":"2017-02-17T23:54:24.040Z","msg":[2,{"msg":[19,{"Height":6,"Round":0,"Part":{"index":0,"bytes":"0101010F74656E6465726D696E745F74657374010614A43849369AF7C0018C0114FDC6D837995BEBBBFCBF3E7D7CF44F8FDA44854301010114A52BAA9C2E52E633A1605F4B930205613E3E7A2F0114AD3EFC80659CF2DCB932CAAA832249B1100C7D0901149D3F259328643A0DA0B83CF23A1AC918965E393D0114354594CBFC1A7BCA1AD0050ED6AA010023EADA390114BFB5455B51A6694370771F5072E0204CE75E6C6901018C011E363136323633363433363330333933443634363336323631333633303339011E363136323633363433363331333033443634363336323631333633313330011E363136323633363433363331333133443634363336323631333633313331011E363136323633363433363331333233443634363336323631333633313332011E363136323633363433363331333333443634363336323631333633313333011E363136323633363433363331333433443634363336323631333633313334011E363136323633363433363331333533443634363336323631333633313335011E363136323633363433363331333633443634363336323631333633313336011E363136323633363433363331333733443634363336323631333633313337011E363136323633363433363331333833443634363336323631333633313338011E363136323633363433363331333933443634363336323631333633313339011E363136323633363433363332333033443634363336323631333633323330011E363136323633363433363332333133443634363336323631333633323331011E363136323633363433363332333233443634363336323631333633323332011E363136323633363433363332333333443634363336323631333633323333011E363136323633363433363332333433443634363336323631333633323334011E363136323633363433363332333533443634363336323631333633323335011E363136323633363433363332333633443634363336323631333633323336011E363136323633363433363332333733443634363336323631333633323337011E363136323633363433363332333833443634363336323631333633323338011E363136323633363433363332333933443634363336323631333633323339011E363136323633363433363333333033443634363336323631333633333330011E363136323633363433363333333133443634363336323631333633333331011E363136323633363433363333333233443634363336323631333633333332011E363136323633363433363333333333443634363336323631333633333333011E363136323633363433363333333433443634363336323631333633333334011E363136323633363433363333333533443634363336323631333633333335011E363136323633363433363333333633443634363336323631333633333336011E363136323633363433363333333733443634363336323631333633333337011E363136323633363433363333333833443634363336323631333633333338011E363136323633363433363333333933443634363336323631333633333339011E363136323633363433363334333033443634363336323631333633343330011E363136323633363433363334333133443634363336323631333633343331011E363136323633363433363334333233443634363336323631333633343332011E363136323633363433363334333333443634363336323631333633343333011E363136323633363433363334333433443634363336323631333633343334011E363136323633363433363334333533443634363336323631333633343335011E363136323633363433363334333633443634363336323631333633343336011E363136323633363433363334333733443634363336323631333633343337011E363136323633363433363334333833443634363336323631333633343338011E363136323633363433363334333933443634363336323631333633343339011E363136323633363433363335333033443634363336323631333633353330011E363136323633363433363335333133443634363336323631333633353331011E363136323633363433363335333233443634363336323631333633353332011E363136323633363433363335333333443634363336323631333633353333011E363136323633363433363335333433443634363336323631333633353334011E363136323633363433363335333533443634363336323631333633353335011E363136323633363433363335333633443634363336323631333633353336011E363136323633363433363335333733443634363336323631333633353337011E363136323633363433363335333833443634363336323631333633353338011E363136323633363433363335333933443634363336323631333633353339011E363136323633363433363336333033443634363336323631333633363330011E363136323633363433363336333133443634363336323631333633363331011E363136323633363433363336333233443634363336323631333633363332011E363136323633363433363336333333443634363336323631333633363333011E363136323633363433363336333433443634363336323631333633363334011E363136323633363433363336333533443634363336323631333633363335011E363136323633363433363336333633443634363336323631333633363336011E363136323633363433363336333733443634363336323631333633363337011E363136323633363433363336333833443634363336323631333633363338011E363136323633363433363336333933443634363336323631333633363339011E363136323633363433363337333033443634363336323631333633373330011E363136323633363433363337333133443634363336323631333633373331011E363136323633363433363337333233443634363336323631333633373332011E363136323633363433363337333333443634363336323631333633373333011E363136323633363433363337333433443634363336323631333633373334011E363136323633363433363337333533443634363336323631333633373335011E363136323633363433363337333633443634363336323631333633373336011E363136323633363433363337333733443634363336323631333633373337011E363136323633363433363337333833443634363336323631333633373338011E363136323633363433363337333933443634363336323631333633373339011E363136323633363433363338333033443634363336323631333633383330011E363136323633363433363338333133443634363336323631333633383331011E363136323633363433363338333233443634363336323631333633383332011E363136323633363433363338333333443634363336323631333633383333011E363136323633363433363338333433443634363336323631333633383334011E363136323633363433363338333533443634363336323631333633383335011E363136323633363433363338333633443634363336323631333633383336011E363136323633363433363338333733443634363336323631333633383337011E363136323633363433363338333833443634363336323631333633383338011E363136323633363433363338333933443634363336323631333633383339011E363136323633363433363339333033443634363336323631333633393330011E363136323633363433363339333133443634363336323631333633393331011E363136323633363433363339333233443634363336323631333633393332011E363136323633363433363339333333443634363336323631333633393333011E363136323633363433363339333433443634363336323631333633393334011E363136323633363433363339333533443634363336323631333633393335011E363136323633363433363339333633443634363336323631333633393336011E363136323633363433363339333733443634363336323631333633393337011E363136323633363433363339333833443634363336323631333633393338011E363136323633363433363339333933443634363336323631333633393339011E363136323633363433373330333033443634363336323631333733303330011E363136323633363433373330333133443634363336323631333733303331011E363136323633363433373330333233443634363336323631333733303332011E363136323633363433373330333333443634363336323631333733303333011E363136323633363433373330333433443634363336323631333733303334011E363136323633363433373330333533443634363336323631333733303335011E363136323633363433373330333633443634363336323631333733303336011E363136323633363433373330333733443634363336323631333733303337011E363136323633363433373330333833443634363336323631333733303338011E363136323633363433373330333933443634363336323631333733303339011E363136323633363433373331333033443634363336323631333733313330011E363136323633363433373331333133443634363336323631333733313331011E363136323633363433373331333233443634363336323631333733313332011E363136323633363433373331333333443634363336323631333733313333011E363136323633363433373331333433443634363336323631333733313334011E363136323633363433373331333533443634363336323631333733313335011E363136323633363433373331333633443634363336323631333733313336011E363136323633363433373331333733443634363336323631333733313337011E363136323633363433373331333833443634363336323631333733313338011E363136323633363433373331333933443634363336323631333733313339011E363136323633363433373332333033443634363336323631333733323330011E363136323633363433373332333133443634363336323631333733323331011E363136323633363433373332333233443634363336323631333733323332011E363136323633363433373332333333443634363336323631333733323333011E363136323633363433373332333433443634363336323631333733323334011E363136323633363433373332333533443634363336323631333733323335011E363136323633363433373332333633443634363336323631333733323336011E363136323633363433373332333733443634363336323631333733323337011E363136323633363433373332333833443634363336323631333733323338011E363136323633363433373332333933443634363336323631333733323339011E363136323633363433373333333033443634363336323631333733333330011E363136323633363433373333333133443634363336323631333733333331011E363136323633363433373333333233443634363336323631333733333332011E363136323633363433373333333333443634363336323631333733333333011E363136323633363433373333333433443634363336323631333733333334011E363136323633363433373333333533443634363336323631333733333335011E363136323633363433373333333633443634363336323631333733333336011E363136323633363433373333333733443634363336323631333733333337011E363136323633363433373333333833443634363336323631333733333338011E363136323633363433373333333933443634363336323631333733333339011E363136323633363433373334333033443634363336323631333733343330011E363136323633363433373334333133443634363336323631333733343331011E363136323633363433373334333233443634363336323631333733343332011E363136323633363433373334333333443634363336323631333733343333011E363136323633363433373334333433443634363336323631333733343334011E363136323633363433373334333533443634363336323631333733343335011E363136323633363433373334333633443634363336323631333733343336011E363136323633363433373334333733443634363336323631333733343337011E363136323633363433373334333833443634363336323631333733343338010114FDC6D837995BEBBBFCBF3E7D7CF44F8FDA44854301010114A52BAA9C2E52E633A1605F4B930205613E3E7A2F0101010114D028C9981F7A87F3093672BF0D5B0E2A1B3ED45600010500020114FDC6D837995BEBBBFCBF3E7D7CF44F8FDA44854301010114A52BAA9C2E52E633A1605F4B930205613E3E7A2F01DF51D23D5D2C57598F67791D953A6C2D9FC5865A3048ADA4469B37500D2996B95732E0DC6F99EAEAEA12B4818CE355C7B701D16857D2AC767D740C2E30E9260C","proof":{"aunts":[]}}}],"peer_key":""}]} -{"time":"2017-02-17T23:54:24.041Z","msg":[1,{"height":6,"round":0,"step":"RoundStepPrevote"}]} -{"time":"2017-02-17T23:54:24.041Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":6,"round":0,"type":1,"block_id":{"hash":"1F7C249FF99B67AC57C4EEC94C42E0B95C9AFB6B","parts":{"total":1,"hash":"EA1E4111198195006BF7C23322B1051BE6C11582"}},"signature":[1,"1F79910354E1F4ACA11FC16DBA1ED6F75063A15BF8093C4AAEF87F69B3990F65E51FFC8B35A409838ECD0FF3C26E87637B068D0DC7E5863D5F1CF97826222300"]}}],"peer_key":""}]} -{"time":"2017-02-17T23:54:24.042Z","msg":[1,{"height":6,"round":0,"step":"RoundStepPrecommit"}]} -{"time":"2017-02-17T23:54:24.042Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":6,"round":0,"type":2,"block_id":{"hash":"1F7C249FF99B67AC57C4EEC94C42E0B95C9AFB6B","parts":{"total":1,"hash":"EA1E4111198195006BF7C23322B1051BE6C11582"}},"signature":[1,"E7838F403E4D5E651317D8563355CB2E140409B1B471B4AC12EBF7085989228CFA062029DF78A405CF977925777177D876804D78D80DF2312977E6D804394A0E"]}}],"peer_key":""}]} -{"time":"2017-02-17T23:54:24.042Z","msg":[1,{"height":6,"round":0,"step":"RoundStepCommit"}]} +{"time":"2017-04-27T22:24:10.432Z","msg":[1,{"height":6,"round":0,"step":"RoundStepNewHeight"}]} +{"time":"2017-04-27T22:24:11.422Z","msg":[3,{"duration":989935903,"height":6,"round":0,"step":1}]} +{"time":"2017-04-27T22:24:11.424Z","msg":[1,{"height":6,"round":0,"step":"RoundStepPropose"}]} +{"time":"2017-04-27T22:24:11.424Z","msg":[2,{"msg":[17,{"Proposal":{"height":6,"round":0,"block_parts_header":{"total":1,"hash":"37436A7FCDB02F18074E8D2C90E9F004BBCB534E"},"pol_round":-1,"pol_block_id":{"hash":"","parts":{"total":0,"hash":""}},"signature":[1,"11204470769A82145069D6F08BF1B5C62E86EB0016E820FC2B4BDDA283F1B9CD4A35DA897E7624AC35D48026A1D73FDBAA19F5E43E89D63310C16168A5E7460D"]}}],"peer_key":""}]} +{"time":"2017-04-27T22:24:11.424Z","msg":[2,{"msg":[19,{"Height":6,"Round":0,"Part":{"index":0,"bytes":"0101010F74656E6465726D696E745F74657374010614B9616827C8E3800171011429C2401351653BDD300FDA82FF670747DEE0D6BD01010114DC0AAD92EA45834EB90563B51F5FCB8F6CE6A6B201147EF9A4B59129B957565C5AEA8F67911AD0672C3C011463CBE710CCF92C056DECC32112CC3A64F3F191560114354594CBFC1A7BCA1AD0050ED6AA010023EADA3901141EF14BB9890DC775E68CB57C86BA2A9118573099010171011E363136323633363433353331333833443634363336323631333533313338011E363136323633363433353331333933443634363336323631333533313339011E363136323633363433353332333033443634363336323631333533323330011E363136323633363433353332333133443634363336323631333533323331011E363136323633363433353332333233443634363336323631333533323332011E363136323633363433353332333333443634363336323631333533323333011E363136323633363433353332333433443634363336323631333533323334011E363136323633363433353332333533443634363336323631333533323335011E363136323633363433353332333633443634363336323631333533323336011E363136323633363433353332333733443634363336323631333533323337011E363136323633363433353332333833443634363336323631333533323338011E363136323633363433353332333933443634363336323631333533323339011E363136323633363433353333333033443634363336323631333533333330011E363136323633363433353333333133443634363336323631333533333331011E363136323633363433353333333233443634363336323631333533333332011E363136323633363433353333333333443634363336323631333533333333011E363136323633363433353333333433443634363336323631333533333334011E363136323633363433353333333533443634363336323631333533333335011E363136323633363433353333333633443634363336323631333533333336011E363136323633363433353333333733443634363336323631333533333337011E363136323633363433353333333833443634363336323631333533333338011E363136323633363433353333333933443634363336323631333533333339011E363136323633363433353334333033443634363336323631333533343330011E363136323633363433353334333133443634363336323631333533343331011E363136323633363433353334333233443634363336323631333533343332011E363136323633363433353334333333443634363336323631333533343333011E363136323633363433353334333433443634363336323631333533343334011E363136323633363433353334333533443634363336323631333533343335011E363136323633363433353334333633443634363336323631333533343336011E363136323633363433353334333733443634363336323631333533343337011E363136323633363433353334333833443634363336323631333533343338011E363136323633363433353334333933443634363336323631333533343339011E363136323633363433353335333033443634363336323631333533353330011E363136323633363433353335333133443634363336323631333533353331011E363136323633363433353335333233443634363336323631333533353332011E363136323633363433353335333333443634363336323631333533353333011E363136323633363433353335333433443634363336323631333533353334011E363136323633363433353335333533443634363336323631333533353335011E363136323633363433353335333633443634363336323631333533353336011E363136323633363433353335333733443634363336323631333533353337011E363136323633363433353335333833443634363336323631333533353338011E363136323633363433353335333933443634363336323631333533353339011E363136323633363433353336333033443634363336323631333533363330011E363136323633363433353336333133443634363336323631333533363331011E363136323633363433353336333233443634363336323631333533363332011E363136323633363433353336333333443634363336323631333533363333011E363136323633363433353336333433443634363336323631333533363334011E363136323633363433353336333533443634363336323631333533363335011E363136323633363433353336333633443634363336323631333533363336011E363136323633363433353336333733443634363336323631333533363337011E363136323633363433353336333833443634363336323631333533363338011E363136323633363433353336333933443634363336323631333533363339011E363136323633363433353337333033443634363336323631333533373330011E363136323633363433353337333133443634363336323631333533373331011E363136323633363433353337333233443634363336323631333533373332011E363136323633363433353337333333443634363336323631333533373333011E363136323633363433353337333433443634363336323631333533373334011E363136323633363433353337333533443634363336323631333533373335011E363136323633363433353337333633443634363336323631333533373336011E363136323633363433353337333733443634363336323631333533373337011E363136323633363433353337333833443634363336323631333533373338011E363136323633363433353337333933443634363336323631333533373339011E363136323633363433353338333033443634363336323631333533383330011E363136323633363433353338333133443634363336323631333533383331011E363136323633363433353338333233443634363336323631333533383332011E363136323633363433353338333333443634363336323631333533383333011E363136323633363433353338333433443634363336323631333533383334011E363136323633363433353338333533443634363336323631333533383335011E363136323633363433353338333633443634363336323631333533383336011E363136323633363433353338333733443634363336323631333533383337011E363136323633363433353338333833443634363336323631333533383338011E363136323633363433353338333933443634363336323631333533383339011E363136323633363433353339333033443634363336323631333533393330011E363136323633363433353339333133443634363336323631333533393331011E363136323633363433353339333233443634363336323631333533393332011E363136323633363433353339333333443634363336323631333533393333011E363136323633363433353339333433443634363336323631333533393334011E363136323633363433353339333533443634363336323631333533393335011E363136323633363433353339333633443634363336323631333533393336011E363136323633363433353339333733443634363336323631333533393337011E363136323633363433353339333833443634363336323631333533393338011E363136323633363433353339333933443634363336323631333533393339011E363136323633363433363330333033443634363336323631333633303330011E363136323633363433363330333133443634363336323631333633303331011E363136323633363433363330333233443634363336323631333633303332011E363136323633363433363330333333443634363336323631333633303333011E363136323633363433363330333433443634363336323631333633303334011E363136323633363433363330333533443634363336323631333633303335011E363136323633363433363330333633443634363336323631333633303336011E363136323633363433363330333733443634363336323631333633303337011E363136323633363433363330333833443634363336323631333633303338011E363136323633363433363330333933443634363336323631333633303339011E363136323633363433363331333033443634363336323631333633313330011E363136323633363433363331333133443634363336323631333633313331011E363136323633363433363331333233443634363336323631333633313332011E363136323633363433363331333333443634363336323631333633313333011E363136323633363433363331333433443634363336323631333633313334011E363136323633363433363331333533443634363336323631333633313335011E363136323633363433363331333633443634363336323631333633313336011E363136323633363433363331333733443634363336323631333633313337011E363136323633363433363331333833443634363336323631333633313338011E363136323633363433363331333933443634363336323631333633313339011E363136323633363433363332333033443634363336323631333633323330011E363136323633363433363332333133443634363336323631333633323331011E363136323633363433363332333233443634363336323631333633323332011E363136323633363433363332333333443634363336323631333633323333011E363136323633363433363332333433443634363336323631333633323334011E363136323633363433363332333533443634363336323631333633323335011E363136323633363433363332333633443634363336323631333633323336011E363136323633363433363332333733443634363336323631333633323337011E363136323633363433363332333833443634363336323631333633323338011E363136323633363433363332333933443634363336323631333633323339011E36313632363336343336333333303344363436333632363133363333333001011429C2401351653BDD300FDA82FF670747DEE0D6BD01010114DC0AAD92EA45834EB90563B51F5FCB8F6CE6A6B20101010114D028C9981F7A87F3093672BF0D5B0E2A1B3ED4560001050002011429C2401351653BDD300FDA82FF670747DEE0D6BD01010114DC0AAD92EA45834EB90563B51F5FCB8F6CE6A6B2015FFD69406ABEE706DD424F69E6D2A94A7ED8566D4A2A936A160BF7C574B7371C53CDC75B739D173EC456ECBBC84A4745CAAAB55D9CEA0BD4AD91FB04A8300406","proof":{"aunts":[]}}}],"peer_key":""}]} +{"time":"2017-04-27T22:24:11.425Z","msg":[1,{"height":6,"round":0,"step":"RoundStepPrevote"}]} +{"time":"2017-04-27T22:24:11.425Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":6,"round":0,"type":1,"block_id":{"hash":"01CA8EA6995CA94535B20FFD04123D5CB68C0469","parts":{"total":1,"hash":"37436A7FCDB02F18074E8D2C90E9F004BBCB534E"}},"signature":[1,"F5C420BC1E1A6C6A9715756B0D71AF5481893150BCBA3F7702B1EB60D5077E66128B432064331C8B8AA46366C383666BDC5AFE56502233E9CAD0B6A6FB1BFF01"]}}],"peer_key":""}]} +{"time":"2017-04-27T22:24:11.427Z","msg":[1,{"height":6,"round":0,"step":"RoundStepPrecommit"}]} +{"time":"2017-04-27T22:24:11.427Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":6,"round":0,"type":2,"block_id":{"hash":"01CA8EA6995CA94535B20FFD04123D5CB68C0469","parts":{"total":1,"hash":"37436A7FCDB02F18074E8D2C90E9F004BBCB534E"}},"signature":[1,"43C023CF88559C0BEA31FB11DD304279389373B856A5FEB56CB1BCDFCED9E01E1F46251753CE57E76EEF2616DE2F7511148A14B14B389D43CF224B2BD4571B00"]}}],"peer_key":""}]} +{"time":"2017-04-27T22:24:11.427Z","msg":[1,{"height":6,"round":0,"step":"RoundStepCommit"}]} diff --git a/consensus/test_data/small_block1.cswal b/consensus/test_data/small_block1.cswal index d4eff73f1..94ccf712b 100644 --- a/consensus/test_data/small_block1.cswal +++ b/consensus/test_data/small_block1.cswal @@ -1,10 +1,10 @@ #ENDHEIGHT: 0 -{"time":"2016-12-18T05:05:38.593Z","msg":[3,{"duration":970717663,"height":1,"round":0,"step":1}]} -{"time":"2016-12-18T05:05:38.595Z","msg":[1,{"height":1,"round":0,"step":"RoundStepPropose"}]} -{"time":"2016-12-18T05:05:38.595Z","msg":[2,{"msg":[17,{"Proposal":{"height":1,"round":0,"block_parts_header":{"total":1,"hash":"A434EC796DF1CECC01296E953839C4675863A4E5"},"pol_round":-1,"pol_block_id":{"hash":"","parts":{"total":0,"hash":""}},"signature":[1,"39563C3C7EDD9855B2971457A5DABF05CFDAF52805658847EB1F05115B8341344A77761CC85E670AF1B679DA9FC0905231957174699FE8326DBE7706209BDD0B"]}}],"peer_key":""}]} -{"time":"2016-12-18T05:05:38.595Z","msg":[2,{"msg":[19,{"Height":1,"Round":0,"Part":{"index":0,"bytes":"0101010F74656E6465726D696E745F7465737401011491414A07A14A400195000000000114F27F65C16210AA65ACBBB6F0DFF88981B292A6D40114354594CBFC1A7BCA1AD0050ED6AA010023EADA3900010195010D6162636431333D646362613133010D6162636431343D646362613134010D6162636431353D646362613135010D6162636431363D646362613136010D6162636431373D646362613137010D6162636431383D646362613138010D6162636431393D646362613139010D6162636432303D646362613230010D6162636432313D646362613231010D6162636432323D646362613232010D6162636432333D646362613233010D6162636432343D646362613234010D6162636432353D646362613235010D6162636432363D646362613236010D6162636432373D646362613237010D6162636432383D646362613238010D6162636432393D646362613239010D6162636433303D646362613330010D6162636433313D646362613331010D6162636433323D646362613332010D6162636433333D646362613333010D6162636433343D646362613334010D6162636433353D646362613335010D6162636433363D646362613336010D6162636433373D646362613337010D6162636433383D646362613338010D6162636433393D646362613339010D6162636434303D646362613430010D6162636434313D646362613431010D6162636434323D646362613432010D6162636434333D646362613433010D6162636434343D646362613434010D6162636434353D646362613435010D6162636434363D646362613436010D6162636434373D646362613437010D6162636434383D646362613438010D6162636434393D646362613439010D6162636435303D646362613530010D6162636435313D646362613531010D6162636435323D646362613532010D6162636435333D646362613533010D6162636435343D646362613534010D6162636435353D646362613535010D6162636435363D646362613536010D6162636435373D646362613537010D6162636435383D646362613538010D6162636435393D646362613539010D6162636436303D646362613630010D6162636436313D646362613631010D6162636436323D646362613632010D6162636436333D646362613633010D6162636436343D646362613634010D6162636436353D646362613635010D6162636436363D646362613636010D6162636436373D646362613637010D6162636436383D646362613638010D6162636436393D646362613639010D6162636437303D646362613730010D6162636437313D646362613731010D6162636437323D646362613732010D6162636437333D646362613733010D6162636437343D646362613734010D6162636437353D646362613735010D6162636437363D646362613736010D6162636437373D646362613737010D6162636437383D646362613738010D6162636437393D646362613739010D6162636438303D646362613830010D6162636438313D646362613831010D6162636438323D646362613832010D6162636438333D646362613833010D6162636438343D646362613834010D6162636438353D646362613835010D6162636438363D646362613836010D6162636438373D646362613837010D6162636438383D646362613838010D6162636438393D646362613839010D6162636439303D646362613930010D6162636439313D646362613931010D6162636439323D646362613932010D6162636439333D646362613933010D6162636439343D646362613934010D6162636439353D646362613935010D6162636439363D646362613936010D6162636439373D646362613937010D6162636439383D646362613938010D6162636439393D646362613939010F616263643130303D64636261313030010F616263643130313D64636261313031010F616263643130323D64636261313032010F616263643130333D64636261313033010F616263643130343D64636261313034010F616263643130353D64636261313035010F616263643130363D64636261313036010F616263643130373D64636261313037010F616263643130383D64636261313038010F616263643130393D64636261313039010F616263643131303D64636261313130010F616263643131313D64636261313131010F616263643131323D64636261313132010F616263643131333D64636261313133010F616263643131343D64636261313134010F616263643131353D64636261313135010F616263643131363D64636261313136010F616263643131373D64636261313137010F616263643131383D64636261313138010F616263643131393D64636261313139010F616263643132303D64636261313230010F616263643132313D64636261313231010F616263643132323D64636261313232010F616263643132333D64636261313233010F616263643132343D64636261313234010F616263643132353D64636261313235010F616263643132363D64636261313236010F616263643132373D64636261313237010F616263643132383D64636261313238010F616263643132393D64636261313239010F616263643133303D64636261313330010F616263643133313D64636261313331010F616263643133323D64636261313332010F616263643133333D64636261313333010F616263643133343D64636261313334010F616263643133353D64636261313335010F616263643133363D64636261313336010F616263643133373D64636261313337010F616263643133383D64636261313338010F616263643133393D64636261313339010F616263643134303D64636261313430010F616263643134313D64636261313431010F616263643134323D64636261313432010F616263643134333D64636261313433010F616263643134343D64636261313434010F616263643134353D64636261313435010F616263643134363D64636261313436010F616263643134373D64636261313437010F616263643134383D64636261313438010F616263643134393D64636261313439010F616263643135303D64636261313530010F616263643135313D64636261313531010F616263643135323D64636261313532010F616263643135333D64636261313533010F616263643135343D64636261313534010F616263643135353D64636261313535010F616263643135363D64636261313536010F616263643135373D64636261313537010F616263643135383D64636261313538010F616263643135393D64636261313539010F616263643136303D64636261313630010F616263643136313D646362613136310100000000","proof":{"aunts":[]}}}],"peer_key":""}]} -{"time":"2016-12-18T05:05:38.598Z","msg":[1,{"height":1,"round":0,"step":"RoundStepPrevote"}]} -{"time":"2016-12-18T05:05:38.598Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":1,"round":0,"type":1,"block_id":{"hash":"07BE34D315EE9E3F0B815E390FDC33747B4936C2","parts":{"total":1,"hash":"A434EC796DF1CECC01296E953839C4675863A4E5"}},"signature":[1,"9EAD2876BAD7D34B5073723929FF4AFE427AED2EB4E911DD24B1665C4FB937A8BE0C4F19A2188B8D5077D07920627218F1705E6365CC27D5B7255AC76AB91D00"]}}],"peer_key":""}]} -{"time":"2016-12-18T05:05:38.599Z","msg":[1,{"height":1,"round":0,"step":"RoundStepPrecommit"}]} -{"time":"2016-12-18T05:05:38.599Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":1,"round":0,"type":2,"block_id":{"hash":"07BE34D315EE9E3F0B815E390FDC33747B4936C2","parts":{"total":1,"hash":"A434EC796DF1CECC01296E953839C4675863A4E5"}},"signature":[1,"60EF6D09CB56944EA27C054A6908BEFD73C5E0A0EB5E0599FFAD3070596B864498D0C6A0D5A25D6E41BCE9548E9681AA5ECE481B955C6214B8D64AFF9737770B"]}}],"peer_key":""}]} -{"time":"2016-12-18T05:05:38.600Z","msg":[1,{"height":1,"round":0,"step":"RoundStepCommit"}]} +{"time":"2017-04-27T22:23:46.268Z","msg":[3,{"duration":972111736,"height":1,"round":0,"step":1}]} +{"time":"2017-04-27T22:23:46.270Z","msg":[1,{"height":1,"round":0,"step":"RoundStepPropose"}]} +{"time":"2017-04-27T22:23:46.270Z","msg":[2,{"msg":[17,{"Proposal":{"height":1,"round":0,"block_parts_header":{"total":1,"hash":"368323AC043A67ACFCF02877D0117F487B6728C2"},"pol_round":-1,"pol_block_id":{"hash":"","parts":{"total":0,"hash":""}},"signature":[1,"3948300A68131AD851E79F09EAF809AAD46C5EC1D2CFC65706F226A78E3C55B093A4AF6C57AFB43C512D818C733C7D273ED7241C4CC16F0E90A30D15730D9209"]}}],"peer_key":""}]} +{"time":"2017-04-27T22:23:46.270Z","msg":[2,{"msg":[19,{"Height":1,"Round":0,"Part":{"index":0,"bytes":"0101010F74656E6465726D696E745F74657374010114B961624C7D4F000167000000000114F075CC9E65D85ECBEA8E4603DC7DB96E881CEEB60114354594CBFC1A7BCA1AD0050ED6AA010023EADA3900010167011A3631363236333634333133303344363436333632363133313330011A3631363236333634333133313344363436333632363133313331011A3631363236333634333133323344363436333632363133313332011A3631363236333634333133333344363436333632363133313333011A3631363236333634333133343344363436333632363133313334011A3631363236333634333133353344363436333632363133313335011A3631363236333634333133363344363436333632363133313336011A3631363236333634333133373344363436333632363133313337011A3631363236333634333133383344363436333632363133313338011A3631363236333634333133393344363436333632363133313339011A3631363236333634333233303344363436333632363133323330011A3631363236333634333233313344363436333632363133323331011A3631363236333634333233323344363436333632363133323332011A3631363236333634333233333344363436333632363133323333011A3631363236333634333233343344363436333632363133323334011A3631363236333634333233353344363436333632363133323335011A3631363236333634333233363344363436333632363133323336011A3631363236333634333233373344363436333632363133323337011A3631363236333634333233383344363436333632363133323338011A3631363236333634333233393344363436333632363133323339011A3631363236333634333333303344363436333632363133333330011A3631363236333634333333313344363436333632363133333331011A3631363236333634333333323344363436333632363133333332011A3631363236333634333333333344363436333632363133333333011A3631363236333634333333343344363436333632363133333334011A3631363236333634333333353344363436333632363133333335011A3631363236333634333333363344363436333632363133333336011A3631363236333634333333373344363436333632363133333337011A3631363236333634333333383344363436333632363133333338011A3631363236333634333333393344363436333632363133333339011A3631363236333634333433303344363436333632363133343330011A3631363236333634333433313344363436333632363133343331011A3631363236333634333433323344363436333632363133343332011A3631363236333634333433333344363436333632363133343333011A3631363236333634333433343344363436333632363133343334011A3631363236333634333433353344363436333632363133343335011A3631363236333634333433363344363436333632363133343336011A3631363236333634333433373344363436333632363133343337011A3631363236333634333433383344363436333632363133343338011A3631363236333634333433393344363436333632363133343339011A3631363236333634333533303344363436333632363133353330011A3631363236333634333533313344363436333632363133353331011A3631363236333634333533323344363436333632363133353332011A3631363236333634333533333344363436333632363133353333011A3631363236333634333533343344363436333632363133353334011A3631363236333634333533353344363436333632363133353335011A3631363236333634333533363344363436333632363133353336011A3631363236333634333533373344363436333632363133353337011A3631363236333634333533383344363436333632363133353338011A3631363236333634333533393344363436333632363133353339011A3631363236333634333633303344363436333632363133363330011A3631363236333634333633313344363436333632363133363331011A3631363236333634333633323344363436333632363133363332011A3631363236333634333633333344363436333632363133363333011A3631363236333634333633343344363436333632363133363334011A3631363236333634333633353344363436333632363133363335011A3631363236333634333633363344363436333632363133363336011A3631363236333634333633373344363436333632363133363337011A3631363236333634333633383344363436333632363133363338011A3631363236333634333633393344363436333632363133363339011A3631363236333634333733303344363436333632363133373330011A3631363236333634333733313344363436333632363133373331011A3631363236333634333733323344363436333632363133373332011A3631363236333634333733333344363436333632363133373333011A3631363236333634333733343344363436333632363133373334011A3631363236333634333733353344363436333632363133373335011A3631363236333634333733363344363436333632363133373336011A3631363236333634333733373344363436333632363133373337011A3631363236333634333733383344363436333632363133373338011A3631363236333634333733393344363436333632363133373339011A3631363236333634333833303344363436333632363133383330011A3631363236333634333833313344363436333632363133383331011A3631363236333634333833323344363436333632363133383332011A3631363236333634333833333344363436333632363133383333011A3631363236333634333833343344363436333632363133383334011A3631363236333634333833353344363436333632363133383335011A3631363236333634333833363344363436333632363133383336011A3631363236333634333833373344363436333632363133383337011A3631363236333634333833383344363436333632363133383338011A3631363236333634333833393344363436333632363133383339011A3631363236333634333933303344363436333632363133393330011A3631363236333634333933313344363436333632363133393331011A3631363236333634333933323344363436333632363133393332011A3631363236333634333933333344363436333632363133393333011A3631363236333634333933343344363436333632363133393334011A3631363236333634333933353344363436333632363133393335011A3631363236333634333933363344363436333632363133393336011A3631363236333634333933373344363436333632363133393337011A3631363236333634333933383344363436333632363133393338011A3631363236333634333933393344363436333632363133393339011E363136323633363433313330333033443634363336323631333133303330011E363136323633363433313330333133443634363336323631333133303331011E363136323633363433313330333233443634363336323631333133303332011E363136323633363433313330333333443634363336323631333133303333011E363136323633363433313330333433443634363336323631333133303334011E363136323633363433313330333533443634363336323631333133303335011E363136323633363433313330333633443634363336323631333133303336011E363136323633363433313330333733443634363336323631333133303337011E363136323633363433313330333833443634363336323631333133303338011E363136323633363433313330333933443634363336323631333133303339011E363136323633363433313331333033443634363336323631333133313330011E363136323633363433313331333133443634363336323631333133313331011E3631363236333634333133313332334436343633363236313331333133320100000000","proof":{"aunts":[]}}}],"peer_key":""}]} +{"time":"2017-04-27T22:23:46.271Z","msg":[1,{"height":1,"round":0,"step":"RoundStepPrevote"}]} +{"time":"2017-04-27T22:23:46.271Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":1,"round":0,"type":1,"block_id":{"hash":"FC7032C1A475C288FE30ED57BD4131AFE03DDC16","parts":{"total":1,"hash":"368323AC043A67ACFCF02877D0117F487B6728C2"}},"signature":[1,"78DD4C7854DED0D76C3B9783DD535B967E795E93ACD1947B362B418C99DB3AB271BF20546628ECDF523C839C6C5D1BF3605DA552CBCFB9C8BB7A74594BAB8F01"]}}],"peer_key":""}]} +{"time":"2017-04-27T22:23:46.273Z","msg":[1,{"height":1,"round":0,"step":"RoundStepPrecommit"}]} +{"time":"2017-04-27T22:23:46.273Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":1,"round":0,"type":2,"block_id":{"hash":"FC7032C1A475C288FE30ED57BD4131AFE03DDC16","parts":{"total":1,"hash":"368323AC043A67ACFCF02877D0117F487B6728C2"}},"signature":[1,"A1C01F36B87CA1CBCE87560FBE297B6820A421F86F80C88DAD6CAD6204A11C573CDCC60796F958F52E5AF04F54DB5321AC6F38BD19E8CF069771C9F899D0220B"]}}],"peer_key":""}]} +{"time":"2017-04-27T22:23:46.273Z","msg":[1,{"height":1,"round":0,"step":"RoundStepCommit"}]} diff --git a/consensus/test_data/small_block2.cswal b/consensus/test_data/small_block2.cswal index b5d1d282b..e3cfaad32 100644 --- a/consensus/test_data/small_block2.cswal +++ b/consensus/test_data/small_block2.cswal @@ -1,14 +1,15 @@ #ENDHEIGHT: 0 -{"time":"2016-12-18T05:05:43.641Z","msg":[3,{"duration":969409681,"height":1,"round":0,"step":1}]} -{"time":"2016-12-18T05:05:43.643Z","msg":[1,{"height":1,"round":0,"step":"RoundStepPropose"}]} -{"time":"2016-12-18T05:05:43.643Z","msg":[2,{"msg":[17,{"Proposal":{"height":1,"round":0,"block_parts_header":{"total":5,"hash":"C916905C3C444501DDDAA1BF52E959B7531E762E"},"pol_round":-1,"pol_block_id":{"hash":"","parts":{"total":0,"hash":""}},"signature":[1,"F1A8E9928889C68FD393F3983B5362AECA4A95AA13FE3C78569B2515EC046893CB718071CAF54F3F1507DCD851B37CD5557EA17BB5471D2DC6FB5AC5FBB72E02"]}}],"peer_key":""}]} -{"time":"2016-12-18T05:05:43.643Z","msg":[2,{"msg":[19,{"Height":1,"Round":0,"Part":{"index":0,"bytes":"0101010F74656E6465726D696E745F7465737401011491414B3483A8400190000000000114926EA77D30A4D19866159DE7E58AA9461F90F9D10114354594CBFC1A7BCA1AD0050ED6AA010023EADA3900010190010D6162636431323D646362613132010D6162636431333D646362613133010D6162636431343D646362613134010D6162636431353D646362613135010D6162636431363D646362613136010D6162636431373D646362613137010D6162636431383D646362613138010D6162636431393D646362613139010D6162636432303D646362613230010D6162636432313D646362613231010D6162636432323D646362613232010D6162636432333D646362613233010D6162636432343D646362613234010D6162636432353D646362613235010D6162636432363D646362613236010D6162636432373D646362613237010D6162636432383D646362613238010D6162636432393D646362613239010D6162636433303D646362613330010D6162636433313D646362613331010D6162636433323D646362613332010D6162636433333D646362613333010D6162636433343D646362613334010D6162636433353D646362613335010D6162636433363D646362613336010D6162636433373D646362613337010D6162636433383D646362613338010D6162636433393D646362613339010D6162636434303D","proof":{"aunts":["C9FBD66B63A976638196323F5B93494BDDFC9EED","47FD83BB7607E679EE5CF0783372D13C5A264056","FEEC97078A26B7F6057821C0660855170CC6F1D7"]}}}],"peer_key":""}]} -{"time":"2016-12-18T05:05:43.643Z","msg":[2,{"msg":[19,{"Height":1,"Round":0,"Part":{"index":1,"bytes":"646362613430010D6162636434313D646362613431010D6162636434323D646362613432010D6162636434333D646362613433010D6162636434343D646362613434010D6162636434353D646362613435010D6162636434363D646362613436010D6162636434373D646362613437010D6162636434383D646362613438010D6162636434393D646362613439010D6162636435303D646362613530010D6162636435313D646362613531010D6162636435323D646362613532010D6162636435333D646362613533010D6162636435343D646362613534010D6162636435353D646362613535010D6162636435363D646362613536010D6162636435373D646362613537010D6162636435383D646362613538010D6162636435393D646362613539010D6162636436303D646362613630010D6162636436313D646362613631010D6162636436323D646362613632010D6162636436333D646362613633010D6162636436343D646362613634010D6162636436353D646362613635010D6162636436363D646362613636010D6162636436373D646362613637010D6162636436383D646362613638010D6162636436393D646362613639010D6162636437303D646362613730010D6162636437313D646362613731010D6162636437323D646362613732010D6162636437333D646362613733010D6162636437343D6463","proof":{"aunts":["D7FB03B935B77C322064F8277823CDB5C7018597","47FD83BB7607E679EE5CF0783372D13C5A264056","FEEC97078A26B7F6057821C0660855170CC6F1D7"]}}}],"peer_key":""}]} -{"time":"2016-12-18T05:05:43.644Z","msg":[2,{"msg":[19,{"Height":1,"Round":0,"Part":{"index":2,"bytes":"62613734010D6162636437353D646362613735010D6162636437363D646362613736010D6162636437373D646362613737010D6162636437383D646362613738010D6162636437393D646362613739010D6162636438303D646362613830010D6162636438313D646362613831010D6162636438323D646362613832010D6162636438333D646362613833010D6162636438343D646362613834010D6162636438353D646362613835010D6162636438363D646362613836010D6162636438373D646362613837010D6162636438383D646362613838010D6162636438393D646362613839010D6162636439303D646362613930010D6162636439313D646362613931010D6162636439323D646362613932010D6162636439333D646362613933010D6162636439343D646362613934010D6162636439353D646362613935010D6162636439363D646362613936010D6162636439373D646362613937010D6162636439383D646362613938010D6162636439393D646362613939010F616263643130303D64636261313030010F616263643130313D64636261313031010F616263643130323D64636261313032010F616263643130333D64636261313033010F616263643130343D64636261313034010F616263643130353D64636261313035010F616263643130363D64636261313036010F616263643130373D64636261","proof":{"aunts":["A607D9BF5107E6C9FD19B6928D9CC7714B0730E4","FEEC97078A26B7F6057821C0660855170CC6F1D7"]}}}],"peer_key":""}]} -{"time":"2016-12-18T05:05:43.644Z","msg":[2,{"msg":[19,{"Height":1,"Round":0,"Part":{"index":3,"bytes":"313037010F616263643130383D64636261313038010F616263643130393D64636261313039010F616263643131303D64636261313130010F616263643131313D64636261313131010F616263643131323D64636261313132010F616263643131333D64636261313133010F616263643131343D64636261313134010F616263643131353D64636261313135010F616263643131363D64636261313136010F616263643131373D64636261313137010F616263643131383D64636261313138010F616263643131393D64636261313139010F616263643132303D64636261313230010F616263643132313D64636261313231010F616263643132323D64636261313232010F616263643132333D64636261313233010F616263643132343D64636261313234010F616263643132353D64636261313235010F616263643132363D64636261313236010F616263643132373D64636261313237010F616263643132383D64636261313238010F616263643132393D64636261313239010F616263643133303D64636261313330010F616263643133313D64636261313331010F616263643133323D64636261313332010F616263643133333D64636261313333010F616263643133343D64636261313334010F616263643133353D64636261313335010F616263643133363D64636261313336010F616263643133373D646362613133","proof":{"aunts":["0FD794B3506B9E92CDE3703F7189D42167E77095","86D455F542DA79F5A764B9DABDEABF01F4BAB2AB"]}}}],"peer_key":""}]} -{"time":"2016-12-18T05:05:43.644Z","msg":[2,{"msg":[19,{"Height":1,"Round":0,"Part":{"index":4,"bytes":"37010F616263643133383D64636261313338010F616263643133393D64636261313339010F616263643134303D64636261313430010F616263643134313D64636261313431010F616263643134323D64636261313432010F616263643134333D64636261313433010F616263643134343D64636261313434010F616263643134353D64636261313435010F616263643134363D64636261313436010F616263643134373D64636261313437010F616263643134383D64636261313438010F616263643134393D64636261313439010F616263643135303D64636261313530010F616263643135313D64636261313531010F616263643135323D64636261313532010F616263643135333D64636261313533010F616263643135343D64636261313534010F616263643135353D646362613135350100000000","proof":{"aunts":["50CBDC078A660EAE3442BA355BE10EE0D04408D1","86D455F542DA79F5A764B9DABDEABF01F4BAB2AB"]}}}],"peer_key":""}]} -{"time":"2016-12-18T05:05:43.645Z","msg":[1,{"height":1,"round":0,"step":"RoundStepPrevote"}]} -{"time":"2016-12-18T05:05:43.645Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":1,"round":0,"type":1,"block_id":{"hash":"6ADACDC2871C59A67337DAFD5045A982ED070C51","parts":{"total":5,"hash":"C916905C3C444501DDDAA1BF52E959B7531E762E"}},"signature":[1,"E815E0A63B7EEE7894DE2D72372A7C393434AC8ACCC46B60C628910F73351806D55A59994F08B454BFD71EDAA0CA95733CA47E37FFDAF9AAA2431A8160176E01"]}}],"peer_key":""}]} -{"time":"2016-12-18T05:05:43.647Z","msg":[1,{"height":1,"round":0,"step":"RoundStepPrecommit"}]} -{"time":"2016-12-18T05:05:43.647Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":1,"round":0,"type":2,"block_id":{"hash":"6ADACDC2871C59A67337DAFD5045A982ED070C51","parts":{"total":5,"hash":"C916905C3C444501DDDAA1BF52E959B7531E762E"}},"signature":[1,"9AAC3F3A118EE039EB460E9E5308D490D671C7490309BD5D62B5F392205C7E420DFDAF90F08294FF36BE8A9AA5CC203C1F2088B42D2BB8EE40A45F2BB5C54D0A"]}}],"peer_key":""}]} -{"time":"2016-12-18T05:05:43.648Z","msg":[1,{"height":1,"round":0,"step":"RoundStepCommit"}]} +{"time":"2017-04-27T22:23:56.310Z","msg":[3,{"duration":969732098,"height":1,"round":0,"step":1}]} +{"time":"2017-04-27T22:23:56.312Z","msg":[1,{"height":1,"round":0,"step":"RoundStepPropose"}]} +{"time":"2017-04-27T22:23:56.312Z","msg":[2,{"msg":[17,{"Proposal":{"height":1,"round":0,"block_parts_header":{"total":6,"hash":"A3C176F13F5CBC7C48EE27A472800410C9D487DC"},"pol_round":-1,"pol_block_id":{"hash":"","parts":{"total":0,"hash":""}},"signature":[1,"7624F6E943B7A207E16D1FA87EA099BD924E930F98E7DECBC01DB37735C619409588A67C2EABA9845FD6B80FDB65ECFCDA5F0DEFCEF74B8C34DB8E0540480203"]}}],"peer_key":""}]} +{"time":"2017-04-27T22:23:56.312Z","msg":[2,{"msg":[19,{"Height":1,"Round":0,"Part":{"index":0,"bytes":"0101010F74656E6465726D696E745F74657374010114B96164A30A118001620000000001141F6753D22BACA2180B1EADD722434EB28444D91D0114354594CBFC1A7BCA1AD0050ED6AA010023EADA3900010162011A3631363236333634333133303344363436333632363133313330011A3631363236333634333133313344363436333632363133313331011A3631363236333634333133323344363436333632363133313332011A3631363236333634333133333344363436333632363133313333011A3631363236333634333133343344363436333632363133313334011A3631363236333634333133353344363436333632363133313335011A3631363236333634333133363344363436333632363133313336011A3631363236333634333133373344363436333632363133313337011A3631363236333634333133383344363436333632363133313338011A3631363236333634333133393344363436333632363133313339011A3631363236333634333233303344363436333632363133323330011A3631363236333634333233313344363436333632363133323331011A3631363236333634333233323344363436333632363133323332011A3631363236333634333233333344363436333632363133323333011A3631363236333634333233343344363436333632363133323334011A36313632363336","proof":{"aunts":["49F4B71E3D7C457415069E2EA916DB12F67AA8D0","D35A72BEDAAAAC17045D7BFAAFA94C2EC0B0A4C2","705BC647374F3495EE73C3F44C21E9BDB4731738"]}}}],"peer_key":""}]} +{"time":"2017-04-27T22:23:56.312Z","msg":[2,{"msg":[19,{"Height":1,"Round":0,"Part":{"index":1,"bytes":"34333233353344363436333632363133323335011A3631363236333634333233363344363436333632363133323336011A3631363236333634333233373344363436333632363133323337011A3631363236333634333233383344363436333632363133323338011A3631363236333634333233393344363436333632363133323339011A3631363236333634333333303344363436333632363133333330011A3631363236333634333333313344363436333632363133333331011A3631363236333634333333323344363436333632363133333332011A3631363236333634333333333344363436333632363133333333011A3631363236333634333333343344363436333632363133333334011A3631363236333634333333353344363436333632363133333335011A3631363236333634333333363344363436333632363133333336011A3631363236333634333333373344363436333632363133333337011A3631363236333634333333383344363436333632363133333338011A3631363236333634333333393344363436333632363133333339011A3631363236333634333433303344363436333632363133343330011A3631363236333634333433313344363436333632363133343331011A3631363236333634333433323344363436333632363133343332011A363136323633363433343333334436","proof":{"aunts":["5AD2A9A1A49A1FD6EF83F05FA4588F800B29DEF1","D35A72BEDAAAAC17045D7BFAAFA94C2EC0B0A4C2","705BC647374F3495EE73C3F44C21E9BDB4731738"]}}}],"peer_key":""}]} +{"time":"2017-04-27T22:23:56.312Z","msg":[2,{"msg":[19,{"Height":1,"Round":0,"Part":{"index":2,"bytes":"3436333632363133343333011A3631363236333634333433343344363436333632363133343334011A3631363236333634333433353344363436333632363133343335011A3631363236333634333433363344363436333632363133343336011A3631363236333634333433373344363436333632363133343337011A3631363236333634333433383344363436333632363133343338011A3631363236333634333433393344363436333632363133343339011A3631363236333634333533303344363436333632363133353330011A3631363236333634333533313344363436333632363133353331011A3631363236333634333533323344363436333632363133353332011A3631363236333634333533333344363436333632363133353333011A3631363236333634333533343344363436333632363133353334011A3631363236333634333533353344363436333632363133353335011A3631363236333634333533363344363436333632363133353336011A3631363236333634333533373344363436333632363133353337011A3631363236333634333533383344363436333632363133353338011A3631363236333634333533393344363436333632363133353339011A3631363236333634333633303344363436333632363133363330011A3631363236333634333633313344363436333632363133","proof":{"aunts":["8B5786C3D871EE37B0F4B2DECAC39E157340DFBE","705BC647374F3495EE73C3F44C21E9BDB4731738"]}}}],"peer_key":""}]} +{"time":"2017-04-27T22:23:56.312Z","msg":[2,{"msg":[19,{"Height":1,"Round":0,"Part":{"index":3,"bytes":"363331011A3631363236333634333633323344363436333632363133363332011A3631363236333634333633333344363436333632363133363333011A3631363236333634333633343344363436333632363133363334011A3631363236333634333633353344363436333632363133363335011A3631363236333634333633363344363436333632363133363336011A3631363236333634333633373344363436333632363133363337011A3631363236333634333633383344363436333632363133363338011A3631363236333634333633393344363436333632363133363339011A3631363236333634333733303344363436333632363133373330011A3631363236333634333733313344363436333632363133373331011A3631363236333634333733323344363436333632363133373332011A3631363236333634333733333344363436333632363133373333011A3631363236333634333733343344363436333632363133373334011A3631363236333634333733353344363436333632363133373335011A3631363236333634333733363344363436333632363133373336011A3631363236333634333733373344363436333632363133373337011A3631363236333634333733383344363436333632363133373338011A3631363236333634333733393344363436333632363133373339011A363136","proof":{"aunts":["56097661A1B2707588100586B3B1C2C8A51057D1","6DE889147DF528EEB5F7422E95DC45900CAFB619","247C721D5CEB90BB1FE389BA74C43DF0955E1647"]}}}],"peer_key":""}]} +{"time":"2017-04-27T22:23:56.312Z","msg":[2,{"msg":[19,{"Height":1,"Round":0,"Part":{"index":4,"bytes":"3236333634333833303344363436333632363133383330011A3631363236333634333833313344363436333632363133383331011A3631363236333634333833323344363436333632363133383332011A3631363236333634333833333344363436333632363133383333011A3631363236333634333833343344363436333632363133383334011A3631363236333634333833353344363436333632363133383335011A3631363236333634333833363344363436333632363133383336011A3631363236333634333833373344363436333632363133383337011A3631363236333634333833383344363436333632363133383338011A3631363236333634333833393344363436333632363133383339011A3631363236333634333933303344363436333632363133393330011A3631363236333634333933313344363436333632363133393331011A3631363236333634333933323344363436333632363133393332011A3631363236333634333933333344363436333632363133393333011A3631363236333634333933343344363436333632363133393334011A3631363236333634333933353344363436333632363133393335011A3631363236333634333933363344363436333632363133393336011A3631363236333634333933373344363436333632363133393337011A3631363236333634333933","proof":{"aunts":["081D3DC5F11850851D5F0D760B98EE87BFA6B8B0","6DE889147DF528EEB5F7422E95DC45900CAFB619","247C721D5CEB90BB1FE389BA74C43DF0955E1647"]}}}],"peer_key":""}]} +{"time":"2017-04-27T22:23:56.313Z","msg":[2,{"msg":[19,{"Height":1,"Round":0,"Part":{"index":5,"bytes":"383344363436333632363133393338011A3631363236333634333933393344363436333632363133393339011E363136323633363433313330333033443634363336323631333133303330011E363136323633363433313330333133443634363336323631333133303331011E363136323633363433313330333233443634363336323631333133303332011E363136323633363433313330333333443634363336323631333133303333011E363136323633363433313330333433443634363336323631333133303334011E363136323633363433313330333533443634363336323631333133303335011E363136323633363433313330333633443634363336323631333133303336011E3631363236333634333133303337334436343633363236313331333033370100000000","proof":{"aunts":["6AA912328C2B52EFA0ECE71F523E137E400EC484","247C721D5CEB90BB1FE389BA74C43DF0955E1647"]}}}],"peer_key":""}]} +{"time":"2017-04-27T22:23:56.314Z","msg":[1,{"height":1,"round":0,"step":"RoundStepPrevote"}]} +{"time":"2017-04-27T22:23:56.314Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":1,"round":0,"type":1,"block_id":{"hash":"62371CF72F8662378691706DB256C833CF1AF81B","parts":{"total":6,"hash":"A3C176F13F5CBC7C48EE27A472800410C9D487DC"}},"signature":[1,"255906FAAA50C84E85DABF7DE73468E4F95DB4E46F598848145926E2FAD77CA682BF07E09E2F3EC81FFBD9A036B67914A3C02F819B69248D777AEBA792725907"]}}],"peer_key":""}]} +{"time":"2017-04-27T22:23:56.315Z","msg":[1,{"height":1,"round":0,"step":"RoundStepPrecommit"}]} +{"time":"2017-04-27T22:23:56.315Z","msg":[2,{"msg":[20,{"Vote":{"validator_address":"D028C9981F7A87F3093672BF0D5B0E2A1B3ED456","validator_index":0,"height":1,"round":0,"type":2,"block_id":{"hash":"62371CF72F8662378691706DB256C833CF1AF81B","parts":{"total":6,"hash":"A3C176F13F5CBC7C48EE27A472800410C9D487DC"}},"signature":[1,"056CC15C748434D0A59B64B45CB56EDC1A437A426E68FA63DC7D61A7C17B0F768F207D81340D129A57C5A64195F8AFDD03B6BF28D7B2286290D61BCE88FCA304"]}}],"peer_key":""}]} +{"time":"2017-04-27T22:23:56.316Z","msg":[1,{"height":1,"round":0,"step":"RoundStepCommit"}]} From 0be3480729705bde52ebc25e2d7d3e26557023b8 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Thu, 27 Apr 2017 18:34:54 -0400 Subject: [PATCH 217/309] consensus: comment about test_data [ci skip] --- consensus/replay_test.go | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/consensus/replay_test.go b/consensus/replay_test.go index e6335f699..626de6bbf 100644 --- a/consensus/replay_test.go +++ b/consensus/replay_test.go @@ -37,6 +37,12 @@ func init() { // the `Handshake Tests` are for failures in applying the block. // With the help of the WAL, we can recover from it all! +// NOTE: Files in this dir are generated by running the `build.sh` therein. +// It's a simple way to generate wals for a single block, or multiple blocks, with random transactions, +// and different part sizes. The output is not deterministic, and the stepChanges may need to be adjusted +// after running it (eg. sometimes small_block2 will have 5 block parts, sometimes 6). +// It should only have to be re-run if there is some breaking change to the consensus data structures (eg. blocks, votes) +// or to the behaviour of the app (eg. computes app hash differently) var data_dir = path.Join(cmn.GoPath, "src/github.com/tendermint/tendermint/consensus", "test_data") //------------------------------------------------------------------------------------------ From bdb34f9f4e81d99d9308cb930b9cbad195e7ce7d Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Thu, 27 Apr 2017 19:01:18 -0400 Subject: [PATCH 218/309] types: []byte -> data.Bytes --- types/block.go | 23 ++++++++++++----------- types/canonical_json.go | 10 +++++++--- types/events.go | 9 +++++---- types/genesis.go | 7 ++++--- types/part_set.go | 27 ++++++++++++++------------- types/tx.go | 3 ++- types/tx_test.go | 6 +++--- types/validator.go | 13 +++++++------ types/vote.go | 11 ++++++----- 9 files changed, 60 insertions(+), 49 deletions(-) diff --git a/types/block.go b/types/block.go index 88288a2bd..65d4031da 100644 --- a/types/block.go +++ b/types/block.go @@ -8,9 +8,10 @@ import ( "strings" "time" + "github.com/tendermint/go-wire" + "github.com/tendermint/go-wire/data" . "github.com/tendermint/tmlibs/common" "github.com/tendermint/tmlibs/merkle" - "github.com/tendermint/go-wire" ) const MaxBlockSize = 22020096 // 21MB TODO make it configurable @@ -150,15 +151,15 @@ func (b *Block) StringShort() string { //----------------------------------------------------------------------------- type Header struct { - ChainID string `json:"chain_id"` - Height int `json:"height"` - Time time.Time `json:"time"` - NumTxs int `json:"num_txs"` // XXX: Can we get rid of this? - LastBlockID BlockID `json:"last_block_id"` - LastCommitHash []byte `json:"last_commit_hash"` // commit from validators from the last block - DataHash []byte `json:"data_hash"` // transactions - ValidatorsHash []byte `json:"validators_hash"` // validators for the current block - AppHash []byte `json:"app_hash"` // state after txs from the previous block + ChainID string `json:"chain_id"` + Height int `json:"height"` + Time time.Time `json:"time"` + NumTxs int `json:"num_txs"` // XXX: Can we get rid of this? + LastBlockID BlockID `json:"last_block_id"` + LastCommitHash data.Bytes `json:"last_commit_hash"` // commit from validators from the last block + DataHash data.Bytes `json:"data_hash"` // transactions + ValidatorsHash data.Bytes `json:"validators_hash"` // validators for the current block + AppHash data.Bytes `json:"app_hash"` // state after txs from the previous block } // NOTE: hash is nil if required fields are missing. @@ -388,7 +389,7 @@ func (data *Data) StringIndented(indent string) string { //-------------------------------------------------------------------------------- type BlockID struct { - Hash []byte `json:"hash"` + Hash data.Bytes `json:"hash"` PartsHeader PartSetHeader `json:"parts"` } diff --git a/types/canonical_json.go b/types/canonical_json.go index 68dd6924c..2e8583a4a 100644 --- a/types/canonical_json.go +++ b/types/canonical_json.go @@ -1,15 +1,19 @@ package types +import ( + "github.com/tendermint/go-wire/data" +) + // canonical json is go-wire's json for structs with fields in alphabetical order type CanonicalJSONBlockID struct { - Hash []byte `json:"hash,omitempty"` + Hash data.Bytes `json:"hash,omitempty"` PartsHeader CanonicalJSONPartSetHeader `json:"parts,omitempty"` } type CanonicalJSONPartSetHeader struct { - Hash []byte `json:"hash"` - Total int `json:"total"` + Hash data.Bytes `json:"hash"` + Total int `json:"total"` } type CanonicalJSONProposal struct { diff --git a/types/events.go b/types/events.go index 17f6fc6e4..953859d0d 100644 --- a/types/events.go +++ b/types/events.go @@ -3,9 +3,10 @@ package types import ( // for registering TMEventData as events.EventData abci "github.com/tendermint/abci/types" - . "github.com/tendermint/tmlibs/common" - "github.com/tendermint/tmlibs/events" "github.com/tendermint/go-wire" + "github.com/tendermint/go-wire/data" + cmn "github.com/tendermint/tmlibs/common" + "github.com/tendermint/tmlibs/events" ) // Functions to generate eventId strings @@ -16,7 +17,7 @@ func EventStringUnbond() string { return "Unbond" } func EventStringRebond() string { return "Rebond" } func EventStringDupeout() string { return "Dupeout" } func EventStringFork() string { return "Fork" } -func EventStringTx(tx Tx) string { return Fmt("Tx:%X", tx.Hash()) } +func EventStringTx(tx Tx) string { return cmn.Fmt("Tx:%X", tx.Hash()) } func EventStringNewBlock() string { return "NewBlock" } func EventStringNewBlockHeader() string { return "NewBlockHeader" } @@ -75,7 +76,7 @@ type EventDataNewBlockHeader struct { type EventDataTx struct { Height int `json:"height"` Tx Tx `json:"tx"` - Data []byte `json:"data"` + Data data.Bytes `json:"data"` Log string `json:"log"` Code abci.CodeType `json:"code"` Error string `json:"error"` // this is redundant information for now diff --git a/types/genesis.go b/types/genesis.go index 6a5006648..75999f631 100644 --- a/types/genesis.go +++ b/types/genesis.go @@ -4,8 +4,9 @@ import ( "encoding/json" "time" - . "github.com/tendermint/tmlibs/common" "github.com/tendermint/go-crypto" + "github.com/tendermint/go-wire/data" + cmn "github.com/tendermint/tmlibs/common" ) //------------------------------------------------------------ @@ -26,7 +27,7 @@ type GenesisDoc struct { GenesisTime time.Time `json:"genesis_time"` ChainID string `json:"chain_id"` Validators []GenesisValidator `json:"validators"` - AppHash []byte `json:"app_hash"` + AppHash data.Bytes `json:"app_hash"` } // Utility method for saving GenensisDoc as JSON file. @@ -35,7 +36,7 @@ func (genDoc *GenesisDoc) SaveAs(file string) error { if err != nil { return err } - return WriteFile(file, genDocBytes, 0644) + return cmn.WriteFile(file, genDocBytes, 0644) } //------------------------------------------------------------ diff --git a/types/part_set.go b/types/part_set.go index 96907aa5f..e15d2cab6 100644 --- a/types/part_set.go +++ b/types/part_set.go @@ -9,9 +9,10 @@ import ( "golang.org/x/crypto/ripemd160" - . "github.com/tendermint/tmlibs/common" - "github.com/tendermint/tmlibs/merkle" "github.com/tendermint/go-wire" + "github.com/tendermint/go-wire/data" + cmn "github.com/tendermint/tmlibs/common" + "github.com/tendermint/tmlibs/merkle" ) var ( @@ -21,7 +22,7 @@ var ( type Part struct { Index int `json:"index"` - Bytes []byte `json:"bytes"` + Bytes data.Bytes `json:"bytes"` Proof merkle.SimpleProof `json:"proof"` // Cache @@ -49,7 +50,7 @@ func (part *Part) StringIndented(indent string) string { %s Proof: %v %s}`, part.Index, - indent, Fingerprint(part.Bytes), + indent, cmn.Fingerprint(part.Bytes), indent, part.Proof.StringIndented(indent+" "), indent) } @@ -57,12 +58,12 @@ func (part *Part) StringIndented(indent string) string { //------------------------------------- type PartSetHeader struct { - Total int `json:"total"` - Hash []byte `json:"hash"` + Total int `json:"total"` + Hash data.Bytes `json:"hash"` } func (psh PartSetHeader) String() string { - return fmt.Sprintf("%v:%X", psh.Total, Fingerprint(psh.Hash)) + return fmt.Sprintf("%v:%X", psh.Total, cmn.Fingerprint(psh.Hash)) } func (psh PartSetHeader) IsZero() bool { @@ -85,7 +86,7 @@ type PartSet struct { mtx sync.Mutex parts []*Part - partsBitArray *BitArray + partsBitArray *cmn.BitArray count int } @@ -96,11 +97,11 @@ func NewPartSetFromData(data []byte, partSize int) *PartSet { total := (len(data) + partSize - 1) / partSize parts := make([]*Part, total) parts_ := make([]merkle.Hashable, total) - partsBitArray := NewBitArray(total) + partsBitArray := cmn.NewBitArray(total) for i := 0; i < total; i++ { part := &Part{ Index: i, - Bytes: data[i*partSize : MinInt(len(data), (i+1)*partSize)], + Bytes: data[i*partSize : cmn.MinInt(len(data), (i+1)*partSize)], } parts[i] = part parts_[i] = part @@ -126,7 +127,7 @@ func NewPartSetFromHeader(header PartSetHeader) *PartSet { total: header.Total, hash: header.Hash, parts: make([]*Part, header.Total), - partsBitArray: NewBitArray(header.Total), + partsBitArray: cmn.NewBitArray(header.Total), count: 0, } } @@ -150,7 +151,7 @@ func (ps *PartSet) HasHeader(header PartSetHeader) bool { } } -func (ps *PartSet) BitArray() *BitArray { +func (ps *PartSet) BitArray() *cmn.BitArray { ps.mtx.Lock() defer ps.mtx.Unlock() return ps.partsBitArray.Copy() @@ -224,7 +225,7 @@ func (ps *PartSet) IsComplete() bool { func (ps *PartSet) GetReader() io.Reader { if !ps.IsComplete() { - PanicSanity("Cannot GetReader() on incomplete PartSet") + cmn.PanicSanity("Cannot GetReader() on incomplete PartSet") } return NewPartSetReader(ps.parts) } diff --git a/types/tx.go b/types/tx.go index e62b5f666..ac3ec01d6 100644 --- a/types/tx.go +++ b/types/tx.go @@ -5,6 +5,7 @@ import ( "errors" abci "github.com/tendermint/abci/types" + "github.com/tendermint/go-wire/data" "github.com/tendermint/tmlibs/merkle" ) @@ -79,7 +80,7 @@ func (txs Txs) Proof(i int) TxProof { type TxProof struct { Index, Total int - RootHash []byte + RootHash data.Bytes Data Tx Proof merkle.SimpleProof } diff --git a/types/tx_test.go b/types/tx_test.go index 3ed59e3cb..91cddecfe 100644 --- a/types/tx_test.go +++ b/types/tx_test.go @@ -60,9 +60,9 @@ func TestValidTxProof(t *testing.T) { proof := txs.Proof(i) assert.Equal(i, proof.Index, "%d: %d", h, i) assert.Equal(len(txs), proof.Total, "%d: %d", h, i) - assert.Equal(root, proof.RootHash, "%d: %d", h, i) - assert.Equal(leaf, proof.Data, "%d: %d", h, i) - assert.Equal(leafHash, proof.LeafHash(), "%d: %d", h, i) + assert.EqualValues(root, proof.RootHash, "%d: %d", h, i) + assert.EqualValues(leaf, proof.Data, "%d: %d", h, i) + assert.EqualValues(leafHash, proof.LeafHash(), "%d: %d", h, i) assert.Nil(proof.Validate(root), "%d: %d", h, i) assert.NotNil(proof.Validate([]byte("foobar")), "%d: %d", h, i) diff --git a/types/validator.go b/types/validator.go index 2a8795bf3..595c52ff1 100644 --- a/types/validator.go +++ b/types/validator.go @@ -5,16 +5,17 @@ import ( "fmt" "io" - . "github.com/tendermint/tmlibs/common" "github.com/tendermint/go-crypto" "github.com/tendermint/go-wire" + "github.com/tendermint/go-wire/data" + cmn "github.com/tendermint/tmlibs/common" ) // Volatile state for each Validator // TODO: make non-volatile identity // - Remove Accum - it can be computed, and now valset becomes identifying type Validator struct { - Address []byte `json:"address"` + Address data.Bytes `json:"address"` PubKey crypto.PubKey `json:"pub_key"` VotingPower int64 `json:"voting_power"` Accum int64 `json:"accum"` @@ -51,7 +52,7 @@ func (v *Validator) CompareAccum(other *Validator) *Validator { } else if bytes.Compare(v.Address, other.Address) > 0 { return other } else { - PanicSanity("Cannot compare identical validators") + cmn.PanicSanity("Cannot compare identical validators") return nil } } @@ -87,7 +88,7 @@ func (vc validatorCodec) Decode(r io.Reader, n *int, err *error) interface{} { } func (vc validatorCodec) Compare(o1 interface{}, o2 interface{}) int { - PanicSanity("ValidatorCodec.Compare not implemented") + cmn.PanicSanity("ValidatorCodec.Compare not implemented") return 0 } @@ -96,11 +97,11 @@ func (vc validatorCodec) Compare(o1 interface{}, o2 interface{}) int { func RandValidator(randPower bool, minPower int64) (*Validator, *PrivValidator) { privVal := GenPrivValidator() - _, tempFilePath := Tempfile("priv_validator_") + _, tempFilePath := cmn.Tempfile("priv_validator_") privVal.SetFile(tempFilePath) votePower := minPower if randPower { - votePower += int64(RandUint32()) + votePower += int64(cmn.RandUint32()) } val := NewValidator(privVal.PubKey, votePower) return val, privVal diff --git a/types/vote.go b/types/vote.go index 2ad9df0ad..164293c53 100644 --- a/types/vote.go +++ b/types/vote.go @@ -5,9 +5,10 @@ import ( "fmt" "io" - . "github.com/tendermint/tmlibs/common" "github.com/tendermint/go-crypto" "github.com/tendermint/go-wire" + "github.com/tendermint/go-wire/data" + cmn "github.com/tendermint/tmlibs/common" ) var ( @@ -47,7 +48,7 @@ func IsVoteTypeValid(type_ byte) bool { // Represents a prevote, precommit, or commit vote from validators for consensus. type Vote struct { - ValidatorAddress []byte `json:"validator_address"` + ValidatorAddress data.Bytes `json:"validator_address"` ValidatorIndex int `json:"validator_index"` Height int `json:"height"` Round int `json:"round"` @@ -79,11 +80,11 @@ func (vote *Vote) String() string { case VoteTypePrecommit: typeString = "Precommit" default: - PanicSanity("Unknown vote type") + cmn.PanicSanity("Unknown vote type") } return fmt.Sprintf("Vote{%v:%X %v/%02d/%v(%v) %X %v}", - vote.ValidatorIndex, Fingerprint(vote.ValidatorAddress), + vote.ValidatorIndex, cmn.Fingerprint(vote.ValidatorAddress), vote.Height, vote.Round, vote.Type, typeString, - Fingerprint(vote.BlockID.Hash), vote.Signature) + cmn.Fingerprint(vote.BlockID.Hash), vote.Signature) } From cdf650fba9fb8e277e06cb0d15ed63f25cfb8cf4 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Thu, 27 Apr 2017 19:06:07 -0400 Subject: [PATCH 219/309] rpc: repsonse types use data.Bytes --- rpc/core/types/responses.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/rpc/core/types/responses.go b/rpc/core/types/responses.go index 469e71061..b4b52c9e5 100644 --- a/rpc/core/types/responses.go +++ b/rpc/core/types/responses.go @@ -5,10 +5,10 @@ import ( abci "github.com/tendermint/abci/types" "github.com/tendermint/go-crypto" - data "github.com/tendermint/go-wire/data" + "github.com/tendermint/go-wire" + "github.com/tendermint/go-wire/data" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/rpc/lib/types" - "github.com/tendermint/go-wire" "github.com/tendermint/tendermint/types" ) @@ -85,13 +85,13 @@ type ResultBroadcastTx struct { Data data.Bytes `json:"data"` Log string `json:"log"` - Hash []byte `json:"hash"` + Hash data.Bytes `json:"hash"` } type ResultBroadcastTxCommit struct { CheckTx *abci.ResponseCheckTx `json:"check_tx"` DeliverTx *abci.ResponseDeliverTx `json:"deliver_tx"` - Hash []byte `json:"hash"` + Hash data.Bytes `json:"hash"` Height int `json:"height"` } From a518d08839cc429bed1626fadd4eb101d744d73a Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Thu, 27 Apr 2017 19:34:25 -0400 Subject: [PATCH 220/309] rpc: response types use Result instead of pb Response --- rpc/core/abci.go | 10 +++++++++- rpc/core/mempool.go | 12 ++++++------ rpc/core/tx.go | 2 +- rpc/core/types/responses.go | 26 ++++++++++++++++---------- rpc/grpc/api.go | 16 +++++++++++++++- 5 files changed, 47 insertions(+), 19 deletions(-) diff --git a/rpc/core/abci.go b/rpc/core/abci.go index 5c9fcfc25..4b210ff13 100644 --- a/rpc/core/abci.go +++ b/rpc/core/abci.go @@ -18,7 +18,15 @@ func ABCIQuery(path string, data data.Bytes, prove bool) (*ctypes.ResultABCIQuer return nil, err } log.Info("ABCIQuery", "path", path, "data", data, "result", resQuery) - return &ctypes.ResultABCIQuery{resQuery}, nil + return &ctypes.ResultABCIQuery{ + Code: resQuery.Code, + Index: resQuery.Index, + Key: resQuery.Key, + Value: resQuery.Value, + Proof: resQuery.Proof, + Height: resQuery.Height, + Log: resQuery.Log, + }, nil } func ABCIInfo() (*ctypes.ResultABCIInfo, error) { diff --git a/rpc/core/mempool.go b/rpc/core/mempool.go index 4adf75ce5..4c1b54cfc 100644 --- a/rpc/core/mempool.go +++ b/rpc/core/mempool.go @@ -67,8 +67,8 @@ func BroadcastTxCommit(tx types.Tx) (*ctypes.ResultBroadcastTxCommit, error) { if checkTxR.Code != abci.CodeType_OK { // CheckTx failed! return &ctypes.ResultBroadcastTxCommit{ - CheckTx: checkTxR, - DeliverTx: nil, + CheckTx: checkTxR.Result(), + DeliverTx: abci.Result{}, Hash: tx.Hash(), }, nil } @@ -87,16 +87,16 @@ func BroadcastTxCommit(tx types.Tx) (*ctypes.ResultBroadcastTxCommit, error) { } log.Notice("DeliverTx passed ", "tx", data.Bytes(tx), "response", deliverTxR) return &ctypes.ResultBroadcastTxCommit{ - CheckTx: checkTxR, - DeliverTx: deliverTxR, + CheckTx: checkTxR.Result(), + DeliverTx: deliverTxR.Result(), Hash: tx.Hash(), Height: deliverTxRes.Height, }, nil case <-timer.C: log.Error("failed to include tx") return &ctypes.ResultBroadcastTxCommit{ - CheckTx: checkTxR, - DeliverTx: nil, + CheckTx: checkTxR.Result(), + DeliverTx: abci.Result{}, Hash: tx.Hash(), }, fmt.Errorf("Timed out waiting for transaction to be included in a block") } diff --git a/rpc/core/tx.go b/rpc/core/tx.go index 7f3cdd037..387d4afa6 100644 --- a/rpc/core/tx.go +++ b/rpc/core/tx.go @@ -36,7 +36,7 @@ func Tx(hash []byte, prove bool) (*ctypes.ResultTx, error) { return &ctypes.ResultTx{ Height: height, Index: index, - TxResult: r.Result, + TxResult: r.Result.Result(), Tx: r.Tx, Proof: proof, }, nil diff --git a/rpc/core/types/responses.go b/rpc/core/types/responses.go index b4b52c9e5..367c82d23 100644 --- a/rpc/core/types/responses.go +++ b/rpc/core/types/responses.go @@ -89,18 +89,18 @@ type ResultBroadcastTx struct { } type ResultBroadcastTxCommit struct { - CheckTx *abci.ResponseCheckTx `json:"check_tx"` - DeliverTx *abci.ResponseDeliverTx `json:"deliver_tx"` - Hash data.Bytes `json:"hash"` - Height int `json:"height"` + CheckTx abci.Result `json:"check_tx"` + DeliverTx abci.Result `json:"deliver_tx"` + Hash data.Bytes `json:"hash"` + Height int `json:"height"` } type ResultTx struct { - Height int `json:"height"` - Index int `json:"index"` - TxResult abci.ResponseDeliverTx `json:"tx_result"` - Tx types.Tx `json:"tx"` - Proof types.TxProof `json:"proof,omitempty"` + Height int `json:"height"` + Index int `json:"index"` + TxResult abci.Result `json:"tx_result"` + Tx types.Tx `json:"tx"` + Proof types.TxProof `json:"proof,omitempty"` } type ResultUnconfirmedTxs struct { @@ -113,7 +113,13 @@ type ResultABCIInfo struct { } type ResultABCIQuery struct { - Response abci.ResponseQuery `json:"response"` + Code abci.CodeType `json:"code"` + Index int64 `json:"index"` + Key []byte `json:"key"` + Value []byte `json:"value"` + Proof []byte `json:"proof"` + Height uint64 `json:"height"` + Log string `json:"log"` } type ResultUnsafeFlushMempool struct{} diff --git a/rpc/grpc/api.go b/rpc/grpc/api.go index fab811c2e..7cfda1587 100644 --- a/rpc/grpc/api.go +++ b/rpc/grpc/api.go @@ -3,6 +3,8 @@ package core_grpc import ( core "github.com/tendermint/tendermint/rpc/core" + abci "github.com/tendermint/abci/types" + context "golang.org/x/net/context" ) @@ -14,5 +16,17 @@ func (bapi *broadcastAPI) BroadcastTx(ctx context.Context, req *RequestBroadcast if err != nil { return nil, err } - return &ResponseBroadcastTx{res.CheckTx, res.DeliverTx}, nil + return &ResponseBroadcastTx{ + + CheckTx: &abci.ResponseCheckTx{ + Code: res.CheckTx.Code, + Data: res.CheckTx.Data, + Log: res.CheckTx.Log, + }, + DeliverTx: &abci.ResponseDeliverTx{ + Code: res.DeliverTx.Code, + Data: res.DeliverTx.Data, + Log: res.DeliverTx.Log, + }, + }, nil } From c930f43cbe03fdc9a6b1018bdd5d002f095bd1b0 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Thu, 27 Apr 2017 19:51:18 -0400 Subject: [PATCH 221/309] rpc: fix tests --- rpc/client/mock/abci.go | 13 ++++++------- rpc/client/mock/abci_test.go | 12 ++++++------ rpc/client/rpc_test.go | 20 +++++++++----------- rpc/core/abci.go | 8 +------- rpc/core/types/responses.go | 8 +------- rpc/test/client_test.go | 10 +++++----- 6 files changed, 28 insertions(+), 43 deletions(-) diff --git a/rpc/client/mock/abci.go b/rpc/client/mock/abci.go index db9bd2c2b..0d1012557 100644 --- a/rpc/client/mock/abci.go +++ b/rpc/client/mock/abci.go @@ -25,18 +25,16 @@ func (a ABCIApp) ABCIInfo() (*ctypes.ResultABCIInfo, error) { func (a ABCIApp) ABCIQuery(path string, data data.Bytes, prove bool) (*ctypes.ResultABCIQuery, error) { q := a.App.Query(abci.RequestQuery{data, path, 0, prove}) - return &ctypes.ResultABCIQuery{q}, nil + return &ctypes.ResultABCIQuery{q.Result()}, nil } func (a ABCIApp) BroadcastTxCommit(tx types.Tx) (*ctypes.ResultBroadcastTxCommit, error) { res := ctypes.ResultBroadcastTxCommit{} - c := a.App.CheckTx(tx) - res.CheckTx = &abci.ResponseCheckTx{c.Code, c.Data, c.Log} - if !c.IsOK() { + res.CheckTx = a.App.CheckTx(tx) + if !res.CheckTx.IsOK() { return &res, nil } - d := a.App.DeliverTx(tx) - res.DeliverTx = &abci.ResponseDeliverTx{d.Code, d.Data, d.Log} + res.DeliverTx = a.App.DeliverTx(tx) return &res, nil } @@ -85,7 +83,8 @@ func (m ABCIMock) ABCIQuery(path string, data data.Bytes, prove bool) (*ctypes.R if err != nil { return nil, err } - return &ctypes.ResultABCIQuery{res.(abci.ResponseQuery)}, nil + resQuery := res.(abci.ResponseQuery) + return &ctypes.ResultABCIQuery{resQuery.Result()}, nil } func (m ABCIMock) BroadcastTxCommit(tx types.Tx) (*ctypes.ResultBroadcastTxCommit, error) { diff --git a/rpc/client/mock/abci_test.go b/rpc/client/mock/abci_test.go index 57334f25f..935f9ff94 100644 --- a/rpc/client/mock/abci_test.go +++ b/rpc/client/mock/abci_test.go @@ -36,8 +36,8 @@ func TestABCIMock(t *testing.T) { BroadcastCommit: mock.Call{ Args: goodTx, Response: &ctypes.ResultBroadcastTxCommit{ - CheckTx: &abci.ResponseCheckTx{Data: data.Bytes("stand")}, - DeliverTx: &abci.ResponseDeliverTx{Data: data.Bytes("deliver")}, + CheckTx: abci.Result{Data: data.Bytes("stand")}, + DeliverTx: abci.Result{Data: data.Bytes("deliver")}, }, Error: errors.New("bad tx"), }, @@ -53,9 +53,9 @@ func TestABCIMock(t *testing.T) { query, err := m.ABCIQuery("/", nil, false) require.Nil(err) require.NotNil(query) - assert.Equal(key, query.Response.GetKey()) - assert.Equal(value, query.Response.GetValue()) - assert.Equal(height, query.Response.GetHeight()) + assert.EqualValues(key, query.Key) + assert.EqualValues(value, query.Value) + assert.Equal(height, query.Height) // non-commit calls always return errors _, err = m.BroadcastTxSync(goodTx) @@ -166,5 +166,5 @@ func TestABCIApp(t *testing.T) { // check the key qres, err := m.ABCIQuery("/key", data.Bytes(key), false) require.Nil(err) - assert.EqualValues(value, qres.Response.Value) + assert.EqualValues(value, qres.Value) } diff --git a/rpc/client/rpc_test.go b/rpc/client/rpc_test.go index d0cb7a47b..4c21a4afc 100644 --- a/rpc/client/rpc_test.go +++ b/rpc/client/rpc_test.go @@ -10,7 +10,6 @@ import ( merktest "github.com/tendermint/merkleeyes/testutil" "github.com/tendermint/tendermint/rpc/client" rpctest "github.com/tendermint/tendermint/rpc/test" - "github.com/tendermint/tendermint/types" ) func getHTTPClient() *client.HTTP { @@ -119,17 +118,16 @@ func TestAppCalls(t *testing.T) { k, v, tx := merktest.MakeTxKV() bres, err := c.BroadcastTxCommit(tx) require.Nil(err, "%d: %+v", i, err) - require.True(bres.DeliverTx.GetCode().IsOK()) + require.True(bres.DeliverTx.Code.IsOK()) txh := bres.Height apph := txh + 1 // this is where the tx will be applied to the state // wait before querying client.WaitForHeight(c, apph, nil) qres, err := c.ABCIQuery("/key", k, false) - if assert.Nil(err) && assert.True(qres.Response.Code.IsOK()) { - data := qres.Response + if assert.Nil(err) && assert.True(qres.Code.IsOK()) { // assert.Equal(k, data.GetKey()) // only returned for proofs - assert.Equal(v, data.GetValue()) + assert.EqualValues(v, qres.Value) } // make sure we can lookup the tx with proof @@ -137,7 +135,7 @@ func TestAppCalls(t *testing.T) { ptx, err := c.Tx(bres.Hash, true) require.Nil(err, "%d: %+v", i, err) assert.Equal(txh, ptx.Height) - assert.Equal(types.Tx(tx), ptx.Tx) + assert.EqualValues(tx, ptx.Tx) // and we can even check the block is added block, err := c.Block(apph) @@ -174,12 +172,12 @@ func TestAppCalls(t *testing.T) { // and we got a proof that works! pres, err := c.ABCIQuery("/key", k, true) - if assert.Nil(err) && assert.True(pres.Response.Code.IsOK()) { - proof, err := iavl.ReadProof(pres.Response.GetProof()) + if assert.Nil(err) && assert.True(pres.Code.IsOK()) { + proof, err := iavl.ReadProof(pres.Proof) if assert.Nil(err) { - key := pres.Response.GetKey() - value := pres.Response.GetValue() - assert.Equal(appHash, proof.RootHash) + key := pres.Key + value := pres.Value + assert.EqualValues(appHash, proof.RootHash) valid := proof.Verify(key, value, appHash) assert.True(valid) } diff --git a/rpc/core/abci.go b/rpc/core/abci.go index 4b210ff13..169447526 100644 --- a/rpc/core/abci.go +++ b/rpc/core/abci.go @@ -19,13 +19,7 @@ func ABCIQuery(path string, data data.Bytes, prove bool) (*ctypes.ResultABCIQuer } log.Info("ABCIQuery", "path", path, "data", data, "result", resQuery) return &ctypes.ResultABCIQuery{ - Code: resQuery.Code, - Index: resQuery.Index, - Key: resQuery.Key, - Value: resQuery.Value, - Proof: resQuery.Proof, - Height: resQuery.Height, - Log: resQuery.Log, + resQuery.Result(), }, nil } diff --git a/rpc/core/types/responses.go b/rpc/core/types/responses.go index 367c82d23..ae2340a78 100644 --- a/rpc/core/types/responses.go +++ b/rpc/core/types/responses.go @@ -113,13 +113,7 @@ type ResultABCIInfo struct { } type ResultABCIQuery struct { - Code abci.CodeType `json:"code"` - Index int64 `json:"index"` - Key []byte `json:"key"` - Value []byte `json:"value"` - Proof []byte `json:"proof"` - Height uint64 `json:"height"` - Log string `json:"log"` + *abci.ResultQuery `json:"response"` } type ResultUnsafeFlushMempool struct{} diff --git a/rpc/test/client_test.go b/rpc/test/client_test.go index 67c88356d..6d0905fde 100644 --- a/rpc/test/client_test.go +++ b/rpc/test/client_test.go @@ -12,9 +12,9 @@ import ( "github.com/stretchr/testify/require" abci "github.com/tendermint/abci/types" - rpc "github.com/tendermint/tendermint/rpc/lib/client" "github.com/tendermint/tendermint/rpc/core" ctypes "github.com/tendermint/tendermint/rpc/core/types" + rpc "github.com/tendermint/tendermint/rpc/lib/client" "github.com/tendermint/tendermint/state/txindex/null" "github.com/tendermint/tendermint/types" . "github.com/tendermint/tmlibs/common" @@ -98,8 +98,8 @@ func sendTx(t *testing.T, client rpc.HTTPClient) ([]byte, []byte) { require.Nil(t, err) bres := (*tmResult).(*ctypes.ResultBroadcastTxCommit) require.NotNil(t, 0, bres.DeliverTx, "%#v", bres) - require.EqualValues(t, 0, bres.CheckTx.GetCode(), "%#v", bres) - require.EqualValues(t, 0, bres.DeliverTx.GetCode(), "%#v", bres) + require.EqualValues(t, 0, bres.CheckTx.Code, "%#v", bres) + require.EqualValues(t, 0, bres.DeliverTx.Code, "%#v", bres) return k, v } @@ -120,10 +120,10 @@ func testABCIQuery(t *testing.T, client rpc.HTTPClient) { require.Nil(t, err) resQuery := (*tmResult).(*ctypes.ResultABCIQuery) - require.EqualValues(t, 0, resQuery.Response.Code) + require.EqualValues(t, 0, resQuery.Code) // XXX: specific to value returned by the dummy - require.NotEqual(t, 0, len(resQuery.Response.Value)) + require.NotEqual(t, 0, len(resQuery.Value)) } //-------------------------------------------------------------------------------- From 2bf7e9c968f24c611e5663085d158b8c5ddabbc9 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Thu, 27 Apr 2017 19:58:12 -0400 Subject: [PATCH 222/309] update glide --- glide.lock | 45 +++++++++++++++++++++++++++------------------ 1 file changed, 27 insertions(+), 18 deletions(-) diff --git a/glide.lock b/glide.lock index 7720c946b..24d44a848 100644 --- a/glide.lock +++ b/glide.lock @@ -1,8 +1,8 @@ hash: 6f8962f6ca0e25b8e43bc6e496bd46c9ff3a79dcf789578efeeaee2fffc39c6e -updated: 2017-04-25T14:48:36.999444976-04:00 +updated: 2017-04-27T19:56:37.342860938-04:00 imports: - name: github.com/btcsuite/btcd - version: 583684b21bfbde9b5fc4403916fd7c807feb0289 + version: 4b348c1d33373d672edd83fc576892d0e46686d2 subpackages: - btcec - name: github.com/davecgh/go-spew @@ -20,11 +20,12 @@ imports: subpackages: - proto - name: github.com/golang/protobuf - version: 8ee79997227bf9b34611aee7946ae64735e6fd93 + version: 2bba0603135d7d7f5cb73b2125beeda19c09f4ef subpackages: - proto + - ptypes/any - name: github.com/golang/snappy - version: d9eb7a3d35ec988b8585d4a0068e462c27d28380 + version: 553a641470496b2327abcac10b36396bd98e45c9 - name: github.com/gorilla/websocket version: 3ab3a8b8831546bd18fd182c20687ca853b2bb13 - name: github.com/hashicorp/hcl @@ -45,9 +46,9 @@ imports: - name: github.com/magiconair/properties version: 51463bfca2576e06c62a8504b5c0f06d61312647 - name: github.com/mattn/go-colorable - version: d228849504861217f796da67fae4f6e347643f15 + version: ded68f7a9561c023e790de24279db7ebf473ea80 - name: github.com/mattn/go-isatty - version: 30a891c33c7cde7b02a981314b4228ec99380cca + version: fc9e8d8ef48496124e79ae0df75490096eccf6fe - name: github.com/mitchellh/mapstructure version: 53818660ed4955e899c0bcafa97299a388bd7c8e - name: github.com/pelletier/go-buffruneio @@ -67,11 +68,11 @@ imports: - name: github.com/spf13/cast version: acbeb36b902d72a7a4c18e8f3241075e7ab763e4 - name: github.com/spf13/cobra - version: fcd0c5a1df88f5d6784cb4feead962c3f3d0b66c + version: 10f6b9d7e1631a54ad07c5c0fb71c28a1abfd3c2 - name: github.com/spf13/jwalterweatherman version: fa7ca7e836cf3a8bb4ebf799f472c12d7e903d66 - name: github.com/spf13/pflag - version: 9ff6c6923cfffbcd502984b8e0c80539a94968b7 + version: 2300d0f8576fe575f71aaa5b9bbe4e1b0dc2eb51 - name: github.com/spf13/viper version: 5d46e70da8c0b6f812e0b170b7a985753b5c63cb - name: github.com/stretchr/testify @@ -80,7 +81,7 @@ imports: - assert - require - name: github.com/syndtr/goleveldb - version: 23851d93a2292dcc56e71a18ec9e0624d84a0f65 + version: 8c81ea47d4c41a385645e133e15510fc6a2a74b4 subpackages: - leveldb - leveldb/cache @@ -95,7 +96,7 @@ imports: - leveldb/table - leveldb/util - name: github.com/tendermint/abci - version: c709d3cc857929a8dd36a90da3640122d7e75770 + version: 8d8e35ae537538c9cf6808be3ca9dd7dab81b7f6 subpackages: - client - example/counter @@ -108,9 +109,9 @@ imports: - edwards25519 - extra25519 - name: github.com/tendermint/go-crypto - version: 9b95da8fa4187f6799558d89b271dc8ab6485615 + version: 197a2b270fd94ee03824b158e738fce62862d0b8 - name: github.com/tendermint/go-wire - version: 334005c236d19c632fb5f073f9de3b0fab6a522b + version: b53add0b622662731985485f3a19be7f684660b8 subpackages: - data - name: github.com/tendermint/log15 @@ -118,7 +119,7 @@ imports: subpackages: - term - name: github.com/tendermint/merkleeyes - version: 6fd69aa0871a4e685a5570aa7ab3d12e4068a722 + version: 0fab643ccac1a3f93b90e0e2682a5d1b9d17f8c4 subpackages: - app - client @@ -137,7 +138,7 @@ imports: - merkle - test - name: golang.org/x/crypto - version: 7c6cc321c680f03b9ef0764448e780704f486b51 + version: 96846453c37f0876340a66a47f3f75b1f3a6cd2d subpackages: - curve25519 - nacl/box @@ -148,7 +149,7 @@ imports: - ripemd160 - salsa20/salsa - name: golang.org/x/net - version: 61557ac0112b576429a0df080e1c2cef5dfbb642 + version: c8c74377599bd978aee1cf3b9b63a8634051cec2 subpackages: - context - http2 @@ -158,25 +159,33 @@ imports: - lex/httplex - trace - name: golang.org/x/sys - version: d75a52659825e75fff6158388dddc6a5b04f9ba5 + version: ea9bcade75cb975a0b9738936568ab388b845617 subpackages: - unix - name: golang.org/x/text - version: f4b4367115ec2de254587813edaa901bc1c723a8 + version: 19e3104b43db45fca0303f489a9536087b184802 subpackages: + - secure/bidirule - transform + - unicode/bidi - unicode/norm +- name: google.golang.org/genproto + version: 411e09b969b1170a9f0c467558eb4c4c110d9c77 + subpackages: + - googleapis/rpc/status - name: google.golang.org/grpc - version: cbcceb2942a489498cf22b2f918536e819d33f0a + version: 6914ab1e338c92da4218a23d27fcd03d0ad78d46 subpackages: - codes - credentials - grpclog - internal + - keepalive - metadata - naming - peer - stats + - status - tap - transport - name: gopkg.in/yaml.v2 From 194f3454700a6532bc2bca00266c48c3706a2e1b Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Fri, 28 Apr 2017 14:03:38 +0200 Subject: [PATCH 223/309] Use non-standard port so tests don't die when I am running basecoin --- glide.lock | 2 +- rpc/lib/rpc_test.go | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/glide.lock b/glide.lock index 24d44a848..b78270bd7 100644 --- a/glide.lock +++ b/glide.lock @@ -119,7 +119,7 @@ imports: subpackages: - term - name: github.com/tendermint/merkleeyes - version: 0fab643ccac1a3f93b90e0e2682a5d1b9d17f8c4 + version: ea4dd9c7b773435de26bf59fddf90afd43a07d67 subpackages: - app - client diff --git a/rpc/lib/rpc_test.go b/rpc/lib/rpc_test.go index 2ce19fa75..f42fd274c 100644 --- a/rpc/lib/rpc_test.go +++ b/rpc/lib/rpc_test.go @@ -20,10 +20,10 @@ import ( // Client and Server should work over tcp or unix sockets const ( - tcpAddr = "tcp://0.0.0.0:46657" + tcpAddr = "tcp://0.0.0.0:47768" - unixSocket = "/tmp/rpc.sock" - unixAddr = "unix:///tmp/rpc.sock" + unixSocket = "/tmp/rpc_test.sock" + unixAddr = "unix://" + unixSocket websocketEndpoint = "/websocket/endpoint" ) From f6f1f1992cb9d1a54a5d1851bad642efe2e0bd5f Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Fri, 28 Apr 2017 14:41:08 +0200 Subject: [PATCH 224/309] Prepare rpc responses for go-data compatibility, still use go-wire --- rpc/client/httpclient.go | 34 +++++----- rpc/core/events.go | 4 +- rpc/core/routes.go | 74 ++++++++++++++-------- rpc/core/types/responses.go | 121 +++++++++++++++++++++++++++--------- rpc/test/client_test.go | 14 ++--- rpc/test/helpers.go | 4 +- 6 files changed, 169 insertions(+), 82 deletions(-) diff --git a/rpc/client/httpclient.go b/rpc/client/httpclient.go index 8f3a4f019..7eecea641 100644 --- a/rpc/client/httpclient.go +++ b/rpc/client/httpclient.go @@ -4,12 +4,12 @@ import ( "fmt" "github.com/pkg/errors" - data "github.com/tendermint/go-wire/data" - events "github.com/tendermint/tmlibs/events" - "github.com/tendermint/tendermint/rpc/lib/client" wire "github.com/tendermint/go-wire" + data "github.com/tendermint/go-wire/data" ctypes "github.com/tendermint/tendermint/rpc/core/types" + "github.com/tendermint/tendermint/rpc/lib/client" "github.com/tendermint/tendermint/types" + events "github.com/tendermint/tmlibs/events" ) /* @@ -56,7 +56,7 @@ func (c *HTTP) Status() (*ctypes.ResultStatus, error) { return nil, errors.Wrap(err, "Status") } // note: panics if rpc doesn't match. okay??? - return (*tmResult).(*ctypes.ResultStatus), nil + return tmResult.Unwrap().(*ctypes.ResultStatus), nil } func (c *HTTP) ABCIInfo() (*ctypes.ResultABCIInfo, error) { @@ -65,7 +65,7 @@ func (c *HTTP) ABCIInfo() (*ctypes.ResultABCIInfo, error) { if err != nil { return nil, errors.Wrap(err, "ABCIInfo") } - return (*tmResult).(*ctypes.ResultABCIInfo), nil + return tmResult.Unwrap().(*ctypes.ResultABCIInfo), nil } func (c *HTTP) ABCIQuery(path string, data data.Bytes, prove bool) (*ctypes.ResultABCIQuery, error) { @@ -76,7 +76,7 @@ func (c *HTTP) ABCIQuery(path string, data data.Bytes, prove bool) (*ctypes.Resu if err != nil { return nil, errors.Wrap(err, "ABCIQuery") } - return (*tmResult).(*ctypes.ResultABCIQuery), nil + return tmResult.Unwrap().(*ctypes.ResultABCIQuery), nil } func (c *HTTP) BroadcastTxCommit(tx types.Tx) (*ctypes.ResultBroadcastTxCommit, error) { @@ -85,7 +85,7 @@ func (c *HTTP) BroadcastTxCommit(tx types.Tx) (*ctypes.ResultBroadcastTxCommit, if err != nil { return nil, errors.Wrap(err, "broadcast_tx_commit") } - return (*tmResult).(*ctypes.ResultBroadcastTxCommit), nil + return tmResult.Unwrap().(*ctypes.ResultBroadcastTxCommit), nil } func (c *HTTP) BroadcastTxAsync(tx types.Tx) (*ctypes.ResultBroadcastTx, error) { @@ -102,7 +102,7 @@ func (c *HTTP) broadcastTX(route string, tx types.Tx) (*ctypes.ResultBroadcastTx if err != nil { return nil, errors.Wrap(err, route) } - return (*tmResult).(*ctypes.ResultBroadcastTx), nil + return tmResult.Unwrap().(*ctypes.ResultBroadcastTx), nil } func (c *HTTP) NetInfo() (*ctypes.ResultNetInfo, error) { @@ -111,7 +111,7 @@ func (c *HTTP) NetInfo() (*ctypes.ResultNetInfo, error) { if err != nil { return nil, errors.Wrap(err, "NetInfo") } - return (*tmResult).(*ctypes.ResultNetInfo), nil + return tmResult.Unwrap().(*ctypes.ResultNetInfo), nil } func (c *HTTP) DumpConsensusState() (*ctypes.ResultDumpConsensusState, error) { @@ -120,7 +120,7 @@ func (c *HTTP) DumpConsensusState() (*ctypes.ResultDumpConsensusState, error) { if err != nil { return nil, errors.Wrap(err, "DumpConsensusState") } - return (*tmResult).(*ctypes.ResultDumpConsensusState), nil + return tmResult.Unwrap().(*ctypes.ResultDumpConsensusState), nil } func (c *HTTP) BlockchainInfo(minHeight, maxHeight int) (*ctypes.ResultBlockchainInfo, error) { @@ -131,7 +131,7 @@ func (c *HTTP) BlockchainInfo(minHeight, maxHeight int) (*ctypes.ResultBlockchai if err != nil { return nil, errors.Wrap(err, "BlockchainInfo") } - return (*tmResult).(*ctypes.ResultBlockchainInfo), nil + return tmResult.Unwrap().(*ctypes.ResultBlockchainInfo), nil } func (c *HTTP) Genesis() (*ctypes.ResultGenesis, error) { @@ -140,7 +140,7 @@ func (c *HTTP) Genesis() (*ctypes.ResultGenesis, error) { if err != nil { return nil, errors.Wrap(err, "Genesis") } - return (*tmResult).(*ctypes.ResultGenesis), nil + return tmResult.Unwrap().(*ctypes.ResultGenesis), nil } func (c *HTTP) Block(height int) (*ctypes.ResultBlock, error) { @@ -149,7 +149,7 @@ func (c *HTTP) Block(height int) (*ctypes.ResultBlock, error) { if err != nil { return nil, errors.Wrap(err, "Block") } - return (*tmResult).(*ctypes.ResultBlock), nil + return tmResult.Unwrap().(*ctypes.ResultBlock), nil } func (c *HTTP) Commit(height int) (*ctypes.ResultCommit, error) { @@ -158,7 +158,7 @@ func (c *HTTP) Commit(height int) (*ctypes.ResultCommit, error) { if err != nil { return nil, errors.Wrap(err, "Commit") } - return (*tmResult).(*ctypes.ResultCommit), nil + return tmResult.Unwrap().(*ctypes.ResultCommit), nil } func (c *HTTP) Tx(hash []byte, prove bool) (*ctypes.ResultTx, error) { @@ -171,7 +171,7 @@ func (c *HTTP) Tx(hash []byte, prove bool) (*ctypes.ResultTx, error) { if err != nil { return nil, errors.Wrap(err, "Tx") } - return (*tmResult).(*ctypes.ResultTx), nil + return tmResult.Unwrap().(*ctypes.ResultTx), nil } func (c *HTTP) Validators() (*ctypes.ResultValidators, error) { @@ -180,7 +180,7 @@ func (c *HTTP) Validators() (*ctypes.ResultValidators, error) { if err != nil { return nil, errors.Wrap(err, "Validators") } - return (*tmResult).(*ctypes.ResultValidators), nil + return tmResult.Unwrap().(*ctypes.ResultValidators), nil } /** websocket event stuff here... **/ @@ -340,7 +340,7 @@ func (w *WSEvents) parseEvent(data []byte) (err error) { if err != nil { return err } - event, ok := (*result).(*ctypes.ResultEvent) + event, ok := result.Unwrap().(*ctypes.ResultEvent) if !ok { // ignore silently (eg. subscribe, unsubscribe and maybe other events) return nil diff --git a/rpc/core/events.go b/rpc/core/events.go index 555673df5..271ba5301 100644 --- a/rpc/core/events.go +++ b/rpc/core/events.go @@ -1,8 +1,8 @@ package core import ( - "github.com/tendermint/tendermint/rpc/lib/types" ctypes "github.com/tendermint/tendermint/rpc/core/types" + "github.com/tendermint/tendermint/rpc/lib/types" "github.com/tendermint/tendermint/types" ) @@ -11,7 +11,7 @@ func Subscribe(wsCtx rpctypes.WSRPCContext, event string) (*ctypes.ResultSubscri types.AddListenerForEvent(wsCtx.GetEventSwitch(), wsCtx.GetRemoteAddr(), event, func(msg types.TMEventData) { // NOTE: EventSwitch callbacks must be nonblocking // NOTE: RPCResponses of subscribed events have id suffix "#event" - tmResult := ctypes.TMResult(&ctypes.ResultEvent{event, msg}) + tmResult := ctypes.TMResult{&ctypes.ResultEvent{event, msg}} wsCtx.TryWriteRPCResponse(rpctypes.NewRPCResponse(wsCtx.Request.ID+"#event", &tmResult, "")) }) return &ctypes.ResultSubscribe{}, nil diff --git a/rpc/core/routes.go b/rpc/core/routes.go index 12694ab76..9e4c03be1 100644 --- a/rpc/core/routes.go +++ b/rpc/core/routes.go @@ -2,8 +2,8 @@ package core import ( data "github.com/tendermint/go-wire/data" - rpc "github.com/tendermint/tendermint/rpc/lib/server" ctypes "github.com/tendermint/tendermint/rpc/core/types" + rpc "github.com/tendermint/tendermint/rpc/lib/server" "github.com/tendermint/tendermint/rpc/lib/types" "github.com/tendermint/tendermint/types" ) @@ -50,100 +50,124 @@ var Routes = map[string]*rpc.RPCFunc{ } func SubscribeResult(wsCtx rpctypes.WSRPCContext, event string) (ctypes.TMResult, error) { - return Subscribe(wsCtx, event) + res, err := Subscribe(wsCtx, event) + return ctypes.TMResult{res}, err } func UnsubscribeResult(wsCtx rpctypes.WSRPCContext, event string) (ctypes.TMResult, error) { - return Unsubscribe(wsCtx, event) + res, err := Unsubscribe(wsCtx, event) + return ctypes.TMResult{res}, err } func StatusResult() (ctypes.TMResult, error) { - return Status() + res, err := Status() + return ctypes.TMResult{res}, err } func NetInfoResult() (ctypes.TMResult, error) { - return NetInfo() + res, err := NetInfo() + return ctypes.TMResult{res}, err } func UnsafeDialSeedsResult(seeds []string) (ctypes.TMResult, error) { - return UnsafeDialSeeds(seeds) + res, err := UnsafeDialSeeds(seeds) + return ctypes.TMResult{res}, err } func BlockchainInfoResult(min, max int) (ctypes.TMResult, error) { - return BlockchainInfo(min, max) + res, err := BlockchainInfo(min, max) + return ctypes.TMResult{res}, err } func GenesisResult() (ctypes.TMResult, error) { - return Genesis() + res, err := Genesis() + return ctypes.TMResult{res}, err } func BlockResult(height int) (ctypes.TMResult, error) { - return Block(height) + res, err := Block(height) + return ctypes.TMResult{res}, err } func CommitResult(height int) (ctypes.TMResult, error) { - return Commit(height) + res, err := Commit(height) + return ctypes.TMResult{res}, err } func ValidatorsResult() (ctypes.TMResult, error) { - return Validators() + res, err := Validators() + return ctypes.TMResult{res}, err } func DumpConsensusStateResult() (ctypes.TMResult, error) { - return DumpConsensusState() + res, err := DumpConsensusState() + return ctypes.TMResult{res}, err } func UnconfirmedTxsResult() (ctypes.TMResult, error) { - return UnconfirmedTxs() + res, err := UnconfirmedTxs() + return ctypes.TMResult{res}, err } func NumUnconfirmedTxsResult() (ctypes.TMResult, error) { - return NumUnconfirmedTxs() + res, err := NumUnconfirmedTxs() + return ctypes.TMResult{res}, err } // Tx allow user to query the transaction results. `nil` could mean the // transaction is in the mempool, invalidated, or was not send in the first // place. func TxResult(hash []byte, prove bool) (ctypes.TMResult, error) { - return Tx(hash, prove) + res, err := Tx(hash, prove) + return ctypes.TMResult{res}, err } func BroadcastTxCommitResult(tx types.Tx) (ctypes.TMResult, error) { - return BroadcastTxCommit(tx) + res, err := BroadcastTxCommit(tx) + return ctypes.TMResult{res}, err } func BroadcastTxSyncResult(tx types.Tx) (ctypes.TMResult, error) { - return BroadcastTxSync(tx) + res, err := BroadcastTxSync(tx) + return ctypes.TMResult{res}, err } func BroadcastTxAsyncResult(tx types.Tx) (ctypes.TMResult, error) { - return BroadcastTxAsync(tx) + res, err := BroadcastTxAsync(tx) + return ctypes.TMResult{res}, err } func ABCIQueryResult(path string, data data.Bytes, prove bool) (ctypes.TMResult, error) { - return ABCIQuery(path, data, prove) + res, err := ABCIQuery(path, data, prove) + return ctypes.TMResult{res}, err } func ABCIInfoResult() (ctypes.TMResult, error) { - return ABCIInfo() + res, err := ABCIInfo() + return ctypes.TMResult{res}, err } func UnsafeFlushMempoolResult() (ctypes.TMResult, error) { - return UnsafeFlushMempool() + res, err := UnsafeFlushMempool() + return ctypes.TMResult{res}, err } func UnsafeSetConfigResult(typ, key, value string) (ctypes.TMResult, error) { - return UnsafeSetConfig(typ, key, value) + res, err := UnsafeSetConfig(typ, key, value) + return ctypes.TMResult{res}, err } func UnsafeStartCPUProfilerResult(filename string) (ctypes.TMResult, error) { - return UnsafeStartCPUProfiler(filename) + res, err := UnsafeStartCPUProfiler(filename) + return ctypes.TMResult{res}, err } func UnsafeStopCPUProfilerResult() (ctypes.TMResult, error) { - return UnsafeStopCPUProfiler() + res, err := UnsafeStopCPUProfiler() + return ctypes.TMResult{res}, err } func UnsafeWriteHeapProfileResult(filename string) (ctypes.TMResult, error) { - return UnsafeWriteHeapProfile(filename) + res, err := UnsafeWriteHeapProfile(filename) + return ctypes.TMResult{res}, err } diff --git a/rpc/core/types/responses.go b/rpc/core/types/responses.go index ae2340a78..98056a8ce 100644 --- a/rpc/core/types/responses.go +++ b/rpc/core/types/responses.go @@ -5,7 +5,6 @@ import ( abci "github.com/tendermint/abci/types" "github.com/tendermint/go-crypto" - "github.com/tendermint/go-wire" "github.com/tendermint/go-wire/data" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/rpc/lib/types" @@ -175,34 +174,98 @@ const ( ResultTypeUnsafeFlushMempool = byte(0xa4) ) -type TMResult interface { +const ( + // for the blockchain + ResultNameGenesis = "genesis" + ResultNameBlockchainInfo = "info" + ResultNameBlock = "block" + ResultNameCommit = "commit" + + // for the network + ResultNameStatus = "status" + ResultNameNetInfo = "netinfo" + ResultNameDialSeeds = "dialseeds" + + // for the consensus + ResultNameValidators = "validators" + ResultNameDumpConsensusState = "consensus" + + // for txs / the application + ResultNameBroadcastTx = "broadcast_tx" + ResultNameUnconfirmedTxs = "unconfirmed_tx" + ResultNameBroadcastTxCommit = "broadcast_tx_commit" + ResultNameTx = "tx" + + // for querying the application + ResultNameABCIQuery = "abci_query" + ResultNameABCIInfo = "abci_info" + + // for events + ResultNameSubscribe = "subscribe" + ResultNameUnsubscribe = "unsubscribe" + ResultNameEvent = "event" + + // for testing + ResultNameUnsafeSetConfig = "unsafe_set_config" + ResultNameUnsafeStartCPUProfiler = "unsafe_start_profiler" + ResultNameUnsafeStopCPUProfiler = "unsafe_stop_profiler" + ResultNameUnsafeWriteHeapProfile = "unsafe_write_heap" + ResultNameUnsafeFlushMempool = "unsafe_flush_mempool" +) + +type TMResultInner interface { rpctypes.Result } -// for wire.readReflect -var _ = wire.RegisterInterface( - struct{ TMResult }{}, - wire.ConcreteType{&ResultGenesis{}, ResultTypeGenesis}, - wire.ConcreteType{&ResultBlockchainInfo{}, ResultTypeBlockchainInfo}, - wire.ConcreteType{&ResultBlock{}, ResultTypeBlock}, - wire.ConcreteType{&ResultCommit{}, ResultTypeCommit}, - wire.ConcreteType{&ResultStatus{}, ResultTypeStatus}, - wire.ConcreteType{&ResultNetInfo{}, ResultTypeNetInfo}, - wire.ConcreteType{&ResultDialSeeds{}, ResultTypeDialSeeds}, - wire.ConcreteType{&ResultValidators{}, ResultTypeValidators}, - wire.ConcreteType{&ResultDumpConsensusState{}, ResultTypeDumpConsensusState}, - wire.ConcreteType{&ResultBroadcastTx{}, ResultTypeBroadcastTx}, - wire.ConcreteType{&ResultBroadcastTxCommit{}, ResultTypeBroadcastTxCommit}, - wire.ConcreteType{&ResultTx{}, ResultTypeTx}, - wire.ConcreteType{&ResultUnconfirmedTxs{}, ResultTypeUnconfirmedTxs}, - wire.ConcreteType{&ResultSubscribe{}, ResultTypeSubscribe}, - wire.ConcreteType{&ResultUnsubscribe{}, ResultTypeUnsubscribe}, - wire.ConcreteType{&ResultEvent{}, ResultTypeEvent}, - wire.ConcreteType{&ResultUnsafeSetConfig{}, ResultTypeUnsafeSetConfig}, - wire.ConcreteType{&ResultUnsafeProfile{}, ResultTypeUnsafeStartCPUProfiler}, - wire.ConcreteType{&ResultUnsafeProfile{}, ResultTypeUnsafeStopCPUProfiler}, - wire.ConcreteType{&ResultUnsafeProfile{}, ResultTypeUnsafeWriteHeapProfile}, - wire.ConcreteType{&ResultUnsafeFlushMempool{}, ResultTypeUnsafeFlushMempool}, - wire.ConcreteType{&ResultABCIQuery{}, ResultTypeABCIQuery}, - wire.ConcreteType{&ResultABCIInfo{}, ResultTypeABCIInfo}, -) +type TMResult struct { + TMResultInner +} + +func (tmr TMResult) MarshalJSON() ([]byte, error) { + return tmResultMapper.ToJSON(tmr.TMResultInner) +} + +func (tmr *TMResult) UnmarshalJSON(data []byte) (err error) { + parsed, err := tmResultMapper.FromJSON(data) + if err == nil && parsed != nil { + tmr.TMResultInner = parsed.(TMResultInner) + } + return +} + +func (tmr TMResult) Unwrap() TMResultInner { + tmrI := tmr.TMResultInner + for wrap, ok := tmrI.(TMResult); ok; wrap, ok = tmrI.(TMResult) { + tmrI = wrap.TMResultInner + } + return tmrI +} + +func (tmr TMResult) Empty() bool { + return tmr.TMResultInner == nil +} + +var tmResultMapper = data.NewMapper(TMResult{}). + RegisterImplementation(&ResultGenesis{}, ResultNameGenesis, ResultTypeGenesis). + RegisterImplementation(&ResultBlockchainInfo{}, ResultNameBlockchainInfo, ResultTypeBlockchainInfo). + RegisterImplementation(&ResultBlock{}, ResultNameBlock, ResultTypeBlock). + RegisterImplementation(&ResultCommit{}, ResultNameCommit, ResultTypeCommit). + RegisterImplementation(&ResultStatus{}, ResultNameStatus, ResultTypeStatus). + RegisterImplementation(&ResultNetInfo{}, ResultNameNetInfo, ResultTypeNetInfo). + RegisterImplementation(&ResultDialSeeds{}, ResultNameDialSeeds, ResultTypeDialSeeds). + RegisterImplementation(&ResultValidators{}, ResultNameValidators, ResultTypeValidators). + RegisterImplementation(&ResultDumpConsensusState{}, ResultNameDumpConsensusState, ResultTypeDumpConsensusState). + RegisterImplementation(&ResultBroadcastTx{}, ResultNameBroadcastTx, ResultTypeBroadcastTx). + RegisterImplementation(&ResultBroadcastTxCommit{}, ResultNameBroadcastTxCommit, ResultTypeBroadcastTxCommit). + RegisterImplementation(&ResultTx{}, ResultNameTx, ResultTypeTx). + RegisterImplementation(&ResultUnconfirmedTxs{}, ResultNameUnconfirmedTxs, ResultTypeUnconfirmedTxs). + RegisterImplementation(&ResultSubscribe{}, ResultNameSubscribe, ResultTypeSubscribe). + RegisterImplementation(&ResultUnsubscribe{}, ResultNameUnsubscribe, ResultTypeUnsubscribe). + RegisterImplementation(&ResultEvent{}, ResultNameEvent, ResultTypeEvent). + RegisterImplementation(&ResultUnsafeSetConfig{}, ResultNameUnsafeSetConfig, ResultTypeUnsafeSetConfig). + RegisterImplementation(&ResultUnsafeProfile{}, ResultNameUnsafeStartCPUProfiler, ResultTypeUnsafeStartCPUProfiler). + RegisterImplementation(&ResultUnsafeProfile{}, ResultNameUnsafeStopCPUProfiler, ResultTypeUnsafeStopCPUProfiler). + RegisterImplementation(&ResultUnsafeProfile{}, ResultNameUnsafeWriteHeapProfile, ResultTypeUnsafeWriteHeapProfile). + RegisterImplementation(&ResultUnsafeFlushMempool{}, ResultNameUnsafeFlushMempool, ResultTypeUnsafeFlushMempool). + RegisterImplementation(&ResultABCIQuery{}, ResultNameABCIQuery, ResultTypeABCIQuery). + RegisterImplementation(&ResultABCIInfo{}, ResultNameABCIInfo, ResultTypeABCIInfo) diff --git a/rpc/test/client_test.go b/rpc/test/client_test.go index 6d0905fde..c9a922d72 100644 --- a/rpc/test/client_test.go +++ b/rpc/test/client_test.go @@ -42,7 +42,7 @@ func testStatus(t *testing.T, client rpc.HTTPClient) { _, err := client.Call("status", map[string]interface{}{}, tmResult) require.Nil(t, err) - status := (*tmResult).(*ctypes.ResultStatus) + status := tmResult.Unwrap().(*ctypes.ResultStatus) assert.Equal(t, chainID, status.NodeInfo.Network) } @@ -74,7 +74,7 @@ func testBroadcastTxSync(t *testing.T, client rpc.HTTPClient) { _, err := client.Call("broadcast_tx_sync", map[string]interface{}{"tx": tx}, tmResult) require.Nil(t, err) - res := (*tmResult).(*ctypes.ResultBroadcastTx) + res := tmResult.Unwrap().(*ctypes.ResultBroadcastTx) require.Equal(t, abci.CodeType_OK, res.Code) require.Equal(t, initMemSize+1, mem.Size()) txs := mem.Reap(1) @@ -96,7 +96,7 @@ func sendTx(t *testing.T, client rpc.HTTPClient) ([]byte, []byte) { k, v, tx := testTxKV(t) _, err := client.Call("broadcast_tx_commit", map[string]interface{}{"tx": tx}, tmResult) require.Nil(t, err) - bres := (*tmResult).(*ctypes.ResultBroadcastTxCommit) + bres := tmResult.Unwrap().(*ctypes.ResultBroadcastTxCommit) require.NotNil(t, 0, bres.DeliverTx, "%#v", bres) require.EqualValues(t, 0, bres.CheckTx.Code, "%#v", bres) require.EqualValues(t, 0, bres.DeliverTx.Code, "%#v", bres) @@ -119,7 +119,7 @@ func testABCIQuery(t *testing.T, client rpc.HTTPClient) { map[string]interface{}{"path": "", "data": k, "prove": false}, tmResult) require.Nil(t, err) - resQuery := (*tmResult).(*ctypes.ResultABCIQuery) + resQuery := tmResult.Unwrap().(*ctypes.ResultABCIQuery) require.EqualValues(t, 0, resQuery.Code) // XXX: specific to value returned by the dummy @@ -145,7 +145,7 @@ func testBroadcastTxCommit(t *testing.T, client rpc.HTTPClient) { _, err := client.Call("broadcast_tx_commit", map[string]interface{}{"tx": tx}, tmResult) require.Nil(err) - res := (*tmResult).(*ctypes.ResultBroadcastTxCommit) + res := tmResult.Unwrap().(*ctypes.ResultBroadcastTxCommit) checkTx := res.CheckTx require.Equal(abci.CodeType_OK, checkTx.Code) deliverTx := res.DeliverTx @@ -184,7 +184,7 @@ func testTx(t *testing.T, client rpc.HTTPClient, withIndexer bool) { _, err := client.Call("broadcast_tx_commit", map[string]interface{}{"tx": txBytes}, tmResult) require.Nil(err) - res := (*tmResult).(*ctypes.ResultBroadcastTxCommit) + res := tmResult.Unwrap().(*ctypes.ResultBroadcastTxCommit) checkTx := res.CheckTx require.Equal(abci.CodeType_OK, checkTx.Code) deliverTx := res.DeliverTx @@ -225,7 +225,7 @@ func testTx(t *testing.T, client rpc.HTTPClient, withIndexer bool) { require.NotNil(err, idx) } else { require.Nil(err, idx) - res2 := (*tmResult).(*ctypes.ResultTx) + res2 := tmResult.Unwrap().(*ctypes.ResultTx) assert.Equal(tx, res2.Tx, idx) assert.Equal(res.Height, res2.Height, idx) assert.Equal(0, res2.Index, idx) diff --git a/rpc/test/helpers.go b/rpc/test/helpers.go index 311f05980..622890596 100644 --- a/rpc/test/helpers.go +++ b/rpc/test/helpers.go @@ -18,9 +18,9 @@ import ( "github.com/tendermint/tendermint/config/tendermint_test" nm "github.com/tendermint/tendermint/node" "github.com/tendermint/tendermint/proxy" - client "github.com/tendermint/tendermint/rpc/lib/client" ctypes "github.com/tendermint/tendermint/rpc/core/types" core_grpc "github.com/tendermint/tendermint/rpc/grpc" + client "github.com/tendermint/tendermint/rpc/lib/client" "github.com/tendermint/tendermint/types" ) @@ -137,7 +137,7 @@ func waitForEvent(t *testing.T, wsc *client.WSClient, eventid string, dieOnTimeo errCh <- err break LOOP } - event, ok := (*result).(*ctypes.ResultEvent) + event, ok := result.Unwrap().(*ctypes.ResultEvent) if ok && event.Name == eventid { goodCh <- event.Data break LOOP From bff8402fe866c5234e212e3de8019375c2615ff6 Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Fri, 28 Apr 2017 15:26:06 +0200 Subject: [PATCH 225/309] Fix json for TMResult to not include "TMResultInner" --- rpc/core/types/responses.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/rpc/core/types/responses.go b/rpc/core/types/responses.go index 98056a8ce..9b4e9d579 100644 --- a/rpc/core/types/responses.go +++ b/rpc/core/types/responses.go @@ -218,7 +218,7 @@ type TMResultInner interface { } type TMResult struct { - TMResultInner + TMResultInner `json:"unwrap"` } func (tmr TMResult) MarshalJSON() ([]byte, error) { From 6c60c07f16f09e0f22ab2c3825b258c6b7690b4b Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Fri, 28 Apr 2017 16:24:06 +0200 Subject: [PATCH 226/309] BROKEN: attempt to replace go-wire.JSON with json.Unmarshall in rpc --- rpc/client/httpclient.go | 4 +-- rpc/lib/client/http_client.go | 22 +++++------- rpc/lib/client/ws_client.go | 15 ++++---- rpc/lib/rpc_test.go | 67 ++++++++++++++++++++++++----------- rpc/lib/server/handlers.go | 6 ++-- rpc/lib/types/types.go | 11 ++++-- rpc/test/helpers.go | 4 +-- 7 files changed, 77 insertions(+), 52 deletions(-) diff --git a/rpc/client/httpclient.go b/rpc/client/httpclient.go index 7eecea641..662ced895 100644 --- a/rpc/client/httpclient.go +++ b/rpc/client/httpclient.go @@ -1,10 +1,10 @@ package client import ( + "encoding/json" "fmt" "github.com/pkg/errors" - wire "github.com/tendermint/go-wire" data "github.com/tendermint/go-wire/data" ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/rpc/lib/client" @@ -336,7 +336,7 @@ func (w *WSEvents) eventListener() { // on the merry way to the EventSwitch func (w *WSEvents) parseEvent(data []byte) (err error) { result := new(ctypes.TMResult) - wire.ReadJSONPtr(result, data, &err) + err = json.Unmarshal(data, result) if err != nil { return err } diff --git a/rpc/lib/client/http_client.go b/rpc/lib/client/http_client.go index 45ff8b8ac..55963f506 100644 --- a/rpc/lib/client/http_client.go +++ b/rpc/lib/client/http_client.go @@ -12,7 +12,6 @@ import ( "strings" "github.com/pkg/errors" - wire "github.com/tendermint/go-wire" types "github.com/tendermint/tendermint/rpc/lib/types" ) @@ -70,15 +69,15 @@ func NewJSONRPCClient(remote string) *JSONRPCClient { func (c *JSONRPCClient) Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) { // we need this step because we attempt to decode values using `go-wire` // (handlers.go:176) on the server side - encodedParams := make(map[string]interface{}) - for k, v := range params { - bytes := json.RawMessage(wire.JSONBytes(v)) - encodedParams[k] = &bytes - } + // encodedParams := make(map[string]interface{}) + // for k, v := range params { + // bytes := json.RawMessage(wire.JSONBytes(v)) + // encodedParams[k] = &bytes + // } request := types.RPCRequest{ JSONRPC: "2.0", Method: method, - Params: encodedParams, + Params: params, ID: "", } requestBytes, err := json.Marshal(request) @@ -153,7 +152,7 @@ func unmarshalResponseBytes(responseBytes []byte, result interface{}) (interface return nil, errors.Errorf("Response error: %v", errorStr) } // unmarshal the RawMessage into the result - result = wire.ReadJSONPtr(result, *response.Result, &err) + err = json.Unmarshal(*response.Result, result) if err != nil { return nil, errors.Errorf("Error unmarshalling rpc response result: %v", err) } @@ -176,8 +175,6 @@ func argsToURLValues(args map[string]interface{}) (url.Values, error) { } func argsToJson(args map[string]interface{}) error { - var n int - var err error for k, v := range args { rt := reflect.TypeOf(v) isByteSlice := rt.Kind() == reflect.Slice && rt.Elem().Kind() == reflect.Uint8 @@ -188,12 +185,11 @@ func argsToJson(args map[string]interface{}) error { } // Pass everything else to go-wire - buf := new(bytes.Buffer) - wire.WriteJSON(v, buf, &n, &err) + data, err := json.Marshal(v) if err != nil { return err } - args[k] = buf.String() + args[k] = string(data) } return nil } diff --git a/rpc/lib/client/ws_client.go b/rpc/lib/client/ws_client.go index ad922dd68..8884068b9 100644 --- a/rpc/lib/client/ws_client.go +++ b/rpc/lib/client/ws_client.go @@ -8,9 +8,8 @@ import ( "github.com/gorilla/websocket" "github.com/pkg/errors" - cmn "github.com/tendermint/tmlibs/common" types "github.com/tendermint/tendermint/rpc/lib/types" - wire "github.com/tendermint/go-wire" + cmn "github.com/tendermint/tmlibs/common" ) const ( @@ -157,15 +156,15 @@ func (wsc *WSClient) Unsubscribe(eventid string) error { func (wsc *WSClient) Call(method string, params map[string]interface{}) error { // we need this step because we attempt to decode values using `go-wire` // (handlers.go:470) on the server side - encodedParams := make(map[string]interface{}) - for k, v := range params { - bytes := json.RawMessage(wire.JSONBytes(v)) - encodedParams[k] = &bytes - } + // encodedParams := make(map[string]interface{}) + // for k, v := range params { + // bytes := json.RawMessage(wire.JSONBytes(v)) + // encodedParams[k] = &bytes + // } err := wsc.WriteJSON(types.RPCRequest{ JSONRPC: "2.0", Method: method, - Params: encodedParams, + Params: params, ID: "", }) return err diff --git a/rpc/lib/rpc_test.go b/rpc/lib/rpc_test.go index f42fd274c..cd42f20a6 100644 --- a/rpc/lib/rpc_test.go +++ b/rpc/lib/rpc_test.go @@ -3,6 +3,7 @@ package rpc import ( "bytes" crand "crypto/rand" + "encoding/json" "fmt" "math/rand" "net/http" @@ -12,7 +13,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - wire "github.com/tendermint/go-wire" + data "github.com/tendermint/go-data" client "github.com/tendermint/tendermint/rpc/lib/client" server "github.com/tendermint/tendermint/rpc/lib/server" types "github.com/tendermint/tendermint/rpc/lib/types" @@ -29,7 +30,35 @@ const ( ) // Define a type for results and register concrete versions -type Result interface{} +type ResultInner interface{} + +type Result struct { + ResultInner `json:"unwrap"` +} + +func (r Result) MarshalJSON() ([]byte, error) { + return resultMapper.ToJSON(r.ResultInner) +} + +func (r *Result) UnmarshalJSON(data []byte) (err error) { + parsed, err := resultMapper.FromJSON(data) + if err == nil && parsed != nil { + r.ResultInner = parsed.(ResultInner) + } + return +} + +func (r Result) Unwrap() ResultInner { + tmrI := r.ResultInner + for wrap, ok := tmrI.(Result); ok; wrap, ok = tmrI.(Result) { + tmrI = wrap.ResultInner + } + return tmrI +} + +func (r Result) Empty() bool { + return r.ResultInner == nil +} type ResultEcho struct { Value string @@ -39,11 +68,9 @@ type ResultEchoBytes struct { Value []byte } -var _ = wire.RegisterInterface( - struct{ Result }{}, - wire.ConcreteType{&ResultEcho{}, 0x1}, - wire.ConcreteType{&ResultEchoBytes{}, 0x2}, -) +var resultMapper = data.NewMapper(Result{}). + RegisterImplementation(&ResultEcho{}, "echo", 0x1). + RegisterImplementation(&ResultEchoBytes{}, "echo_bytes", 0x2) // Define some routes var Routes = map[string]*server.RPCFunc{ @@ -53,15 +80,15 @@ var Routes = map[string]*server.RPCFunc{ } func EchoResult(v string) (Result, error) { - return &ResultEcho{v}, nil + return Result{&ResultEcho{v}}, nil } func EchoWSResult(wsCtx types.WSRPCContext, v string) (Result, error) { - return &ResultEcho{v}, nil + return Result{&ResultEcho{v}}, nil } func EchoBytesResult(v []byte) (Result, error) { - return &ResultEchoBytes{v}, nil + return Result{&ResultEchoBytes{v}}, nil } // launch unix and tcp servers @@ -109,7 +136,7 @@ func echoViaHTTP(cl client.HTTPClient, val string) (string, error) { if _, err := cl.Call("echo", params, &result); err != nil { return "", err } - return result.(*ResultEcho).Value, nil + return result.Unwrap().(*ResultEcho).Value, nil } func echoBytesViaHTTP(cl client.HTTPClient, bytes []byte) ([]byte, error) { @@ -120,7 +147,7 @@ func echoBytesViaHTTP(cl client.HTTPClient, bytes []byte) ([]byte, error) { if _, err := cl.Call("echo_bytes", params, &result); err != nil { return []byte{}, err } - return result.(*ResultEchoBytes).Value, nil + return result.Unwrap().(*ResultEchoBytes).Value, nil } func testWithHTTPClient(t *testing.T, cl client.HTTPClient) { @@ -147,11 +174,11 @@ func echoViaWS(cl *client.WSClient, val string) (string, error) { select { case msg := <-cl.ResultsCh: result := new(Result) - wire.ReadJSONPtr(result, msg, &err) + err = json.Unmarshal(msg, result) if err != nil { return "", nil } - return (*result).(*ResultEcho).Value, nil + return result.Unwrap().(*ResultEcho).Value, nil case err := <-cl.ErrorsCh: return "", err } @@ -169,11 +196,11 @@ func echoBytesViaWS(cl *client.WSClient, bytes []byte) ([]byte, error) { select { case msg := <-cl.ResultsCh: result := new(Result) - wire.ReadJSONPtr(result, msg, &err) + err = json.Unmarshal(msg, result) if err != nil { return []byte{}, nil } - return (*result).(*ResultEchoBytes).Value, nil + return result.Unwrap().(*ResultEchoBytes).Value, nil case err := <-cl.ErrorsCh: return []byte{}, err } @@ -252,9 +279,9 @@ func TestWSNewWSRPCFunc(t *testing.T) { select { case msg := <-cl.ResultsCh: result := new(Result) - wire.ReadJSONPtr(result, msg, &err) + err = json.Unmarshal(msg, result) require.Nil(t, err) - got := (*result).(*ResultEcho).Value + got := result.Unwrap().(*ResultEcho).Value assert.Equal(t, got, val) case err := <-cl.ErrorsCh: t.Fatal(err) @@ -280,9 +307,9 @@ func TestWSHandlesArrayParams(t *testing.T) { select { case msg := <-cl.ResultsCh: result := new(Result) - wire.ReadJSONPtr(result, msg, &err) + err = json.Unmarshal(msg, result) require.Nil(t, err) - got := (*result).(*ResultEcho).Value + got := result.Unwrap().(*ResultEcho).Value assert.Equal(t, got, val) case err := <-cl.ErrorsCh: t.Fatalf("%+v", err) diff --git a/rpc/lib/server/handlers.go b/rpc/lib/server/handlers.go index d7dffd402..27451c23d 100644 --- a/rpc/lib/server/handlers.go +++ b/rpc/lib/server/handlers.go @@ -280,9 +280,8 @@ func httpParamsToArgs(rpcFunc *RPCFunc, r *http.Request) ([]reflect.Value, error } func _jsonStringToArg(ty reflect.Type, arg string) (reflect.Value, error) { - var err error v := reflect.New(ty) - wire.ReadJSONPtr(v.Interface(), []byte(arg), &err) + err := json.Unmarshal([]byte(arg), v.Interface()) if err != nil { return v, err } @@ -315,9 +314,8 @@ func nonJsonToArg(ty reflect.Type, arg string) (reflect.Value, error, bool) { } if isQuotedString && expectingByteSlice { - var err error v := reflect.New(reflect.TypeOf("")) - wire.ReadJSONPtr(v.Interface(), []byte(arg), &err) + err := json.Unmarshal([]byte(arg), v.Interface()) if err != nil { return reflect.ValueOf(nil), err, false } diff --git a/rpc/lib/types/types.go b/rpc/lib/types/types.go index 9c5f2625b..28ddfc0ff 100644 --- a/rpc/lib/types/types.go +++ b/rpc/lib/types/types.go @@ -4,7 +4,6 @@ import ( "encoding/json" "strings" - wire "github.com/tendermint/go-wire" events "github.com/tendermint/tmlibs/events" ) @@ -52,8 +51,14 @@ type RPCResponse struct { func NewRPCResponse(id string, res interface{}, err string) RPCResponse { var raw *json.RawMessage if res != nil { - rawMsg := json.RawMessage(wire.JSONBytes(res)) - raw = &rawMsg + var js []byte + js, err2 := json.Marshal(res) + if err2 == nil { + rawMsg := json.RawMessage(js) + raw = &rawMsg + } else { + err = err2.Error() + } } return RPCResponse{ JSONRPC: "2.0", diff --git a/rpc/test/helpers.go b/rpc/test/helpers.go index 622890596..76d04f511 100644 --- a/rpc/test/helpers.go +++ b/rpc/test/helpers.go @@ -1,6 +1,7 @@ package rpctest import ( + "encoding/json" "fmt" "math/rand" "os" @@ -11,7 +12,6 @@ import ( "github.com/spf13/viper" "github.com/stretchr/testify/require" - wire "github.com/tendermint/go-wire" logger "github.com/tendermint/tmlibs/logger" abci "github.com/tendermint/abci/types" @@ -132,7 +132,7 @@ func waitForEvent(t *testing.T, wsc *client.WSClient, eventid string, dieOnTimeo select { case r := <-wsc.ResultsCh: result := new(ctypes.TMResult) - wire.ReadJSONPtr(result, r, &err) + err = json.Unmarshal(r, result) if err != nil { errCh <- err break LOOP From acfbea6d4965fd3e7063d54fedc3a2d48404f066 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 28 Apr 2017 14:36:38 -0400 Subject: [PATCH 227/309] rpc: decode args without wire --- rpc/lib/rpc_test.go | 64 +++++++++++++++++++++++++++++++++++--- rpc/lib/server/handlers.go | 31 ++++++++++++++++-- 2 files changed, 88 insertions(+), 7 deletions(-) diff --git a/rpc/lib/rpc_test.go b/rpc/lib/rpc_test.go index cd42f20a6..2f61f3887 100644 --- a/rpc/lib/rpc_test.go +++ b/rpc/lib/rpc_test.go @@ -13,7 +13,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - data "github.com/tendermint/go-data" + "github.com/tendermint/go-wire/data" client "github.com/tendermint/tendermint/rpc/lib/client" server "github.com/tendermint/tendermint/rpc/lib/server" types "github.com/tendermint/tendermint/rpc/lib/types" @@ -64,19 +64,31 @@ type ResultEcho struct { Value string } +type ResultEchoInt struct { + Value int +} + type ResultEchoBytes struct { Value []byte } +type ResultEchoDataBytes struct { + Value data.Bytes +} + var resultMapper = data.NewMapper(Result{}). RegisterImplementation(&ResultEcho{}, "echo", 0x1). - RegisterImplementation(&ResultEchoBytes{}, "echo_bytes", 0x2) + RegisterImplementation(&ResultEchoBytes{}, "echo_bytes", 0x2). + RegisterImplementation(&ResultEchoDataBytes{}, "echo_data_bytes", 0x3). + RegisterImplementation(&ResultEchoInt{}, "echo_int", 0x4) // Define some routes var Routes = map[string]*server.RPCFunc{ - "echo": server.NewRPCFunc(EchoResult, "arg"), - "echo_ws": server.NewWSRPCFunc(EchoWSResult, "arg"), - "echo_bytes": server.NewRPCFunc(EchoBytesResult, "arg"), + "echo": server.NewRPCFunc(EchoResult, "arg"), + "echo_ws": server.NewWSRPCFunc(EchoWSResult, "arg"), + "echo_bytes": server.NewRPCFunc(EchoBytesResult, "arg"), + "echo_data_bytes": server.NewRPCFunc(EchoDataBytesResult, "arg"), + "echo_int": server.NewRPCFunc(EchoIntResult, "arg"), } func EchoResult(v string) (Result, error) { @@ -87,10 +99,18 @@ func EchoWSResult(wsCtx types.WSRPCContext, v string) (Result, error) { return Result{&ResultEcho{v}}, nil } +func EchoIntResult(v int) (Result, error) { + return Result{&ResultEchoInt{v}}, nil +} + func EchoBytesResult(v []byte) (Result, error) { return Result{&ResultEchoBytes{v}}, nil } +func EchoDataBytesResult(v data.Bytes) (Result, error) { + return Result{&ResultEchoDataBytes{v}}, nil +} + // launch unix and tcp servers func init() { cmd := exec.Command("rm", "-f", unixSocket) @@ -139,6 +159,17 @@ func echoViaHTTP(cl client.HTTPClient, val string) (string, error) { return result.Unwrap().(*ResultEcho).Value, nil } +func echoIntViaHTTP(cl client.HTTPClient, val int) (int, error) { + params := map[string]interface{}{ + "arg": val, + } + var result Result + if _, err := cl.Call("echo_int", params, &result); err != nil { + return 0, err + } + return result.Unwrap().(*ResultEchoInt).Value, nil +} + func echoBytesViaHTTP(cl client.HTTPClient, bytes []byte) ([]byte, error) { params := map[string]interface{}{ "arg": bytes, @@ -150,6 +181,17 @@ func echoBytesViaHTTP(cl client.HTTPClient, bytes []byte) ([]byte, error) { return result.Unwrap().(*ResultEchoBytes).Value, nil } +func echoDataBytesViaHTTP(cl client.HTTPClient, bytes data.Bytes) (data.Bytes, error) { + params := map[string]interface{}{ + "arg": bytes, + } + var result Result + if _, err := cl.Call("echo_data_bytes", params, &result); err != nil { + return []byte{}, err + } + return result.Unwrap().(*ResultEchoDataBytes).Value, nil +} + func testWithHTTPClient(t *testing.T, cl client.HTTPClient) { val := "acbd" got, err := echoViaHTTP(cl, val) @@ -160,6 +202,18 @@ func testWithHTTPClient(t *testing.T, cl client.HTTPClient) { got2, err := echoBytesViaHTTP(cl, val2) require.Nil(t, err) assert.Equal(t, got2, val2) + + val3 := data.Bytes(randBytes(t)) + got3, err := echoDataBytesViaHTTP(cl, val3) + require.Nil(t, err) + assert.Equal(t, got3, val3) + + /* + val4 := rand.Intn(10000) + got4, err := echoIntViaHTTP(cl, val4) + require.Nil(t, err) + assert.Equal(t, got4, val4) + */ } func echoViaWS(cl *client.WSClient, val string) (string, error) { diff --git a/rpc/lib/server/handlers.go b/rpc/lib/server/handlers.go index 27451c23d..1c25d9e75 100644 --- a/rpc/lib/server/handlers.go +++ b/rpc/lib/server/handlers.go @@ -2,6 +2,7 @@ package rpcserver import ( "bytes" + "encoding/base64" "encoding/hex" "encoding/json" "fmt" @@ -14,7 +15,8 @@ import ( "github.com/gorilla/websocket" "github.com/pkg/errors" - wire "github.com/tendermint/go-wire" + //wire "github.com/tendermint/go-wire" + "github.com/tendermint/go-wire/data" types "github.com/tendermint/tendermint/rpc/lib/types" cmn "github.com/tendermint/tmlibs/common" events "github.com/tendermint/tmlibs/events" @@ -204,7 +206,32 @@ func jsonParamsToArgsWS(rpcFunc *RPCFunc, paramsI interface{}, wsCtx types.WSRPC func _jsonObjectToArg(ty reflect.Type, object interface{}) (reflect.Value, error) { var err error v := reflect.New(ty) - wire.ReadJSONObjectPtr(v.Interface(), object, &err) + + // if the object is a byte array, we need to decode it + if ty.Kind() == reflect.Slice && ty.Elem().Kind() == reflect.Uint8 { + s, ok := object.(string) + if !ok { + return v, fmt.Errorf("cmah") + } + + // if its data.Bytes, use hex + // else use base64 + dbty := reflect.TypeOf(data.Bytes{}) + if ty == dbty { + decoded, err := hex.DecodeString(s) + if err != nil { + return v, err + } + object = decoded + } else { + decoded, err := base64.StdEncoding.DecodeString(s) + if err != nil { + return v, err + } + object = decoded + } + } + v.Elem().Set(reflect.ValueOf(object)) if err != nil { return v, err } From 257f45b768d9fba1f7acf678c4fc1c847d017dab Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Fri, 28 Apr 2017 22:01:46 +0200 Subject: [PATCH 228/309] ebuchman: added some demos on how to parse unknown types --- rpc/lib/server/parse_test.go | 133 +++++++++++++++++++++++++++++++++++ 1 file changed, 133 insertions(+) create mode 100644 rpc/lib/server/parse_test.go diff --git a/rpc/lib/server/parse_test.go b/rpc/lib/server/parse_test.go new file mode 100644 index 000000000..5b0478b64 --- /dev/null +++ b/rpc/lib/server/parse_test.go @@ -0,0 +1,133 @@ +package rpcserver + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/tendermint/go-wire/data" +) + +func TestParseJSONMap(t *testing.T) { + assert := assert.New(t) + + input := []byte(`{"value":"1234","height":22}`) + + // naive is float,string + var p1 map[string]interface{} + err := json.Unmarshal(input, &p1) + if assert.Nil(err) { + h, ok := p1["height"].(float64) + if assert.True(ok, "%#v", p1["height"]) { + assert.EqualValues(22, h) + } + v, ok := p1["value"].(string) + if assert.True(ok, "%#v", p1["value"]) { + assert.EqualValues("1234", v) + } + } + + // preloading map with values doesn't help + tmp := 0 + p2 := map[string]interface{}{ + "value": &data.Bytes{}, + "height": &tmp, + } + err = json.Unmarshal(input, &p2) + if assert.Nil(err) { + h, ok := p2["height"].(float64) + if assert.True(ok, "%#v", p2["height"]) { + assert.EqualValues(22, h) + } + v, ok := p2["value"].(string) + if assert.True(ok, "%#v", p2["value"]) { + assert.EqualValues("1234", v) + } + } + + // preload here with *pointers* to the desired types + // struct has unknown types, but hard-coded keys + tmp = 0 + p3 := struct { + Value interface{} `json:"value"` + Height interface{} `json:"height"` + }{ + Height: &tmp, + Value: &data.Bytes{}, + } + err = json.Unmarshal(input, &p3) + if assert.Nil(err) { + h, ok := p3.Height.(*int) + if assert.True(ok, "%#v", p3.Height) { + assert.Equal(22, *h) + } + v, ok := p3.Value.(*data.Bytes) + if assert.True(ok, "%#v", p3.Value) { + assert.EqualValues([]byte{0x12, 0x34}, *v) + } + } + + // simplest solution, but hard-coded + p4 := struct { + Value data.Bytes `json:"value"` + Height int `json:"height"` + }{} + err = json.Unmarshal(input, &p4) + if assert.Nil(err) { + assert.EqualValues(22, p4.Height) + assert.EqualValues([]byte{0x12, 0x34}, p4.Value) + } + + // so, let's use this trick... + // dynamic keys on map, and we can deserialize to the desired types + var p5 map[string]*json.RawMessage + err = json.Unmarshal(input, &p5) + if assert.Nil(err) { + var h int + err = json.Unmarshal(*p5["height"], &h) + if assert.Nil(err) { + assert.Equal(22, h) + } + + var v data.Bytes + err = json.Unmarshal(*p5["value"], &v) + if assert.Nil(err) { + assert.Equal(data.Bytes{0x12, 0x34}, v) + } + } +} + +func TestParseJSONArray(t *testing.T) { + assert := assert.New(t) + + input := []byte(`["1234",22]`) + + // naive is float,string + var p1 []interface{} + err := json.Unmarshal(input, &p1) + if assert.Nil(err) { + v, ok := p1[0].(string) + if assert.True(ok, "%#v", p1[0]) { + assert.EqualValues("1234", v) + } + h, ok := p1[1].(float64) + if assert.True(ok, "%#v", p1[1]) { + assert.EqualValues(22, h) + } + } + + // preloading map with values helps here (unlike map - p2 above) + tmp := 0 + p2 := []interface{}{&data.Bytes{}, &tmp} + err = json.Unmarshal(input, &p2) + if assert.Nil(err) { + v, ok := p2[0].(*data.Bytes) + if assert.True(ok, "%#v", p2[0]) { + assert.EqualValues([]byte{0x12, 0x34}, *v) + } + h, ok := p2[1].(*int) + if assert.True(ok, "%#v", p2[1]) { + assert.EqualValues(22, *h) + } + } +} From ac28b12fa8c513cf8fda42e4ae5064a0225985c0 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 28 Apr 2017 17:55:57 -0400 Subject: [PATCH 229/309] add readReflectJSON from wire --- rpc/lib/server/handlers.go | 29 +--- rpc/lib/server/wire.go | 290 +++++++++++++++++++++++++++++++++++++ 2 files changed, 291 insertions(+), 28 deletions(-) create mode 100644 rpc/lib/server/wire.go diff --git a/rpc/lib/server/handlers.go b/rpc/lib/server/handlers.go index 1c25d9e75..51eaf1401 100644 --- a/rpc/lib/server/handlers.go +++ b/rpc/lib/server/handlers.go @@ -2,7 +2,6 @@ package rpcserver import ( "bytes" - "encoding/base64" "encoding/hex" "encoding/json" "fmt" @@ -16,7 +15,6 @@ import ( "github.com/gorilla/websocket" "github.com/pkg/errors" //wire "github.com/tendermint/go-wire" - "github.com/tendermint/go-wire/data" types "github.com/tendermint/tendermint/rpc/lib/types" cmn "github.com/tendermint/tmlibs/common" events "github.com/tendermint/tmlibs/events" @@ -206,32 +204,7 @@ func jsonParamsToArgsWS(rpcFunc *RPCFunc, paramsI interface{}, wsCtx types.WSRPC func _jsonObjectToArg(ty reflect.Type, object interface{}) (reflect.Value, error) { var err error v := reflect.New(ty) - - // if the object is a byte array, we need to decode it - if ty.Kind() == reflect.Slice && ty.Elem().Kind() == reflect.Uint8 { - s, ok := object.(string) - if !ok { - return v, fmt.Errorf("cmah") - } - - // if its data.Bytes, use hex - // else use base64 - dbty := reflect.TypeOf(data.Bytes{}) - if ty == dbty { - decoded, err := hex.DecodeString(s) - if err != nil { - return v, err - } - object = decoded - } else { - decoded, err := base64.StdEncoding.DecodeString(s) - if err != nil { - return v, err - } - object = decoded - } - } - v.Elem().Set(reflect.ValueOf(object)) + readJSONObjectPtr(v.Interface(), object, &err) if err != nil { return v, err } diff --git a/rpc/lib/server/wire.go b/rpc/lib/server/wire.go new file mode 100644 index 000000000..ad3d61f8c --- /dev/null +++ b/rpc/lib/server/wire.go @@ -0,0 +1,290 @@ +package rpcserver + +import ( + "encoding/base64" + "encoding/hex" + "reflect" + "time" + + "github.com/pkg/errors" + + "github.com/tendermint/go-wire" + "github.com/tendermint/go-wire/data" + cmn "github.com/tendermint/tmlibs/common" +) + +var ( + timeType = wire.GetTypeFromStructDeclaration(struct{ time.Time }{}) +) + +func readJSONObjectPtr(o interface{}, object interface{}, err *error) interface{} { + rv, rt := reflect.ValueOf(o), reflect.TypeOf(o) + if rv.Kind() == reflect.Ptr { + readReflectJSON(rv.Elem(), rt.Elem(), wire.Options{}, object, err) + } else { + cmn.PanicSanity("ReadJSON(Object)Ptr expects o to be a pointer") + } + return o +} + +func readByteJSON(o interface{}) (typeByte byte, rest interface{}, err error) { + oSlice, ok := o.([]interface{}) + if !ok { + err = errors.New(cmn.Fmt("Expected type [Byte,?] but got type %v", reflect.TypeOf(o))) + return + } + if len(oSlice) != 2 { + err = errors.New(cmn.Fmt("Expected [Byte,?] len 2 but got len %v", len(oSlice))) + return + } + typeByte_, ok := oSlice[0].(float64) + typeByte = byte(typeByte_) + rest = oSlice[1] + return +} + +// Contract: Caller must ensure that rt is supported +// (e.g. is recursively composed of supported native types, and structs and slices.) +// rv and rt refer to the object we're unmarhsaling into, whereas o is the result of naiive json unmarshal (map[string]interface{}) +func readReflectJSON(rv reflect.Value, rt reflect.Type, opts wire.Options, o interface{}, err *error) { + + // Get typeInfo + typeInfo := wire.GetTypeInfo(rt) + + if rt.Kind() == reflect.Interface { + if !typeInfo.IsRegisteredInterface { + // There's no way we can read such a thing. + *err = errors.New(cmn.Fmt("Cannot read unregistered interface type %v", rt)) + return + } + if o == nil { + return // nil + } + typeByte, rest, err_ := readByteJSON(o) + if err_ != nil { + *err = err_ + return + } + crt, ok := typeInfo.ByteToType[typeByte] + if !ok { + *err = errors.New(cmn.Fmt("Byte %X not registered for interface %v", typeByte, rt)) + return + } + if crt.Kind() == reflect.Ptr { + crt = crt.Elem() + crv := reflect.New(crt) + readReflectJSON(crv.Elem(), crt, opts, rest, err) + rv.Set(crv) // NOTE: orig rv is ignored. + } else { + crv := reflect.New(crt).Elem() + readReflectJSON(crv, crt, opts, rest, err) + rv.Set(crv) // NOTE: orig rv is ignored. + } + return + } + + if rt.Kind() == reflect.Ptr { + if o == nil { + return // nil + } + // Create new struct if rv is nil. + if rv.IsNil() { + newRv := reflect.New(rt.Elem()) + rv.Set(newRv) + rv = newRv + } + // Dereference pointer + rv, rt = rv.Elem(), rt.Elem() + typeInfo = wire.GetTypeInfo(rt) + // continue... + } + + switch rt.Kind() { + case reflect.Array: + elemRt := rt.Elem() + length := rt.Len() + if elemRt.Kind() == reflect.Uint8 { + // Special case: Bytearrays + oString, ok := o.(string) + if !ok { + *err = errors.New(cmn.Fmt("Expected string but got type %v", reflect.TypeOf(o))) + return + } + + // if its data.Bytes, use hex; else use base64 + dbty := reflect.TypeOf(data.Bytes{}) + var buf []byte + var err_ error + if rt == dbty { + buf, err_ = hex.DecodeString(oString) + } else { + buf, err_ = base64.StdEncoding.DecodeString(oString) + } + if err_ != nil { + *err = err_ + return + } + if len(buf) != length { + *err = errors.New(cmn.Fmt("Expected bytearray of length %v but got %v", length, len(buf))) + return + } + //log.Info("Read bytearray", "bytes", buf) + reflect.Copy(rv, reflect.ValueOf(buf)) + } else { + oSlice, ok := o.([]interface{}) + if !ok { + *err = errors.New(cmn.Fmt("Expected array of %v but got type %v", rt, reflect.TypeOf(o))) + return + } + if len(oSlice) != length { + *err = errors.New(cmn.Fmt("Expected array of length %v but got %v", length, len(oSlice))) + return + } + for i := 0; i < length; i++ { + elemRv := rv.Index(i) + readReflectJSON(elemRv, elemRt, opts, oSlice[i], err) + } + //log.Info("Read x-array", "x", elemRt, "length", length) + } + + case reflect.Slice: + elemRt := rt.Elem() + if elemRt.Kind() == reflect.Uint8 { + // Special case: Byteslices + oString, ok := o.(string) + if !ok { + *err = errors.New(cmn.Fmt("Expected string but got type %v", reflect.TypeOf(o))) + return + } + // if its data.Bytes, use hex; else use base64 + dbty := reflect.TypeOf(data.Bytes{}) + var buf []byte + var err_ error + if rt == dbty { + buf, err_ = hex.DecodeString(oString) + } else { + buf, err_ = base64.StdEncoding.DecodeString(oString) + } + if err_ != nil { + *err = err_ + return + } + //log.Info("Read byteslice", "bytes", byteslice) + rv.Set(reflect.ValueOf(buf)) + } else { + // Read length + oSlice, ok := o.([]interface{}) + if !ok { + *err = errors.New(cmn.Fmt("Expected array of %v but got type %v", rt, reflect.TypeOf(o))) + return + } + length := len(oSlice) + //log.Info("Read slice", "length", length) + sliceRv := reflect.MakeSlice(rt, length, length) + // Read elems + for i := 0; i < length; i++ { + elemRv := sliceRv.Index(i) + readReflectJSON(elemRv, elemRt, opts, oSlice[i], err) + } + rv.Set(sliceRv) + } + + case reflect.Struct: + if rt == timeType { + // Special case: time.Time + str, ok := o.(string) + if !ok { + *err = errors.New(cmn.Fmt("Expected string but got type %v", reflect.TypeOf(o))) + return + } + // try three ways, seconds, milliseconds, or microseconds... + t, err_ := time.Parse(time.RFC3339Nano, str) + if err_ != nil { + *err = err_ + return + } + rv.Set(reflect.ValueOf(t)) + } else { + if typeInfo.Unwrap { + f := typeInfo.Fields[0] + fieldIdx, fieldType, opts := f.Index, f.Type, f.Options + fieldRv := rv.Field(fieldIdx) + readReflectJSON(fieldRv, fieldType, opts, o, err) + } else { + oMap, ok := o.(map[string]interface{}) + if !ok { + *err = errors.New(cmn.Fmt("Expected map but got type %v", reflect.TypeOf(o))) + return + } + // TODO: ensure that all fields are set? + // TODO: disallow unknown oMap fields? + for _, fieldInfo := range typeInfo.Fields { + f := fieldInfo + fieldIdx, fieldType, opts := f.Index, f.Type, f.Options + value, ok := oMap[opts.JSONName] + if !ok { + continue // Skip missing fields. + } + fieldRv := rv.Field(fieldIdx) + readReflectJSON(fieldRv, fieldType, opts, value, err) + } + } + } + + case reflect.String: + str, ok := o.(string) + if !ok { + *err = errors.New(cmn.Fmt("Expected string but got type %v", reflect.TypeOf(o))) + return + } + //log.Info("Read string", "str", str) + rv.SetString(str) + + case reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8, reflect.Int: + num, ok := o.(float64) + if !ok { + *err = errors.New(cmn.Fmt("Expected numeric but got type %v", reflect.TypeOf(o))) + return + } + //log.Info("Read num", "num", num) + rv.SetInt(int64(num)) + + case reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8, reflect.Uint: + num, ok := o.(float64) + if !ok { + *err = errors.New(cmn.Fmt("Expected numeric but got type %v", reflect.TypeOf(o))) + return + } + if num < 0 { + *err = errors.New(cmn.Fmt("Expected unsigned numeric but got %v", num)) + return + } + //log.Info("Read num", "num", num) + rv.SetUint(uint64(num)) + + case reflect.Float64, reflect.Float32: + if !opts.Unsafe { + *err = errors.New("Wire float* support requires `wire:\"unsafe\"`") + return + } + num, ok := o.(float64) + if !ok { + *err = errors.New(cmn.Fmt("Expected numeric but got type %v", reflect.TypeOf(o))) + return + } + //log.Info("Read num", "num", num) + rv.SetFloat(num) + + case reflect.Bool: + bl, ok := o.(bool) + if !ok { + *err = errors.New(cmn.Fmt("Expected boolean but got type %v", reflect.TypeOf(o))) + return + } + //log.Info("Read boolean", "boolean", bl) + rv.SetBool(bl) + + default: + cmn.PanicSanity(cmn.Fmt("Unknown field type %v", rt.Kind())) + } +} From 07e59e63f90c8bee56ba1b260f940d49c1cbf463 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 28 Apr 2017 17:57:06 -0400 Subject: [PATCH 230/309] TMEventDataInner --- consensus/common_test.go | 2 +- consensus/mempool_test.go | 2 +- consensus/reactor.go | 8 ++-- consensus/reactor_test.go | 6 +-- consensus/state_test.go | 30 +++++++------- rpc/client/event_test.go | 4 +- rpc/client/helpers.go | 6 +-- rpc/core/mempool.go | 2 +- rpc/lib/rpc_test.go | 10 ++--- rpc/test/client_test.go | 7 ++-- rpc/test/helpers.go | 2 + types/events.go | 83 +++++++++++++++++++++++++++------------ 12 files changed, 98 insertions(+), 64 deletions(-) diff --git a/consensus/common_test.go b/consensus/common_test.go index 469fc9c6b..1443232a6 100644 --- a/consensus/common_test.go +++ b/consensus/common_test.go @@ -206,7 +206,7 @@ func subscribeToVoter(cs *ConsensusState, addr []byte) chan interface{} { go func() { for { v := <-voteCh0 - vote := v.(types.EventDataVote) + vote := v.(types.TMEventData).Unwrap().(types.EventDataVote) // we only fire for our own votes if bytes.Equal(addr, vote.Vote.ValidatorAddress) { voteCh <- v diff --git a/consensus/mempool_test.go b/consensus/mempool_test.go index 8808185da..15e6a1550 100644 --- a/consensus/mempool_test.go +++ b/consensus/mempool_test.go @@ -44,7 +44,7 @@ func TestTxConcurrentWithCommit(t *testing.T) { for nTxs := 0; nTxs < NTxs; { select { case b := <-newBlockCh: - nTxs += b.(types.EventDataNewBlock).Block.Header.NumTxs + nTxs += b.(types.TMEventData).Unwrap().(types.EventDataNewBlock).Block.Header.NumTxs case <-ticker.C: panic("Timed out waiting to commit blocks with transactions") } diff --git a/consensus/reactor.go b/consensus/reactor.go index 5fe45cc01..5734298ef 100644 --- a/consensus/reactor.go +++ b/consensus/reactor.go @@ -8,11 +8,11 @@ import ( "sync" "time" - . "github.com/tendermint/tmlibs/common" - "github.com/tendermint/tendermint/p2p" "github.com/tendermint/go-wire" + "github.com/tendermint/tendermint/p2p" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" + . "github.com/tendermint/tmlibs/common" ) const ( @@ -299,12 +299,12 @@ func (conR *ConsensusReactor) SetEventSwitch(evsw types.EventSwitch) { func (conR *ConsensusReactor) registerEventCallbacks() { types.AddListenerForEvent(conR.evsw, "conR", types.EventStringNewRoundStep(), func(data types.TMEventData) { - rs := data.(types.EventDataRoundState).RoundState.(*RoundState) + rs := data.Unwrap().(types.EventDataRoundState).RoundState.(*RoundState) conR.broadcastNewRoundStep(rs) }) types.AddListenerForEvent(conR.evsw, "conR", types.EventStringVote(), func(data types.TMEventData) { - edv := data.(types.EventDataVote) + edv := data.Unwrap().(types.EventDataVote) conR.broadcastHasVoteMessage(edv.Vote) }) } diff --git a/consensus/reactor_test.go b/consensus/reactor_test.go index 66827c155..fdf590151 100644 --- a/consensus/reactor_test.go +++ b/consensus/reactor_test.go @@ -8,10 +8,10 @@ import ( "github.com/tendermint/tendermint/config/tendermint_test" - "github.com/tendermint/tmlibs/events" + "github.com/tendermint/abci/example/dummy" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/types" - "github.com/tendermint/abci/example/dummy" + "github.com/tendermint/tmlibs/events" ) func init() { @@ -252,7 +252,7 @@ func TestReactorWithTimeoutCommit(t *testing.T) { func waitForAndValidateBlock(t *testing.T, n int, activeVals map[string]struct{}, eventChans []chan interface{}, css []*ConsensusState, txs ...[]byte) { timeoutWaitGroup(t, n, func(wg *sync.WaitGroup, j int) { newBlockI := <-eventChans[j] - newBlock := newBlockI.(types.EventDataNewBlock).Block + newBlock := newBlockI.(types.TMEventData).Unwrap().(types.EventDataNewBlock).Block log.Warn("Got block", "height", newBlock.Height, "validator", j) err := validateBlock(newBlock, activeVals) if err != nil { diff --git a/consensus/state_test.go b/consensus/state_test.go index d2d34e3ad..2d5ed410b 100644 --- a/consensus/state_test.go +++ b/consensus/state_test.go @@ -6,9 +6,9 @@ import ( "testing" "time" - . "github.com/tendermint/tmlibs/common" "github.com/tendermint/tendermint/config/tendermint_test" "github.com/tendermint/tendermint/types" + . "github.com/tendermint/tmlibs/common" ) func init() { @@ -248,7 +248,7 @@ func TestFullRound1(t *testing.T) { // grab proposal re := <-propCh - propBlockHash := re.(types.EventDataRoundState).RoundState.(*RoundState).ProposalBlock.Hash() + propBlockHash := re.(types.TMEventData).Unwrap().(types.EventDataRoundState).RoundState.(*RoundState).ProposalBlock.Hash() <-voteCh // wait for prevote // NOTE: voteChan cap of 0 ensures we can complete this @@ -345,7 +345,7 @@ func TestLockNoPOL(t *testing.T) { cs1.startRoutines(0) re := <-proposalCh - rs := re.(types.EventDataRoundState).RoundState.(*RoundState) + rs := re.(types.TMEventData).Unwrap().(types.EventDataRoundState).RoundState.(*RoundState) theBlockHash := rs.ProposalBlock.Hash() <-voteCh // prevote @@ -385,7 +385,7 @@ func TestLockNoPOL(t *testing.T) { // now we're on a new round and not the proposer, so wait for timeout re = <-timeoutProposeCh - rs = re.(types.EventDataRoundState).RoundState.(*RoundState) + rs = re.(types.TMEventData).Unwrap().(types.EventDataRoundState).RoundState.(*RoundState) if rs.ProposalBlock != nil { panic("Expected proposal block to be nil") @@ -429,7 +429,7 @@ func TestLockNoPOL(t *testing.T) { incrementRound(vs2) re = <-proposalCh - rs = re.(types.EventDataRoundState).RoundState.(*RoundState) + rs = re.(types.TMEventData).Unwrap().(types.EventDataRoundState).RoundState.(*RoundState) // now we're on a new round and are the proposer if !bytes.Equal(rs.ProposalBlock.Hash(), rs.LockedBlock.Hash()) { @@ -518,7 +518,7 @@ func TestLockPOLRelock(t *testing.T) { <-newRoundCh re := <-proposalCh - rs := re.(types.EventDataRoundState).RoundState.(*RoundState) + rs := re.(types.TMEventData).Unwrap().(types.EventDataRoundState).RoundState.(*RoundState) theBlockHash := rs.ProposalBlock.Hash() <-voteCh // prevote @@ -589,9 +589,9 @@ func TestLockPOLRelock(t *testing.T) { _, _ = <-voteCh, <-voteCh be := <-newBlockCh - b := be.(types.EventDataNewBlockHeader) + b := be.(types.TMEventData).Unwrap().(types.EventDataNewBlockHeader) re = <-newRoundCh - rs = re.(types.EventDataRoundState).RoundState.(*RoundState) + rs = re.(types.TMEventData).Unwrap().(types.EventDataRoundState).RoundState.(*RoundState) if rs.Height != 2 { panic("Expected height to increment") } @@ -627,7 +627,7 @@ func TestLockPOLUnlock(t *testing.T) { startTestRound(cs1, cs1.Height, 0) <-newRoundCh re := <-proposalCh - rs := re.(types.EventDataRoundState).RoundState.(*RoundState) + rs := re.(types.TMEventData).Unwrap().(types.EventDataRoundState).RoundState.(*RoundState) theBlockHash := rs.ProposalBlock.Hash() <-voteCh // prevote @@ -653,7 +653,7 @@ func TestLockPOLUnlock(t *testing.T) { // timeout to new round re = <-timeoutWaitCh - rs = re.(types.EventDataRoundState).RoundState.(*RoundState) + rs = re.(types.TMEventData).Unwrap().(types.EventDataRoundState).RoundState.(*RoundState) lockedBlockHash := rs.LockedBlock.Hash() //XXX: this isnt gauranteed to get there before the timeoutPropose ... @@ -713,7 +713,7 @@ func TestLockPOLSafety1(t *testing.T) { startTestRound(cs1, cs1.Height, 0) <-newRoundCh re := <-proposalCh - rs := re.(types.EventDataRoundState).RoundState.(*RoundState) + rs := re.(types.TMEventData).Unwrap().(types.EventDataRoundState).RoundState.(*RoundState) propBlock := rs.ProposalBlock <-voteCh // prevote @@ -761,7 +761,7 @@ func TestLockPOLSafety1(t *testing.T) { re = <-proposalCh } - rs = re.(types.EventDataRoundState).RoundState.(*RoundState) + rs = re.(types.TMEventData).Unwrap().(types.EventDataRoundState).RoundState.(*RoundState) if rs.LockedBlock != nil { panic("we should not be locked!") @@ -1009,7 +1009,7 @@ func TestHalt1(t *testing.T) { startTestRound(cs1, cs1.Height, 0) <-newRoundCh re := <-proposalCh - rs := re.(types.EventDataRoundState).RoundState.(*RoundState) + rs := re.(types.TMEventData).Unwrap().(types.EventDataRoundState).RoundState.(*RoundState) propBlock := rs.ProposalBlock propBlockParts := propBlock.MakePartSet(partSize) @@ -1032,7 +1032,7 @@ func TestHalt1(t *testing.T) { // timeout to new round <-timeoutWaitCh re = <-newRoundCh - rs = re.(types.EventDataRoundState).RoundState.(*RoundState) + rs = re.(types.TMEventData).Unwrap().(types.EventDataRoundState).RoundState.(*RoundState) log.Notice("### ONTO ROUND 1") /*Round2 @@ -1050,7 +1050,7 @@ func TestHalt1(t *testing.T) { // receiving that precommit should take us straight to commit <-newBlockCh re = <-newRoundCh - rs = re.(types.EventDataRoundState).RoundState.(*RoundState) + rs = re.(types.TMEventData).Unwrap().(types.EventDataRoundState).RoundState.(*RoundState) if rs.Height != 2 { panic("expected height to increment") diff --git a/rpc/client/event_test.go b/rpc/client/event_test.go index cc421ad90..1b99854cb 100644 --- a/rpc/client/event_test.go +++ b/rpc/client/event_test.go @@ -25,7 +25,7 @@ func TestHeaderEvents(t *testing.T) { evtTyp := types.EventStringNewBlockHeader() evt, err := client.WaitForOneEvent(c, evtTyp, 1*time.Second) require.Nil(err, "%d: %+v", i, err) - _, ok := evt.(types.EventDataNewBlockHeader) + _, ok := evt.Unwrap().(types.EventDataNewBlockHeader) require.True(ok, "%d: %#v", i, evt) // TODO: more checks... } @@ -56,7 +56,7 @@ func TestTxEvents(t *testing.T) { evt, err := client.WaitForOneEvent(c, evtTyp, 1*time.Second) require.Nil(err, "%d: %+v", i, err) // and make sure it has the proper info - txe, ok := evt.(types.EventDataTx) + txe, ok := evt.Unwrap().(types.EventDataTx) require.True(ok, "%d: %#v", i, evt) // make sure this is the proper tx require.EqualValues(tx, txe.Tx) diff --git a/rpc/client/helpers.go b/rpc/client/helpers.go index 330bcd199..bc26ea57f 100644 --- a/rpc/client/helpers.go +++ b/rpc/client/helpers.go @@ -4,9 +4,9 @@ import ( "time" "github.com/pkg/errors" + "github.com/tendermint/tendermint/types" cmn "github.com/tendermint/tmlibs/common" events "github.com/tendermint/tmlibs/events" - "github.com/tendermint/tendermint/types" ) // Waiter is informed of current height, decided whether to quit early @@ -77,12 +77,12 @@ func WaitForOneEvent(evsw types.EventSwitch, select { case <-quit: - return nil, errors.New("timed out waiting for event") + return types.TMEventData{}, errors.New("timed out waiting for event") case evt := <-evts: tmevt, ok := evt.(types.TMEventData) if ok { return tmevt, nil } - return nil, errors.Errorf("Got unexpected event type: %#v", evt) + return types.TMEventData{}, errors.Errorf("Got unexpected event type: %#v", evt) } } diff --git a/rpc/core/mempool.go b/rpc/core/mempool.go index 4c1b54cfc..a6e7093fd 100644 --- a/rpc/core/mempool.go +++ b/rpc/core/mempool.go @@ -50,7 +50,7 @@ func BroadcastTxCommit(tx types.Tx) (*ctypes.ResultBroadcastTxCommit, error) { // subscribe to tx being committed in block deliverTxResCh := make(chan types.EventDataTx, 1) types.AddListenerForEvent(eventSwitch, "rpc", types.EventStringTx(tx), func(data types.TMEventData) { - deliverTxResCh <- data.(types.EventDataTx) + deliverTxResCh <- data.Unwrap().(types.EventDataTx) }) // broadcast the tx and register checktx callback diff --git a/rpc/lib/rpc_test.go b/rpc/lib/rpc_test.go index 2f61f3887..9cbdc29a6 100644 --- a/rpc/lib/rpc_test.go +++ b/rpc/lib/rpc_test.go @@ -208,12 +208,10 @@ func testWithHTTPClient(t *testing.T, cl client.HTTPClient) { require.Nil(t, err) assert.Equal(t, got3, val3) - /* - val4 := rand.Intn(10000) - got4, err := echoIntViaHTTP(cl, val4) - require.Nil(t, err) - assert.Equal(t, got4, val4) - */ + val4 := rand.Intn(10000) + got4, err := echoIntViaHTTP(cl, val4) + require.Nil(t, err) + assert.Equal(t, got4, val4) } func echoViaWS(cl *client.WSClient, val string) (string, error) { diff --git a/rpc/test/client_test.go b/rpc/test/client_test.go index c9a922d72..8e636c333 100644 --- a/rpc/test/client_test.go +++ b/rpc/test/client_test.go @@ -12,6 +12,7 @@ import ( "github.com/stretchr/testify/require" abci "github.com/tendermint/abci/types" + "github.com/tendermint/go-wire/data" "github.com/tendermint/tendermint/rpc/core" ctypes "github.com/tendermint/tendermint/rpc/core/types" rpc "github.com/tendermint/tendermint/rpc/lib/client" @@ -116,7 +117,7 @@ func testABCIQuery(t *testing.T, client rpc.HTTPClient) { time.Sleep(time.Millisecond * 500) tmResult := new(ctypes.TMResult) _, err := client.Call("abci_query", - map[string]interface{}{"path": "", "data": k, "prove": false}, tmResult) + map[string]interface{}{"path": "", "data": data.Bytes(k), "prove": false}, tmResult) require.Nil(t, err) resQuery := tmResult.Unwrap().(*ctypes.ResultABCIQuery) @@ -286,7 +287,7 @@ func TestWSBlockchainGrowth(t *testing.T) { var initBlockN int for i := 0; i < 3; i++ { waitForEvent(t, wsc, eid, true, func() {}, func(eid string, eventData interface{}) error { - block := eventData.(types.EventDataNewBlock).Block + block := eventData.(types.TMEventData).Unwrap().(types.EventDataNewBlock).Block if i == 0 { initBlockN = block.Header.Height } else { @@ -320,7 +321,7 @@ func TestWSTxEvent(t *testing.T) { require.Nil(err) waitForEvent(t, wsc, eid, true, func() {}, func(eid string, b interface{}) error { - evt, ok := b.(types.EventDataTx) + evt, ok := b.(types.TMEventData).Unwrap().(types.EventDataTx) require.True(ok, "Got wrong event type: %#v", b) require.Equal(tx, []byte(evt.Tx), "Returned different tx") require.Equal(abci.CodeType_OK, evt.Code) diff --git a/rpc/test/helpers.go b/rpc/test/helpers.go index 76d04f511..2b01d0a69 100644 --- a/rpc/test/helpers.go +++ b/rpc/test/helpers.go @@ -131,9 +131,11 @@ func waitForEvent(t *testing.T, wsc *client.WSClient, eventid string, dieOnTimeo for { select { case r := <-wsc.ResultsCh: + fmt.Println("GOT IT", string(r)) result := new(ctypes.TMResult) err = json.Unmarshal(r, result) if err != nil { + fmt.Println("POOP", err) errCh <- err break LOOP } diff --git a/types/events.go b/types/events.go index 953859d0d..8c29c4445 100644 --- a/types/events.go +++ b/types/events.go @@ -3,7 +3,6 @@ package types import ( // for registering TMEventData as events.EventData abci "github.com/tendermint/abci/types" - "github.com/tendermint/go-wire" "github.com/tendermint/go-wire/data" cmn "github.com/tendermint/tmlibs/common" "github.com/tendermint/tmlibs/events" @@ -34,10 +33,47 @@ func EventStringVote() string { return "Vote" } //---------------------------------------- +var ( + EventDataNameNewBlock = "new_block" + EventDataNameNewBlockHeader = "new_block_header" + EventDataNameTx = "tx" + EventDataNameRoundState = "round_state" + EventDataNameVote = "vote" +) + +//---------------------------------------- + // implements events.EventData -type TMEventData interface { +type TMEventDataInner interface { events.EventData - AssertIsTMEventData() +} + +type TMEventData struct { + TMEventDataInner `json:"unwrap"` +} + +func (tmr TMEventData) MarshalJSON() ([]byte, error) { + return tmEventDataMapper.ToJSON(tmr.TMEventDataInner) +} + +func (tmr *TMEventData) UnmarshalJSON(data []byte) (err error) { + parsed, err := tmEventDataMapper.FromJSON(data) + if err == nil && parsed != nil { + tmr.TMEventDataInner = parsed.(TMEventDataInner) + } + return +} + +func (tmr TMEventData) Unwrap() TMEventDataInner { + tmrI := tmr.TMEventDataInner + for wrap, ok := tmrI.(TMEventData); ok; wrap, ok = tmrI.(TMEventData) { + tmrI = wrap.TMEventDataInner + } + return tmrI +} + +func (tmr TMEventData) Empty() bool { + return tmr.TMEventDataInner == nil } const ( @@ -50,15 +86,12 @@ const ( EventDataTypeVote = byte(0x12) ) -var _ = wire.RegisterInterface( - struct{ TMEventData }{}, - wire.ConcreteType{EventDataNewBlock{}, EventDataTypeNewBlock}, - wire.ConcreteType{EventDataNewBlockHeader{}, EventDataTypeNewBlockHeader}, - // wire.ConcreteType{EventDataFork{}, EventDataTypeFork }, - wire.ConcreteType{EventDataTx{}, EventDataTypeTx}, - wire.ConcreteType{EventDataRoundState{}, EventDataTypeRoundState}, - wire.ConcreteType{EventDataVote{}, EventDataTypeVote}, -) +var tmEventDataMapper = data.NewMapper(TMEventData{}). + RegisterImplementation(EventDataNewBlock{}, EventDataNameNewBlock, EventDataTypeNewBlock). + RegisterImplementation(EventDataNewBlockHeader{}, EventDataNameNewBlockHeader, EventDataTypeNewBlockHeader). + RegisterImplementation(EventDataTx{}, EventDataNameTx, EventDataTypeTx). + RegisterImplementation(EventDataRoundState{}, EventDataNameRoundState, EventDataTypeRoundState). + RegisterImplementation(EventDataVote{}, EventDataNameVote, EventDataTypeVote) // Most event messages are basic types (a block, a transaction) // but some (an input to a call tx or a receive) are more exotic @@ -147,55 +180,55 @@ func AddListenerForEvent(evsw EventSwitch, id, event string, cb func(data TMEven //--- block, tx, and vote events func FireEventNewBlock(fireable events.Fireable, block EventDataNewBlock) { - fireEvent(fireable, EventStringNewBlock(), block) + fireEvent(fireable, EventStringNewBlock(), TMEventData{block}) } func FireEventNewBlockHeader(fireable events.Fireable, header EventDataNewBlockHeader) { - fireEvent(fireable, EventStringNewBlockHeader(), header) + fireEvent(fireable, EventStringNewBlockHeader(), TMEventData{header}) } func FireEventVote(fireable events.Fireable, vote EventDataVote) { - fireEvent(fireable, EventStringVote(), vote) + fireEvent(fireable, EventStringVote(), TMEventData{vote}) } func FireEventTx(fireable events.Fireable, tx EventDataTx) { - fireEvent(fireable, EventStringTx(tx.Tx), tx) + fireEvent(fireable, EventStringTx(tx.Tx), TMEventData{tx}) } //--- EventDataRoundState events func FireEventNewRoundStep(fireable events.Fireable, rs EventDataRoundState) { - fireEvent(fireable, EventStringNewRoundStep(), rs) + fireEvent(fireable, EventStringNewRoundStep(), TMEventData{rs}) } func FireEventTimeoutPropose(fireable events.Fireable, rs EventDataRoundState) { - fireEvent(fireable, EventStringTimeoutPropose(), rs) + fireEvent(fireable, EventStringTimeoutPropose(), TMEventData{rs}) } func FireEventTimeoutWait(fireable events.Fireable, rs EventDataRoundState) { - fireEvent(fireable, EventStringTimeoutWait(), rs) + fireEvent(fireable, EventStringTimeoutWait(), TMEventData{rs}) } func FireEventNewRound(fireable events.Fireable, rs EventDataRoundState) { - fireEvent(fireable, EventStringNewRound(), rs) + fireEvent(fireable, EventStringNewRound(), TMEventData{rs}) } func FireEventCompleteProposal(fireable events.Fireable, rs EventDataRoundState) { - fireEvent(fireable, EventStringCompleteProposal(), rs) + fireEvent(fireable, EventStringCompleteProposal(), TMEventData{rs}) } func FireEventPolka(fireable events.Fireable, rs EventDataRoundState) { - fireEvent(fireable, EventStringPolka(), rs) + fireEvent(fireable, EventStringPolka(), TMEventData{rs}) } func FireEventUnlock(fireable events.Fireable, rs EventDataRoundState) { - fireEvent(fireable, EventStringUnlock(), rs) + fireEvent(fireable, EventStringUnlock(), TMEventData{rs}) } func FireEventRelock(fireable events.Fireable, rs EventDataRoundState) { - fireEvent(fireable, EventStringRelock(), rs) + fireEvent(fireable, EventStringRelock(), TMEventData{rs}) } func FireEventLock(fireable events.Fireable, rs EventDataRoundState) { - fireEvent(fireable, EventStringLock(), rs) + fireEvent(fireable, EventStringLock(), TMEventData{rs}) } From 884060eb9bbbf36ec7a8d3d2235b0f7aa5b3ed81 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 28 Apr 2017 22:04:14 -0400 Subject: [PATCH 231/309] rpc/lib: no Result wrapper --- rpc/lib/rpc_test.go | 112 ++++++++++++++------------------------------ 1 file changed, 35 insertions(+), 77 deletions(-) diff --git a/rpc/lib/rpc_test.go b/rpc/lib/rpc_test.go index 9cbdc29a6..a14551f4f 100644 --- a/rpc/lib/rpc_test.go +++ b/rpc/lib/rpc_test.go @@ -29,59 +29,22 @@ const ( websocketEndpoint = "/websocket/endpoint" ) -// Define a type for results and register concrete versions -type ResultInner interface{} - -type Result struct { - ResultInner `json:"unwrap"` -} - -func (r Result) MarshalJSON() ([]byte, error) { - return resultMapper.ToJSON(r.ResultInner) -} - -func (r *Result) UnmarshalJSON(data []byte) (err error) { - parsed, err := resultMapper.FromJSON(data) - if err == nil && parsed != nil { - r.ResultInner = parsed.(ResultInner) - } - return -} - -func (r Result) Unwrap() ResultInner { - tmrI := r.ResultInner - for wrap, ok := tmrI.(Result); ok; wrap, ok = tmrI.(Result) { - tmrI = wrap.ResultInner - } - return tmrI -} - -func (r Result) Empty() bool { - return r.ResultInner == nil -} - type ResultEcho struct { - Value string + Value string `json:"value"` } type ResultEchoInt struct { - Value int + Value int `json:"value"` } type ResultEchoBytes struct { - Value []byte + Value []byte `json:"value"` } type ResultEchoDataBytes struct { - Value data.Bytes + Value data.Bytes `json:"value"` } -var resultMapper = data.NewMapper(Result{}). - RegisterImplementation(&ResultEcho{}, "echo", 0x1). - RegisterImplementation(&ResultEchoBytes{}, "echo_bytes", 0x2). - RegisterImplementation(&ResultEchoDataBytes{}, "echo_data_bytes", 0x3). - RegisterImplementation(&ResultEchoInt{}, "echo_int", 0x4) - // Define some routes var Routes = map[string]*server.RPCFunc{ "echo": server.NewRPCFunc(EchoResult, "arg"), @@ -91,24 +54,24 @@ var Routes = map[string]*server.RPCFunc{ "echo_int": server.NewRPCFunc(EchoIntResult, "arg"), } -func EchoResult(v string) (Result, error) { - return Result{&ResultEcho{v}}, nil +func EchoResult(v string) (*ResultEcho, error) { + return &ResultEcho{v}, nil } -func EchoWSResult(wsCtx types.WSRPCContext, v string) (Result, error) { - return Result{&ResultEcho{v}}, nil +func EchoWSResult(wsCtx types.WSRPCContext, v string) (*ResultEcho, error) { + return &ResultEcho{v}, nil } -func EchoIntResult(v int) (Result, error) { - return Result{&ResultEchoInt{v}}, nil +func EchoIntResult(v int) (*ResultEchoInt, error) { + return &ResultEchoInt{v}, nil } -func EchoBytesResult(v []byte) (Result, error) { - return Result{&ResultEchoBytes{v}}, nil +func EchoBytesResult(v []byte) (*ResultEchoBytes, error) { + return &ResultEchoBytes{v}, nil } -func EchoDataBytesResult(v data.Bytes) (Result, error) { - return Result{&ResultEchoDataBytes{v}}, nil +func EchoDataBytesResult(v data.Bytes) (*ResultEchoDataBytes, error) { + return &ResultEchoDataBytes{v}, nil } // launch unix and tcp servers @@ -152,44 +115,44 @@ func echoViaHTTP(cl client.HTTPClient, val string) (string, error) { params := map[string]interface{}{ "arg": val, } - var result Result - if _, err := cl.Call("echo", params, &result); err != nil { + result := new(ResultEcho) + if _, err := cl.Call("echo", params, result); err != nil { return "", err } - return result.Unwrap().(*ResultEcho).Value, nil + return result.Value, nil } func echoIntViaHTTP(cl client.HTTPClient, val int) (int, error) { params := map[string]interface{}{ "arg": val, } - var result Result - if _, err := cl.Call("echo_int", params, &result); err != nil { + result := new(ResultEchoInt) + if _, err := cl.Call("echo_int", params, result); err != nil { return 0, err } - return result.Unwrap().(*ResultEchoInt).Value, nil + return result.Value, nil } func echoBytesViaHTTP(cl client.HTTPClient, bytes []byte) ([]byte, error) { params := map[string]interface{}{ "arg": bytes, } - var result Result - if _, err := cl.Call("echo_bytes", params, &result); err != nil { + result := new(ResultEchoBytes) + if _, err := cl.Call("echo_bytes", params, result); err != nil { return []byte{}, err } - return result.Unwrap().(*ResultEchoBytes).Value, nil + return result.Value, nil } func echoDataBytesViaHTTP(cl client.HTTPClient, bytes data.Bytes) (data.Bytes, error) { params := map[string]interface{}{ "arg": bytes, } - var result Result - if _, err := cl.Call("echo_data_bytes", params, &result); err != nil { + result := new(ResultEchoDataBytes) + if _, err := cl.Call("echo_data_bytes", params, result); err != nil { return []byte{}, err } - return result.Unwrap().(*ResultEchoDataBytes).Value, nil + return result.Value, nil } func testWithHTTPClient(t *testing.T, cl client.HTTPClient) { @@ -225,12 +188,12 @@ func echoViaWS(cl *client.WSClient, val string) (string, error) { select { case msg := <-cl.ResultsCh: - result := new(Result) + result := new(ResultEcho) err = json.Unmarshal(msg, result) if err != nil { return "", nil } - return result.Unwrap().(*ResultEcho).Value, nil + return result.Value, nil case err := <-cl.ErrorsCh: return "", err } @@ -247,12 +210,12 @@ func echoBytesViaWS(cl *client.WSClient, bytes []byte) ([]byte, error) { select { case msg := <-cl.ResultsCh: - result := new(Result) + result := new(ResultEchoBytes) err = json.Unmarshal(msg, result) if err != nil { return []byte{}, nil } - return result.Unwrap().(*ResultEchoBytes).Value, nil + return result.Value, nil case err := <-cl.ErrorsCh: return []byte{}, err } @@ -320,20 +283,15 @@ func TestWSNewWSRPCFunc(t *testing.T) { params := map[string]interface{}{ "arg": val, } - err = cl.WriteJSON(types.RPCRequest{ - JSONRPC: "2.0", - ID: "", - Method: "echo_ws", - Params: params, - }) + err = cl.Call("echo_ws", params) require.Nil(t, err) select { case msg := <-cl.ResultsCh: - result := new(Result) + result := new(ResultEcho) err = json.Unmarshal(msg, result) require.Nil(t, err) - got := result.Unwrap().(*ResultEcho).Value + got := result.Value assert.Equal(t, got, val) case err := <-cl.ErrorsCh: t.Fatal(err) @@ -358,10 +316,10 @@ func TestWSHandlesArrayParams(t *testing.T) { select { case msg := <-cl.ResultsCh: - result := new(Result) + result := new(ResultEcho) err = json.Unmarshal(msg, result) require.Nil(t, err) - got := result.Unwrap().(*ResultEcho).Value + got := result.Value assert.Equal(t, got, val) case err := <-cl.ErrorsCh: t.Fatalf("%+v", err) From 4e781961e9b35e5de91bb7d7067afb1e3ebacaa9 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 28 Apr 2017 22:26:17 -0400 Subject: [PATCH 232/309] remove TMResult. ::drinks champagne:: --- rpc/client/httpclient.go | 88 +++++++++--------- rpc/core/events.go | 4 +- rpc/core/routes.go | 173 +++++------------------------------- rpc/core/tx.go | 3 + rpc/core/types/responses.go | 59 +----------- rpc/test/client_test.go | 79 ++++++++-------- rpc/test/helpers.go | 11 ++- 7 files changed, 112 insertions(+), 305 deletions(-) diff --git a/rpc/client/httpclient.go b/rpc/client/httpclient.go index 662ced895..cb7149406 100644 --- a/rpc/client/httpclient.go +++ b/rpc/client/httpclient.go @@ -50,42 +50,41 @@ func (c *HTTP) _assertIsEventSwitch() types.EventSwitch { } func (c *HTTP) Status() (*ctypes.ResultStatus, error) { - tmResult := new(ctypes.TMResult) - _, err := c.rpc.Call("status", map[string]interface{}{}, tmResult) + result := new(ctypes.ResultStatus) + _, err := c.rpc.Call("status", map[string]interface{}{}, result) if err != nil { return nil, errors.Wrap(err, "Status") } - // note: panics if rpc doesn't match. okay??? - return tmResult.Unwrap().(*ctypes.ResultStatus), nil + return result, nil } func (c *HTTP) ABCIInfo() (*ctypes.ResultABCIInfo, error) { - tmResult := new(ctypes.TMResult) - _, err := c.rpc.Call("abci_info", map[string]interface{}{}, tmResult) + result := new(ctypes.ResultABCIInfo) + _, err := c.rpc.Call("abci_info", map[string]interface{}{}, result) if err != nil { return nil, errors.Wrap(err, "ABCIInfo") } - return tmResult.Unwrap().(*ctypes.ResultABCIInfo), nil + return result, nil } func (c *HTTP) ABCIQuery(path string, data data.Bytes, prove bool) (*ctypes.ResultABCIQuery, error) { - tmResult := new(ctypes.TMResult) + result := new(ctypes.ResultABCIQuery) _, err := c.rpc.Call("abci_query", map[string]interface{}{"path": path, "data": data, "prove": prove}, - tmResult) + result) if err != nil { return nil, errors.Wrap(err, "ABCIQuery") } - return tmResult.Unwrap().(*ctypes.ResultABCIQuery), nil + return result, nil } func (c *HTTP) BroadcastTxCommit(tx types.Tx) (*ctypes.ResultBroadcastTxCommit, error) { - tmResult := new(ctypes.TMResult) - _, err := c.rpc.Call("broadcast_tx_commit", map[string]interface{}{"tx": tx}, tmResult) + result := new(ctypes.ResultBroadcastTxCommit) + _, err := c.rpc.Call("broadcast_tx_commit", map[string]interface{}{"tx": tx}, result) if err != nil { return nil, errors.Wrap(err, "broadcast_tx_commit") } - return tmResult.Unwrap().(*ctypes.ResultBroadcastTxCommit), nil + return result, nil } func (c *HTTP) BroadcastTxAsync(tx types.Tx) (*ctypes.ResultBroadcastTx, error) { @@ -97,90 +96,90 @@ func (c *HTTP) BroadcastTxSync(tx types.Tx) (*ctypes.ResultBroadcastTx, error) { } func (c *HTTP) broadcastTX(route string, tx types.Tx) (*ctypes.ResultBroadcastTx, error) { - tmResult := new(ctypes.TMResult) - _, err := c.rpc.Call(route, map[string]interface{}{"tx": tx}, tmResult) + result := new(ctypes.ResultBroadcastTx) + _, err := c.rpc.Call(route, map[string]interface{}{"tx": tx}, result) if err != nil { return nil, errors.Wrap(err, route) } - return tmResult.Unwrap().(*ctypes.ResultBroadcastTx), nil + return result, nil } func (c *HTTP) NetInfo() (*ctypes.ResultNetInfo, error) { - tmResult := new(ctypes.TMResult) - _, err := c.rpc.Call("net_info", map[string]interface{}{}, tmResult) + result := new(ctypes.ResultNetInfo) + _, err := c.rpc.Call("net_info", map[string]interface{}{}, result) if err != nil { return nil, errors.Wrap(err, "NetInfo") } - return tmResult.Unwrap().(*ctypes.ResultNetInfo), nil + return result, nil } func (c *HTTP) DumpConsensusState() (*ctypes.ResultDumpConsensusState, error) { - tmResult := new(ctypes.TMResult) - _, err := c.rpc.Call("dump_consensus_state", map[string]interface{}{}, tmResult) + result := new(ctypes.ResultDumpConsensusState) + _, err := c.rpc.Call("dump_consensus_state", map[string]interface{}{}, result) if err != nil { return nil, errors.Wrap(err, "DumpConsensusState") } - return tmResult.Unwrap().(*ctypes.ResultDumpConsensusState), nil + return result, nil } func (c *HTTP) BlockchainInfo(minHeight, maxHeight int) (*ctypes.ResultBlockchainInfo, error) { - tmResult := new(ctypes.TMResult) + result := new(ctypes.ResultBlockchainInfo) _, err := c.rpc.Call("blockchain", map[string]interface{}{"minHeight": minHeight, "maxHeight": maxHeight}, - tmResult) + result) if err != nil { return nil, errors.Wrap(err, "BlockchainInfo") } - return tmResult.Unwrap().(*ctypes.ResultBlockchainInfo), nil + return result, nil } func (c *HTTP) Genesis() (*ctypes.ResultGenesis, error) { - tmResult := new(ctypes.TMResult) - _, err := c.rpc.Call("genesis", map[string]interface{}{}, tmResult) + result := new(ctypes.ResultGenesis) + _, err := c.rpc.Call("genesis", map[string]interface{}{}, result) if err != nil { return nil, errors.Wrap(err, "Genesis") } - return tmResult.Unwrap().(*ctypes.ResultGenesis), nil + return result, nil } func (c *HTTP) Block(height int) (*ctypes.ResultBlock, error) { - tmResult := new(ctypes.TMResult) - _, err := c.rpc.Call("block", map[string]interface{}{"height": height}, tmResult) + result := new(ctypes.ResultBlock) + _, err := c.rpc.Call("block", map[string]interface{}{"height": height}, result) if err != nil { return nil, errors.Wrap(err, "Block") } - return tmResult.Unwrap().(*ctypes.ResultBlock), nil + return result, nil } func (c *HTTP) Commit(height int) (*ctypes.ResultCommit, error) { - tmResult := new(ctypes.TMResult) - _, err := c.rpc.Call("commit", map[string]interface{}{"height": height}, tmResult) + result := new(ctypes.ResultCommit) + _, err := c.rpc.Call("commit", map[string]interface{}{"height": height}, result) if err != nil { return nil, errors.Wrap(err, "Commit") } - return tmResult.Unwrap().(*ctypes.ResultCommit), nil + return result, nil } func (c *HTTP) Tx(hash []byte, prove bool) (*ctypes.ResultTx, error) { - tmResult := new(ctypes.TMResult) + result := new(ctypes.ResultTx) query := map[string]interface{}{ "hash": hash, "prove": prove, } - _, err := c.rpc.Call("tx", query, tmResult) + _, err := c.rpc.Call("tx", query, result) if err != nil { return nil, errors.Wrap(err, "Tx") } - return tmResult.Unwrap().(*ctypes.ResultTx), nil + return result, nil } func (c *HTTP) Validators() (*ctypes.ResultValidators, error) { - tmResult := new(ctypes.TMResult) - _, err := c.rpc.Call("validators", map[string]interface{}{}, tmResult) + result := new(ctypes.ResultValidators) + _, err := c.rpc.Call("validators", map[string]interface{}{}, result) if err != nil { return nil, errors.Wrap(err, "Validators") } - return tmResult.Unwrap().(*ctypes.ResultValidators), nil + return result, nil } /** websocket event stuff here... **/ @@ -335,18 +334,15 @@ func (w *WSEvents) eventListener() { // some implementation of types.TMEventData, and sends it off // on the merry way to the EventSwitch func (w *WSEvents) parseEvent(data []byte) (err error) { - result := new(ctypes.TMResult) + result := new(ctypes.ResultEvent) err = json.Unmarshal(data, result) if err != nil { - return err - } - event, ok := result.Unwrap().(*ctypes.ResultEvent) - if !ok { // ignore silently (eg. subscribe, unsubscribe and maybe other events) + // TODO: ? return nil } // looks good! let's fire this baby! - w.EventSwitch.FireEvent(event.Name, event.Data) + w.EventSwitch.FireEvent(result.Name, result.Data) return nil } diff --git a/rpc/core/events.go b/rpc/core/events.go index 271ba5301..fa40c5a81 100644 --- a/rpc/core/events.go +++ b/rpc/core/events.go @@ -11,8 +11,8 @@ func Subscribe(wsCtx rpctypes.WSRPCContext, event string) (*ctypes.ResultSubscri types.AddListenerForEvent(wsCtx.GetEventSwitch(), wsCtx.GetRemoteAddr(), event, func(msg types.TMEventData) { // NOTE: EventSwitch callbacks must be nonblocking // NOTE: RPCResponses of subscribed events have id suffix "#event" - tmResult := ctypes.TMResult{&ctypes.ResultEvent{event, msg}} - wsCtx.TryWriteRPCResponse(rpctypes.NewRPCResponse(wsCtx.Request.ID+"#event", &tmResult, "")) + tmResult := &ctypes.ResultEvent{event, msg} + wsCtx.TryWriteRPCResponse(rpctypes.NewRPCResponse(wsCtx.Request.ID+"#event", tmResult, "")) }) return &ctypes.ResultSubscribe{}, nil } diff --git a/rpc/core/routes.go b/rpc/core/routes.go index 9e4c03be1..b662ae48c 100644 --- a/rpc/core/routes.go +++ b/rpc/core/routes.go @@ -1,173 +1,46 @@ package core import ( - data "github.com/tendermint/go-wire/data" - ctypes "github.com/tendermint/tendermint/rpc/core/types" rpc "github.com/tendermint/tendermint/rpc/lib/server" - "github.com/tendermint/tendermint/rpc/lib/types" - "github.com/tendermint/tendermint/types" ) // TODO: better system than "unsafe" prefix var Routes = map[string]*rpc.RPCFunc{ // subscribe/unsubscribe are reserved for websocket events. - "subscribe": rpc.NewWSRPCFunc(SubscribeResult, "event"), - "unsubscribe": rpc.NewWSRPCFunc(UnsubscribeResult, "event"), + "subscribe": rpc.NewWSRPCFunc(Subscribe, "event"), + "unsubscribe": rpc.NewWSRPCFunc(Unsubscribe, "event"), // info API - "status": rpc.NewRPCFunc(StatusResult, ""), - "net_info": rpc.NewRPCFunc(NetInfoResult, ""), - "blockchain": rpc.NewRPCFunc(BlockchainInfoResult, "minHeight,maxHeight"), - "genesis": rpc.NewRPCFunc(GenesisResult, ""), - "block": rpc.NewRPCFunc(BlockResult, "height"), - "commit": rpc.NewRPCFunc(CommitResult, "height"), - "tx": rpc.NewRPCFunc(TxResult, "hash,prove"), - "validators": rpc.NewRPCFunc(ValidatorsResult, ""), - "dump_consensus_state": rpc.NewRPCFunc(DumpConsensusStateResult, ""), - "unconfirmed_txs": rpc.NewRPCFunc(UnconfirmedTxsResult, ""), - "num_unconfirmed_txs": rpc.NewRPCFunc(NumUnconfirmedTxsResult, ""), + "status": rpc.NewRPCFunc(Status, ""), + "net_info": rpc.NewRPCFunc(NetInfo, ""), + "blockchain": rpc.NewRPCFunc(BlockchainInfo, "minHeight,maxHeight"), + "genesis": rpc.NewRPCFunc(Genesis, ""), + "block": rpc.NewRPCFunc(Block, "height"), + "commit": rpc.NewRPCFunc(Commit, "height"), + "tx": rpc.NewRPCFunc(Tx, "hash,prove"), + "validators": rpc.NewRPCFunc(Validators, ""), + "dump_consensus_state": rpc.NewRPCFunc(DumpConsensusState, ""), + "unconfirmed_txs": rpc.NewRPCFunc(UnconfirmedTxs, ""), + "num_unconfirmed_txs": rpc.NewRPCFunc(NumUnconfirmedTxs, ""), // broadcast API - "broadcast_tx_commit": rpc.NewRPCFunc(BroadcastTxCommitResult, "tx"), - "broadcast_tx_sync": rpc.NewRPCFunc(BroadcastTxSyncResult, "tx"), - "broadcast_tx_async": rpc.NewRPCFunc(BroadcastTxAsyncResult, "tx"), + "broadcast_tx_commit": rpc.NewRPCFunc(BroadcastTxCommit, "tx"), + "broadcast_tx_sync": rpc.NewRPCFunc(BroadcastTxSync, "tx"), + "broadcast_tx_async": rpc.NewRPCFunc(BroadcastTxAsync, "tx"), // abci API - "abci_query": rpc.NewRPCFunc(ABCIQueryResult, "path,data,prove"), - "abci_info": rpc.NewRPCFunc(ABCIInfoResult, ""), + "abci_query": rpc.NewRPCFunc(ABCIQuery, "path,data,prove"), + "abci_info": rpc.NewRPCFunc(ABCIInfo, ""), // control API - "dial_seeds": rpc.NewRPCFunc(UnsafeDialSeedsResult, "seeds"), + "dial_seeds": rpc.NewRPCFunc(UnsafeDialSeeds, "seeds"), "unsafe_flush_mempool": rpc.NewRPCFunc(UnsafeFlushMempool, ""), // config is not in general thread safe. expose specifics if you need em - // "unsafe_set_config": rpc.NewRPCFunc(UnsafeSetConfigResult, "type,key,value"), + // "unsafe_set_config": rpc.NewRPCFunc(UnsafeSetConfig, "type,key,value"), // profiler API - "unsafe_start_cpu_profiler": rpc.NewRPCFunc(UnsafeStartCPUProfilerResult, "filename"), - "unsafe_stop_cpu_profiler": rpc.NewRPCFunc(UnsafeStopCPUProfilerResult, ""), - "unsafe_write_heap_profile": rpc.NewRPCFunc(UnsafeWriteHeapProfileResult, "filename"), -} - -func SubscribeResult(wsCtx rpctypes.WSRPCContext, event string) (ctypes.TMResult, error) { - res, err := Subscribe(wsCtx, event) - return ctypes.TMResult{res}, err -} - -func UnsubscribeResult(wsCtx rpctypes.WSRPCContext, event string) (ctypes.TMResult, error) { - res, err := Unsubscribe(wsCtx, event) - return ctypes.TMResult{res}, err -} - -func StatusResult() (ctypes.TMResult, error) { - res, err := Status() - return ctypes.TMResult{res}, err -} - -func NetInfoResult() (ctypes.TMResult, error) { - res, err := NetInfo() - return ctypes.TMResult{res}, err -} - -func UnsafeDialSeedsResult(seeds []string) (ctypes.TMResult, error) { - res, err := UnsafeDialSeeds(seeds) - return ctypes.TMResult{res}, err -} - -func BlockchainInfoResult(min, max int) (ctypes.TMResult, error) { - res, err := BlockchainInfo(min, max) - return ctypes.TMResult{res}, err -} - -func GenesisResult() (ctypes.TMResult, error) { - res, err := Genesis() - return ctypes.TMResult{res}, err -} - -func BlockResult(height int) (ctypes.TMResult, error) { - res, err := Block(height) - return ctypes.TMResult{res}, err -} - -func CommitResult(height int) (ctypes.TMResult, error) { - res, err := Commit(height) - return ctypes.TMResult{res}, err -} - -func ValidatorsResult() (ctypes.TMResult, error) { - res, err := Validators() - return ctypes.TMResult{res}, err -} - -func DumpConsensusStateResult() (ctypes.TMResult, error) { - res, err := DumpConsensusState() - return ctypes.TMResult{res}, err -} - -func UnconfirmedTxsResult() (ctypes.TMResult, error) { - res, err := UnconfirmedTxs() - return ctypes.TMResult{res}, err -} - -func NumUnconfirmedTxsResult() (ctypes.TMResult, error) { - res, err := NumUnconfirmedTxs() - return ctypes.TMResult{res}, err -} - -// Tx allow user to query the transaction results. `nil` could mean the -// transaction is in the mempool, invalidated, or was not send in the first -// place. -func TxResult(hash []byte, prove bool) (ctypes.TMResult, error) { - res, err := Tx(hash, prove) - return ctypes.TMResult{res}, err -} - -func BroadcastTxCommitResult(tx types.Tx) (ctypes.TMResult, error) { - res, err := BroadcastTxCommit(tx) - return ctypes.TMResult{res}, err -} - -func BroadcastTxSyncResult(tx types.Tx) (ctypes.TMResult, error) { - res, err := BroadcastTxSync(tx) - return ctypes.TMResult{res}, err -} - -func BroadcastTxAsyncResult(tx types.Tx) (ctypes.TMResult, error) { - res, err := BroadcastTxAsync(tx) - return ctypes.TMResult{res}, err -} - -func ABCIQueryResult(path string, data data.Bytes, prove bool) (ctypes.TMResult, error) { - res, err := ABCIQuery(path, data, prove) - return ctypes.TMResult{res}, err -} - -func ABCIInfoResult() (ctypes.TMResult, error) { - res, err := ABCIInfo() - return ctypes.TMResult{res}, err -} - -func UnsafeFlushMempoolResult() (ctypes.TMResult, error) { - res, err := UnsafeFlushMempool() - return ctypes.TMResult{res}, err -} - -func UnsafeSetConfigResult(typ, key, value string) (ctypes.TMResult, error) { - res, err := UnsafeSetConfig(typ, key, value) - return ctypes.TMResult{res}, err -} - -func UnsafeStartCPUProfilerResult(filename string) (ctypes.TMResult, error) { - res, err := UnsafeStartCPUProfiler(filename) - return ctypes.TMResult{res}, err -} - -func UnsafeStopCPUProfilerResult() (ctypes.TMResult, error) { - res, err := UnsafeStopCPUProfiler() - return ctypes.TMResult{res}, err -} - -func UnsafeWriteHeapProfileResult(filename string) (ctypes.TMResult, error) { - res, err := UnsafeWriteHeapProfile(filename) - return ctypes.TMResult{res}, err + "unsafe_start_cpu_profiler": rpc.NewRPCFunc(UnsafeStartCPUProfiler, "filename"), + "unsafe_stop_cpu_profiler": rpc.NewRPCFunc(UnsafeStopCPUProfiler, ""), + "unsafe_write_heap_profile": rpc.NewRPCFunc(UnsafeWriteHeapProfile, "filename"), } diff --git a/rpc/core/tx.go b/rpc/core/tx.go index 387d4afa6..5bd6e1806 100644 --- a/rpc/core/tx.go +++ b/rpc/core/tx.go @@ -8,6 +8,9 @@ import ( "github.com/tendermint/tendermint/types" ) +// Tx allow user to query the transaction results. `nil` could mean the +// transaction is in the mempool, invalidated, or was not send in the first +// place. func Tx(hash []byte, prove bool) (*ctypes.ResultTx, error) { // if index is disabled, return error diff --git a/rpc/core/types/responses.go b/rpc/core/types/responses.go index 9b4e9d579..23d68587b 100644 --- a/rpc/core/types/responses.go +++ b/rpc/core/types/responses.go @@ -7,7 +7,7 @@ import ( "github.com/tendermint/go-crypto" "github.com/tendermint/go-wire/data" "github.com/tendermint/tendermint/p2p" - "github.com/tendermint/tendermint/rpc/lib/types" + // "github.com/tendermint/tendermint/rpc/lib/types" "github.com/tendermint/tendermint/types" ) @@ -212,60 +212,3 @@ const ( ResultNameUnsafeWriteHeapProfile = "unsafe_write_heap" ResultNameUnsafeFlushMempool = "unsafe_flush_mempool" ) - -type TMResultInner interface { - rpctypes.Result -} - -type TMResult struct { - TMResultInner `json:"unwrap"` -} - -func (tmr TMResult) MarshalJSON() ([]byte, error) { - return tmResultMapper.ToJSON(tmr.TMResultInner) -} - -func (tmr *TMResult) UnmarshalJSON(data []byte) (err error) { - parsed, err := tmResultMapper.FromJSON(data) - if err == nil && parsed != nil { - tmr.TMResultInner = parsed.(TMResultInner) - } - return -} - -func (tmr TMResult) Unwrap() TMResultInner { - tmrI := tmr.TMResultInner - for wrap, ok := tmrI.(TMResult); ok; wrap, ok = tmrI.(TMResult) { - tmrI = wrap.TMResultInner - } - return tmrI -} - -func (tmr TMResult) Empty() bool { - return tmr.TMResultInner == nil -} - -var tmResultMapper = data.NewMapper(TMResult{}). - RegisterImplementation(&ResultGenesis{}, ResultNameGenesis, ResultTypeGenesis). - RegisterImplementation(&ResultBlockchainInfo{}, ResultNameBlockchainInfo, ResultTypeBlockchainInfo). - RegisterImplementation(&ResultBlock{}, ResultNameBlock, ResultTypeBlock). - RegisterImplementation(&ResultCommit{}, ResultNameCommit, ResultTypeCommit). - RegisterImplementation(&ResultStatus{}, ResultNameStatus, ResultTypeStatus). - RegisterImplementation(&ResultNetInfo{}, ResultNameNetInfo, ResultTypeNetInfo). - RegisterImplementation(&ResultDialSeeds{}, ResultNameDialSeeds, ResultTypeDialSeeds). - RegisterImplementation(&ResultValidators{}, ResultNameValidators, ResultTypeValidators). - RegisterImplementation(&ResultDumpConsensusState{}, ResultNameDumpConsensusState, ResultTypeDumpConsensusState). - RegisterImplementation(&ResultBroadcastTx{}, ResultNameBroadcastTx, ResultTypeBroadcastTx). - RegisterImplementation(&ResultBroadcastTxCommit{}, ResultNameBroadcastTxCommit, ResultTypeBroadcastTxCommit). - RegisterImplementation(&ResultTx{}, ResultNameTx, ResultTypeTx). - RegisterImplementation(&ResultUnconfirmedTxs{}, ResultNameUnconfirmedTxs, ResultTypeUnconfirmedTxs). - RegisterImplementation(&ResultSubscribe{}, ResultNameSubscribe, ResultTypeSubscribe). - RegisterImplementation(&ResultUnsubscribe{}, ResultNameUnsubscribe, ResultTypeUnsubscribe). - RegisterImplementation(&ResultEvent{}, ResultNameEvent, ResultTypeEvent). - RegisterImplementation(&ResultUnsafeSetConfig{}, ResultNameUnsafeSetConfig, ResultTypeUnsafeSetConfig). - RegisterImplementation(&ResultUnsafeProfile{}, ResultNameUnsafeStartCPUProfiler, ResultTypeUnsafeStartCPUProfiler). - RegisterImplementation(&ResultUnsafeProfile{}, ResultNameUnsafeStopCPUProfiler, ResultTypeUnsafeStopCPUProfiler). - RegisterImplementation(&ResultUnsafeProfile{}, ResultNameUnsafeWriteHeapProfile, ResultTypeUnsafeWriteHeapProfile). - RegisterImplementation(&ResultUnsafeFlushMempool{}, ResultNameUnsafeFlushMempool, ResultTypeUnsafeFlushMempool). - RegisterImplementation(&ResultABCIQuery{}, ResultNameABCIQuery, ResultTypeABCIQuery). - RegisterImplementation(&ResultABCIInfo{}, ResultNameABCIInfo, ResultTypeABCIInfo) diff --git a/rpc/test/client_test.go b/rpc/test/client_test.go index 8e636c333..aed179d47 100644 --- a/rpc/test/client_test.go +++ b/rpc/test/client_test.go @@ -39,12 +39,11 @@ func TestJSONStatus(t *testing.T) { func testStatus(t *testing.T, client rpc.HTTPClient) { chainID := GetConfig().GetString("chain_id") - tmResult := new(ctypes.TMResult) - _, err := client.Call("status", map[string]interface{}{}, tmResult) + result := new(ctypes.ResultStatus) + _, err := client.Call("status", map[string]interface{}{}, result) require.Nil(t, err) - status := tmResult.Unwrap().(*ctypes.ResultStatus) - assert.Equal(t, chainID, status.NodeInfo.Network) + assert.Equal(t, chainID, result.NodeInfo.Network) } //-------------------------------------------------------------------------------- @@ -70,13 +69,12 @@ func TestJSONBroadcastTxSync(t *testing.T) { func testBroadcastTxSync(t *testing.T, client rpc.HTTPClient) { mem := node.MempoolReactor().Mempool initMemSize := mem.Size() - tmResult := new(ctypes.TMResult) + result := new(ctypes.ResultBroadcastTx) tx := randBytes(t) - _, err := client.Call("broadcast_tx_sync", map[string]interface{}{"tx": tx}, tmResult) + _, err := client.Call("broadcast_tx_sync", map[string]interface{}{"tx": tx}, result) require.Nil(t, err) - res := tmResult.Unwrap().(*ctypes.ResultBroadcastTx) - require.Equal(t, abci.CodeType_OK, res.Code) + require.Equal(t, abci.CodeType_OK, result.Code) require.Equal(t, initMemSize+1, mem.Size()) txs := mem.Reap(1) require.EqualValues(t, tx, txs[0]) @@ -93,14 +91,13 @@ func testTxKV(t *testing.T) ([]byte, []byte, types.Tx) { } func sendTx(t *testing.T, client rpc.HTTPClient) ([]byte, []byte) { - tmResult := new(ctypes.TMResult) + result := new(ctypes.ResultBroadcastTxCommit) k, v, tx := testTxKV(t) - _, err := client.Call("broadcast_tx_commit", map[string]interface{}{"tx": tx}, tmResult) + _, err := client.Call("broadcast_tx_commit", map[string]interface{}{"tx": tx}, result) require.Nil(t, err) - bres := tmResult.Unwrap().(*ctypes.ResultBroadcastTxCommit) - require.NotNil(t, 0, bres.DeliverTx, "%#v", bres) - require.EqualValues(t, 0, bres.CheckTx.Code, "%#v", bres) - require.EqualValues(t, 0, bres.DeliverTx.Code, "%#v", bres) + require.NotNil(t, 0, result.DeliverTx, "%#v", result) + require.EqualValues(t, 0, result.CheckTx.Code, "%#v", result) + require.EqualValues(t, 0, result.DeliverTx.Code, "%#v", result) return k, v } @@ -115,16 +112,15 @@ func TestJSONABCIQuery(t *testing.T) { func testABCIQuery(t *testing.T, client rpc.HTTPClient) { k, _ := sendTx(t, client) time.Sleep(time.Millisecond * 500) - tmResult := new(ctypes.TMResult) + result := new(ctypes.ResultABCIQuery) _, err := client.Call("abci_query", - map[string]interface{}{"path": "", "data": data.Bytes(k), "prove": false}, tmResult) + map[string]interface{}{"path": "", "data": data.Bytes(k), "prove": false}, result) require.Nil(t, err) - resQuery := tmResult.Unwrap().(*ctypes.ResultABCIQuery) - require.EqualValues(t, 0, resQuery.Code) + require.EqualValues(t, 0, result.Code) // XXX: specific to value returned by the dummy - require.NotEqual(t, 0, len(resQuery.Value)) + require.NotEqual(t, 0, len(result.Value)) } //-------------------------------------------------------------------------------- @@ -141,15 +137,14 @@ func TestJSONBroadcastTxCommit(t *testing.T) { func testBroadcastTxCommit(t *testing.T, client rpc.HTTPClient) { require := require.New(t) - tmResult := new(ctypes.TMResult) + result := new(ctypes.ResultBroadcastTxCommit) tx := randBytes(t) - _, err := client.Call("broadcast_tx_commit", map[string]interface{}{"tx": tx}, tmResult) + _, err := client.Call("broadcast_tx_commit", map[string]interface{}{"tx": tx}, result) require.Nil(err) - res := tmResult.Unwrap().(*ctypes.ResultBroadcastTxCommit) - checkTx := res.CheckTx + checkTx := result.CheckTx require.Equal(abci.CodeType_OK, checkTx.Code) - deliverTx := res.DeliverTx + deliverTx := result.DeliverTx require.Equal(abci.CodeType_OK, deliverTx.Code) mem := node.MempoolReactor().Mempool require.Equal(0, mem.Size()) @@ -179,16 +174,15 @@ func testTx(t *testing.T, client rpc.HTTPClient, withIndexer bool) { assert, require := assert.New(t), require.New(t) // first we broadcast a tx - tmResult := new(ctypes.TMResult) + result := new(ctypes.ResultBroadcastTxCommit) txBytes := randBytes(t) tx := types.Tx(txBytes) - _, err := client.Call("broadcast_tx_commit", map[string]interface{}{"tx": txBytes}, tmResult) + _, err := client.Call("broadcast_tx_commit", map[string]interface{}{"tx": txBytes}, result) require.Nil(err) - res := tmResult.Unwrap().(*ctypes.ResultBroadcastTxCommit) - checkTx := res.CheckTx + checkTx := result.CheckTx require.Equal(abci.CodeType_OK, checkTx.Code) - deliverTx := res.DeliverTx + deliverTx := result.DeliverTx require.Equal(abci.CodeType_OK, deliverTx.Code) mem := node.MempoolReactor().Mempool require.Equal(0, mem.Size()) @@ -215,24 +209,23 @@ func testTx(t *testing.T, client rpc.HTTPClient, withIndexer bool) { // now we query for the tx. // since there's only one tx, we know index=0. - tmResult = new(ctypes.TMResult) + result2 := new(ctypes.ResultTx) query := map[string]interface{}{ "hash": tc.hash, "prove": tc.prove, } - _, err = client.Call("tx", query, tmResult) + _, err = client.Call("tx", query, result2) valid := (withIndexer && tc.valid) if !valid { require.NotNil(err, idx) } else { require.Nil(err, idx) - res2 := tmResult.Unwrap().(*ctypes.ResultTx) - assert.Equal(tx, res2.Tx, idx) - assert.Equal(res.Height, res2.Height, idx) - assert.Equal(0, res2.Index, idx) - assert.Equal(abci.CodeType_OK, res2.TxResult.Code, idx) + assert.Equal(tx, result2.Tx, idx) + assert.Equal(result.Height, result2.Height, idx) + assert.Equal(0, result2.Index, idx) + assert.Equal(abci.CodeType_OK, result2.TxResult.Code, idx) // time to verify the proof - proof := res2.Proof + proof := result2.Proof if tc.prove && assert.Equal(tx, proof.Data, idx) { assert.True(proof.Proof.Verify(proof.Index, proof.Total, tx.Hash(), proof.RootHash), idx) } @@ -316,8 +309,8 @@ func TestWSTxEvent(t *testing.T) { }() // send an tx - tmResult := new(ctypes.TMResult) - _, err := GetJSONClient().Call("broadcast_tx_sync", map[string]interface{}{"tx": tx}, tmResult) + result := new(ctypes.ResultBroadcastTx) + _, err := GetJSONClient().Call("broadcast_tx_sync", map[string]interface{}{"tx": tx}, result) require.Nil(err) waitForEvent(t, wsc, eid, true, func() {}, func(eid string, b interface{}) error { @@ -374,12 +367,12 @@ func TestWSDoubleFire(t *testing.T) { // //func TestURIUnsafeSetConfig(t *testing.T) { // for _, testCase := range testCasesUnsafeSetConfig { -// tmResult := new(ctypes.TMResult) +// result := new(ctypes.TMResult) // _, err := GetURIClient().Call("unsafe_set_config", map[string]interface{}{ // "type": testCase[0], // "key": testCase[1], // "value": testCase[2], -// }, tmResult) +// }, result) // require.Nil(t, err) // } // testUnsafeSetConfig(t) @@ -387,10 +380,10 @@ func TestWSDoubleFire(t *testing.T) { // //func TestJSONUnsafeSetConfig(t *testing.T) { // for _, testCase := range testCasesUnsafeSetConfig { -// tmResult := new(ctypes.TMResult) +// result := new(ctypes.TMResult) // _, err := GetJSONClient().Call("unsafe_set_config", // map[string]interface{}{"type": testCase[0], "key": testCase[1], "value": testCase[2]}, -// tmResult) +// result) // require.Nil(t, err) // } // testUnsafeSetConfig(t) diff --git a/rpc/test/helpers.go b/rpc/test/helpers.go index 2b01d0a69..a12d82f23 100644 --- a/rpc/test/helpers.go +++ b/rpc/test/helpers.go @@ -132,16 +132,15 @@ func waitForEvent(t *testing.T, wsc *client.WSClient, eventid string, dieOnTimeo select { case r := <-wsc.ResultsCh: fmt.Println("GOT IT", string(r)) - result := new(ctypes.TMResult) + result := new(ctypes.ResultEvent) err = json.Unmarshal(r, result) if err != nil { fmt.Println("POOP", err) - errCh <- err - break LOOP + // cant distinguish between error and wrong type ... + continue } - event, ok := result.Unwrap().(*ctypes.ResultEvent) - if ok && event.Name == eventid { - goodCh <- event.Data + if result.Name == eventid { + goodCh <- result.Data break LOOP } case err := <-wsc.ErrorsCh: From aa9e673ed78ae6d8bae5b141e9299753f9382fc1 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 28 Apr 2017 22:31:30 -0400 Subject: [PATCH 233/309] test: jq .result[1] -> jq .result --- test/app/counter_test.sh | 2 +- test/app/dummy_test.sh | 4 ++-- test/p2p/atomic_broadcast/test.sh | 10 +++++----- test/p2p/basic/test.sh | 8 ++++---- test/p2p/fast_sync/check_peer.sh | 8 ++++---- test/p2p/kill_all/check_peers.sh | 6 +++--- test/p2p/pex/check_peer.sh | 2 +- test/persist/test_failure_indices.sh | 4 ++-- test/persist/test_simple.sh | 4 ++-- 9 files changed, 24 insertions(+), 24 deletions(-) diff --git a/test/app/counter_test.sh b/test/app/counter_test.sh index 439926a5d..cc5c38b25 100644 --- a/test/app/counter_test.sh +++ b/test/app/counter_test.sh @@ -33,7 +33,7 @@ function sendTx() { ERROR=`echo $RESPONSE | jq .error` ERROR=$(echo "$ERROR" | tr -d '"') # remove surrounding quotes - RESPONSE=`echo $RESPONSE | jq .result[1]` + RESPONSE=`echo $RESPONSE | jq .result` else if [ -f grpc_client ]; then rm grpc_client diff --git a/test/app/dummy_test.sh b/test/app/dummy_test.sh index 0449bc491..1a117c634 100644 --- a/test/app/dummy_test.sh +++ b/test/app/dummy_test.sh @@ -57,7 +57,7 @@ echo "... testing query with /abci_query 2" # we should be able to look up the key RESPONSE=`curl -s "127.0.0.1:46657/abci_query?path=\"\"&data=$(toHex $KEY)&prove=false"` -RESPONSE=`echo $RESPONSE | jq .result[1].response.log` +RESPONSE=`echo $RESPONSE | jq .result.response.log` set +e A=`echo $RESPONSE | grep 'exists'` @@ -70,7 +70,7 @@ set -e # we should not be able to look up the value RESPONSE=`curl -s "127.0.0.1:46657/abci_query?path=\"\"&data=$(toHex $VALUE)&prove=false"` -RESPONSE=`echo $RESPONSE | jq .result[1].response.log` +RESPONSE=`echo $RESPONSE | jq .result.response.log` set +e A=`echo $RESPONSE | grep 'exists'` if [[ $? == 0 ]]; then diff --git a/test/p2p/atomic_broadcast/test.sh b/test/p2p/atomic_broadcast/test.sh index 8e0633c8a..00b339631 100644 --- a/test/p2p/atomic_broadcast/test.sh +++ b/test/p2p/atomic_broadcast/test.sh @@ -17,7 +17,7 @@ for i in `seq 1 $N`; do addr=$(test/p2p/ip.sh $i):46657 # current state - HASH1=`curl -s $addr/status | jq .result[1].latest_app_hash` + HASH1=`curl -s $addr/status | jq .result.latest_app_hash` # - send a tx TX=aadeadbeefbeefbeef0$i @@ -26,15 +26,15 @@ for i in `seq 1 $N`; do echo "" # we need to wait another block to get the new app_hash - h1=`curl -s $addr/status | jq .result[1].latest_block_height` + h1=`curl -s $addr/status | jq .result.latest_block_height` h2=$h1 while [ "$h2" == "$h1" ]; do sleep 1 - h2=`curl -s $addr/status | jq .result[1].latest_block_height` + h2=`curl -s $addr/status | jq .result.latest_block_height` done # check that hash was updated - HASH2=`curl -s $addr/status | jq .result[1].latest_app_hash` + HASH2=`curl -s $addr/status | jq .result.latest_app_hash` if [[ "$HASH1" == "$HASH2" ]]; then echo "Expected state hash to update from $HASH1. Got $HASH2" exit 1 @@ -44,7 +44,7 @@ for i in `seq 1 $N`; do for j in `seq 1 $N`; do if [[ "$i" != "$j" ]]; then addrJ=$(test/p2p/ip.sh $j):46657 - HASH3=`curl -s $addrJ/status | jq .result[1].latest_app_hash` + HASH3=`curl -s $addrJ/status | jq .result.latest_app_hash` if [[ "$HASH2" != "$HASH3" ]]; then echo "App hash for node $j doesn't match. Got $HASH3, expected $HASH2" diff --git a/test/p2p/basic/test.sh b/test/p2p/basic/test.sh index 3399515a8..93444792b 100644 --- a/test/p2p/basic/test.sh +++ b/test/p2p/basic/test.sh @@ -31,19 +31,19 @@ for i in `seq 1 $N`; do N_1=$(($N - 1)) # - assert everyone has N-1 other peers - N_PEERS=`curl -s $addr/net_info | jq '.result[1].peers | length'` + N_PEERS=`curl -s $addr/net_info | jq '.result.peers | length'` while [ "$N_PEERS" != $N_1 ]; do echo "Waiting for node $i to connect to all peers ..." sleep 1 - N_PEERS=`curl -s $addr/net_info | jq '.result[1].peers | length'` + N_PEERS=`curl -s $addr/net_info | jq '.result.peers | length'` done # - assert block height is greater than 1 - BLOCK_HEIGHT=`curl -s $addr/status | jq .result[1].latest_block_height` + BLOCK_HEIGHT=`curl -s $addr/status | jq .result.latest_block_height` while [ "$BLOCK_HEIGHT" -le 1 ]; do echo "Waiting for node $i to commit a block ..." sleep 1 - BLOCK_HEIGHT=`curl -s $addr/status | jq .result[1].latest_block_height` + BLOCK_HEIGHT=`curl -s $addr/status | jq .result.latest_block_height` done echo "Node $i is connected to all peers and at block $BLOCK_HEIGHT" done diff --git a/test/p2p/fast_sync/check_peer.sh b/test/p2p/fast_sync/check_peer.sh index c459277d2..b10c3efc5 100644 --- a/test/p2p/fast_sync/check_peer.sh +++ b/test/p2p/fast_sync/check_peer.sh @@ -15,10 +15,10 @@ peerID=$(( $(($ID % 4)) + 1 )) # 1->2 ... 3->4 ... 4->1 peer_addr=$(test/p2p/ip.sh $peerID):46657 # get another peer's height -h1=`curl -s $peer_addr/status | jq .result[1].latest_block_height` +h1=`curl -s $peer_addr/status | jq .result.latest_block_height` # get another peer's state -root1=`curl -s $peer_addr/status | jq .result[1].latest_app_hash` +root1=`curl -s $peer_addr/status | jq .result.latest_app_hash` echo "Other peer is on height $h1 with state $root1" echo "Waiting for peer $ID to catch up" @@ -29,12 +29,12 @@ set +o pipefail h2="0" while [[ "$h2" -lt "$(($h1+3))" ]]; do sleep 1 - h2=`curl -s $addr/status | jq .result[1].latest_block_height` + h2=`curl -s $addr/status | jq .result.latest_block_height` echo "... $h2" done # check the app hash -root2=`curl -s $addr/status | jq .result[1].latest_app_hash` +root2=`curl -s $addr/status | jq .result.latest_app_hash` if [[ "$root1" != "$root2" ]]; then echo "App hash after fast sync does not match. Got $root2; expected $root1" diff --git a/test/p2p/kill_all/check_peers.sh b/test/p2p/kill_all/check_peers.sh index d085a025c..52dcde91c 100644 --- a/test/p2p/kill_all/check_peers.sh +++ b/test/p2p/kill_all/check_peers.sh @@ -23,7 +23,7 @@ set -e # get the first peer's height addr=$(test/p2p/ip.sh 1):46657 -h1=$(curl -s "$addr/status" | jq .result[1].latest_block_height) +h1=$(curl -s "$addr/status" | jq .result.latest_block_height) echo "1st peer is on height $h1" echo "Waiting until other peers reporting a height higher than the 1st one" @@ -33,14 +33,14 @@ for i in $(seq 2 "$NUM_OF_PEERS"); do while [[ $hi -le $h1 ]] ; do addr=$(test/p2p/ip.sh "$i"):46657 - hi=$(curl -s "$addr/status" | jq .result[1].latest_block_height) + hi=$(curl -s "$addr/status" | jq .result.latest_block_height) echo "... peer $i is on height $hi" ((attempt++)) if [ "$attempt" -ge $MAX_ATTEMPTS_TO_CATCH_UP ] ; then echo "$attempt unsuccessful attempts were made to catch up" - curl -s "$addr/dump_consensus_state" | jq .result[1] + curl -s "$addr/dump_consensus_state" | jq .result exit 1 fi diff --git a/test/p2p/pex/check_peer.sh b/test/p2p/pex/check_peer.sh index ceabd2ac6..e851c8923 100644 --- a/test/p2p/pex/check_peer.sh +++ b/test/p2p/pex/check_peer.sh @@ -10,7 +10,7 @@ echo "2. wait until peer $ID connects to other nodes using pex reactor" peers_count="0" while [[ "$peers_count" -lt "$((N-1))" ]]; do sleep 1 - peers_count=$(curl -s "$addr/net_info" | jq ".result[1].peers | length") + peers_count=$(curl -s "$addr/net_info" | jq ".result.peers | length") echo "... peers count = $peers_count, expected = $((N-1))" done diff --git a/test/persist/test_failure_indices.sh b/test/persist/test_failure_indices.sh index bca8b8ae9..9e3c8f19e 100644 --- a/test/persist/test_failure_indices.sh +++ b/test/persist/test_failure_indices.sh @@ -107,11 +107,11 @@ for failIndex in $(seq $failsStart $failsEnd); do done # wait for a new block - h1=$(curl -s --unix-socket "$RPC_ADDR" http://localhost/status | jq .result[1].latest_block_height) + h1=$(curl -s --unix-socket "$RPC_ADDR" http://localhost/status | jq .result.latest_block_height) h2=$h1 while [ "$h2" == "$h1" ]; do sleep 1 - h2=$(curl -s --unix-socket "$RPC_ADDR" http://localhost/status | jq .result[1].latest_block_height) + h2=$(curl -s --unix-socket "$RPC_ADDR" http://localhost/status | jq .result.latest_block_height) done kill_procs diff --git a/test/persist/test_simple.sh b/test/persist/test_simple.sh index 59bc38458..273c714ca 100644 --- a/test/persist/test_simple.sh +++ b/test/persist/test_simple.sh @@ -57,11 +57,11 @@ while [ "$ERR" != 0 ]; do done # wait for a new block -h1=`curl -s $addr/status | jq .result[1].latest_block_height` +h1=`curl -s $addr/status | jq .result.latest_block_height` h2=$h1 while [ "$h2" == "$h1" ]; do sleep 1 - h2=`curl -s $addr/status | jq .result[1].latest_block_height` + h2=`curl -s $addr/status | jq .result.latest_block_height` done kill_procs From efeadcc0f44f563ebab9870f446c89cb39509208 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 28 Apr 2017 23:18:38 -0400 Subject: [PATCH 234/309] some cleanup from review --- cmd/tendermint/commands/gen_validator.go | 4 +- rpc/core/types/responses.go | 88 +----------------------- rpc/lib/README.md | 12 +--- rpc/lib/client/http_client.go | 7 -- rpc/lib/client/ws_client.go | 7 -- rpc/lib/server/http_server.go | 1 - rpc/lib/types/types.go | 16 ----- rpc/test/helpers.go | 2 - 8 files changed, 6 insertions(+), 131 deletions(-) diff --git a/cmd/tendermint/commands/gen_validator.go b/cmd/tendermint/commands/gen_validator.go index a1217e1f0..97c583c22 100644 --- a/cmd/tendermint/commands/gen_validator.go +++ b/cmd/tendermint/commands/gen_validator.go @@ -1,11 +1,11 @@ package commands import ( + "encoding/json" "fmt" "github.com/spf13/cobra" - "github.com/tendermint/go-wire" "github.com/tendermint/tendermint/types" ) @@ -21,7 +21,7 @@ func init() { func genValidator(cmd *cobra.Command, args []string) { privValidator := types.GenPrivValidator() - privValidatorJSONBytes := wire.JSONBytesPretty(privValidator) + privValidatorJSONBytes, _ := json.MarshalIndent(privValidator, "", "\t") fmt.Printf(`%v `, string(privValidatorJSONBytes)) } diff --git a/rpc/core/types/responses.go b/rpc/core/types/responses.go index 23d68587b..7fa9e70b6 100644 --- a/rpc/core/types/responses.go +++ b/rpc/core/types/responses.go @@ -7,7 +7,6 @@ import ( "github.com/tendermint/go-crypto" "github.com/tendermint/go-wire/data" "github.com/tendermint/tendermint/p2p" - // "github.com/tendermint/tendermint/rpc/lib/types" "github.com/tendermint/tendermint/types" ) @@ -121,94 +120,11 @@ type ResultUnsafeSetConfig struct{} type ResultUnsafeProfile struct{} -type ResultSubscribe struct { -} +type ResultSubscribe struct{} -type ResultUnsubscribe struct { -} +type ResultUnsubscribe struct{} type ResultEvent struct { Name string `json:"name"` Data types.TMEventData `json:"data"` } - -//---------------------------------------- -// response & result types - -const ( - // 0x0 bytes are for the blockchain - ResultTypeGenesis = byte(0x01) - ResultTypeBlockchainInfo = byte(0x02) - ResultTypeBlock = byte(0x03) - ResultTypeCommit = byte(0x04) - - // 0x2 bytes are for the network - ResultTypeStatus = byte(0x20) - ResultTypeNetInfo = byte(0x21) - ResultTypeDialSeeds = byte(0x22) - - // 0x4 bytes are for the consensus - ResultTypeValidators = byte(0x40) - ResultTypeDumpConsensusState = byte(0x41) - - // 0x6 bytes are for txs / the application - ResultTypeBroadcastTx = byte(0x60) - ResultTypeUnconfirmedTxs = byte(0x61) - ResultTypeBroadcastTxCommit = byte(0x62) - ResultTypeTx = byte(0x63) - - // 0x7 bytes are for querying the application - ResultTypeABCIQuery = byte(0x70) - ResultTypeABCIInfo = byte(0x71) - - // 0x8 bytes are for events - ResultTypeSubscribe = byte(0x80) - ResultTypeUnsubscribe = byte(0x81) - ResultTypeEvent = byte(0x82) - - // 0xa bytes for testing - ResultTypeUnsafeSetConfig = byte(0xa0) - ResultTypeUnsafeStartCPUProfiler = byte(0xa1) - ResultTypeUnsafeStopCPUProfiler = byte(0xa2) - ResultTypeUnsafeWriteHeapProfile = byte(0xa3) - ResultTypeUnsafeFlushMempool = byte(0xa4) -) - -const ( - // for the blockchain - ResultNameGenesis = "genesis" - ResultNameBlockchainInfo = "info" - ResultNameBlock = "block" - ResultNameCommit = "commit" - - // for the network - ResultNameStatus = "status" - ResultNameNetInfo = "netinfo" - ResultNameDialSeeds = "dialseeds" - - // for the consensus - ResultNameValidators = "validators" - ResultNameDumpConsensusState = "consensus" - - // for txs / the application - ResultNameBroadcastTx = "broadcast_tx" - ResultNameUnconfirmedTxs = "unconfirmed_tx" - ResultNameBroadcastTxCommit = "broadcast_tx_commit" - ResultNameTx = "tx" - - // for querying the application - ResultNameABCIQuery = "abci_query" - ResultNameABCIInfo = "abci_info" - - // for events - ResultNameSubscribe = "subscribe" - ResultNameUnsubscribe = "unsubscribe" - ResultNameEvent = "event" - - // for testing - ResultNameUnsafeSetConfig = "unsafe_set_config" - ResultNameUnsafeStartCPUProfiler = "unsafe_start_profiler" - ResultNameUnsafeStopCPUProfiler = "unsafe_stop_profiler" - ResultNameUnsafeWriteHeapProfile = "unsafe_write_heap" - ResultNameUnsafeFlushMempool = "unsafe_flush_mempool" -) diff --git a/rpc/lib/README.md b/rpc/lib/README.md index 75531963e..6fe44c22f 100644 --- a/rpc/lib/README.md +++ b/rpc/lib/README.md @@ -59,25 +59,17 @@ though this is configurable when starting the server. Define some types and routes: ``` -// Define a type for results and register concrete versions with go-wire -type Result interface{} - type ResultStatus struct { Value string } -var _ = wire.RegisterInterface( - struct{ Result }{}, - wire.ConcreteType{&ResultStatus{}, 0x1}, -) - // Define some routes var Routes = map[string]*rpcserver.RPCFunc{ - "status": rpcserver.NewRPCFunc(StatusResult, "arg"), + "status": rpcserver.NewRPCFunc(Status, "arg"), } // an rpc function -func StatusResult(v string) (Result, error) { +func Status(v string) (*ResultStatus, error) { return &ResultStatus{v}, nil } diff --git a/rpc/lib/client/http_client.go b/rpc/lib/client/http_client.go index 55963f506..5386779d3 100644 --- a/rpc/lib/client/http_client.go +++ b/rpc/lib/client/http_client.go @@ -67,13 +67,6 @@ func NewJSONRPCClient(remote string) *JSONRPCClient { } func (c *JSONRPCClient) Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) { - // we need this step because we attempt to decode values using `go-wire` - // (handlers.go:176) on the server side - // encodedParams := make(map[string]interface{}) - // for k, v := range params { - // bytes := json.RawMessage(wire.JSONBytes(v)) - // encodedParams[k] = &bytes - // } request := types.RPCRequest{ JSONRPC: "2.0", Method: method, diff --git a/rpc/lib/client/ws_client.go b/rpc/lib/client/ws_client.go index 8884068b9..df9cb3812 100644 --- a/rpc/lib/client/ws_client.go +++ b/rpc/lib/client/ws_client.go @@ -154,13 +154,6 @@ func (wsc *WSClient) Unsubscribe(eventid string) error { // Call asynchronously calls a given method by sending an RPCRequest to the // server. Results will be available on ResultsCh, errors, if any, on ErrorsCh. func (wsc *WSClient) Call(method string, params map[string]interface{}) error { - // we need this step because we attempt to decode values using `go-wire` - // (handlers.go:470) on the server side - // encodedParams := make(map[string]interface{}) - // for k, v := range params { - // bytes := json.RawMessage(wire.JSONBytes(v)) - // encodedParams[k] = &bytes - // } err := wsc.WriteJSON(types.RPCRequest{ JSONRPC: "2.0", Method: method, diff --git a/rpc/lib/server/http_server.go b/rpc/lib/server/http_server.go index ae0923c39..b51699c22 100644 --- a/rpc/lib/server/http_server.go +++ b/rpc/lib/server/http_server.go @@ -58,7 +58,6 @@ func WriteRPCResponseHTTPError(w http.ResponseWriter, httpCode int, res types.RP } func WriteRPCResponseHTTP(w http.ResponseWriter, res types.RPCResponse) { - // jsonBytes := wire.JSONBytesPretty(res) jsonBytes, err := json.Marshal(res) if err != nil { panic(err) diff --git a/rpc/lib/types/types.go b/rpc/lib/types/types.go index 28ddfc0ff..a91811e53 100644 --- a/rpc/lib/types/types.go +++ b/rpc/lib/types/types.go @@ -25,22 +25,6 @@ func NewRPCRequest(id string, method string, params map[string]interface{}) RPCR //---------------------------------------- -/* -Result is a generic interface. -Applications should register type-bytes like so: - -var _ = wire.RegisterInterface( - struct{ Result }{}, - wire.ConcreteType{&ResultGenesis{}, ResultTypeGenesis}, - wire.ConcreteType{&ResultBlockchainInfo{}, ResultTypeBlockchainInfo}, - ... -) -*/ -type Result interface { -} - -//---------------------------------------- - type RPCResponse struct { JSONRPC string `json:"jsonrpc"` ID string `json:"id"` diff --git a/rpc/test/helpers.go b/rpc/test/helpers.go index a12d82f23..11a228bb1 100644 --- a/rpc/test/helpers.go +++ b/rpc/test/helpers.go @@ -131,11 +131,9 @@ func waitForEvent(t *testing.T, wsc *client.WSClient, eventid string, dieOnTimeo for { select { case r := <-wsc.ResultsCh: - fmt.Println("GOT IT", string(r)) result := new(ctypes.ResultEvent) err = json.Unmarshal(r, result) if err != nil { - fmt.Println("POOP", err) // cant distinguish between error and wrong type ... continue } From 6dbcfb32d29e4924ebb900f49a1450f1aeb4e957 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 28 Apr 2017 23:22:54 -0400 Subject: [PATCH 235/309] comment on copied wire file --- rpc/lib/server/wire.go | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/rpc/lib/server/wire.go b/rpc/lib/server/wire.go index ad3d61f8c..4ed9771a1 100644 --- a/rpc/lib/server/wire.go +++ b/rpc/lib/server/wire.go @@ -13,6 +13,10 @@ import ( cmn "github.com/tendermint/tmlibs/common" ) +// NOTE: This code is copied from go-wire in order to allow byte arrays to be treated +// differently whether they are data.Bytes (hex) or not (base64). We can't build this +// into wire directly without refactoring since we'd need to import data but data imports wire + var ( timeType = wire.GetTypeFromStructDeclaration(struct{ time.Time }{}) ) @@ -128,7 +132,6 @@ func readReflectJSON(rv reflect.Value, rt reflect.Type, opts wire.Options, o int *err = errors.New(cmn.Fmt("Expected bytearray of length %v but got %v", length, len(buf))) return } - //log.Info("Read bytearray", "bytes", buf) reflect.Copy(rv, reflect.ValueOf(buf)) } else { oSlice, ok := o.([]interface{}) @@ -144,7 +147,6 @@ func readReflectJSON(rv reflect.Value, rt reflect.Type, opts wire.Options, o int elemRv := rv.Index(i) readReflectJSON(elemRv, elemRt, opts, oSlice[i], err) } - //log.Info("Read x-array", "x", elemRt, "length", length) } case reflect.Slice: @@ -169,7 +171,6 @@ func readReflectJSON(rv reflect.Value, rt reflect.Type, opts wire.Options, o int *err = err_ return } - //log.Info("Read byteslice", "bytes", byteslice) rv.Set(reflect.ValueOf(buf)) } else { // Read length @@ -179,7 +180,6 @@ func readReflectJSON(rv reflect.Value, rt reflect.Type, opts wire.Options, o int return } length := len(oSlice) - //log.Info("Read slice", "length", length) sliceRv := reflect.MakeSlice(rt, length, length) // Read elems for i := 0; i < length; i++ { @@ -237,7 +237,6 @@ func readReflectJSON(rv reflect.Value, rt reflect.Type, opts wire.Options, o int *err = errors.New(cmn.Fmt("Expected string but got type %v", reflect.TypeOf(o))) return } - //log.Info("Read string", "str", str) rv.SetString(str) case reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8, reflect.Int: @@ -246,7 +245,6 @@ func readReflectJSON(rv reflect.Value, rt reflect.Type, opts wire.Options, o int *err = errors.New(cmn.Fmt("Expected numeric but got type %v", reflect.TypeOf(o))) return } - //log.Info("Read num", "num", num) rv.SetInt(int64(num)) case reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8, reflect.Uint: @@ -259,7 +257,6 @@ func readReflectJSON(rv reflect.Value, rt reflect.Type, opts wire.Options, o int *err = errors.New(cmn.Fmt("Expected unsigned numeric but got %v", num)) return } - //log.Info("Read num", "num", num) rv.SetUint(uint64(num)) case reflect.Float64, reflect.Float32: @@ -272,7 +269,6 @@ func readReflectJSON(rv reflect.Value, rt reflect.Type, opts wire.Options, o int *err = errors.New(cmn.Fmt("Expected numeric but got type %v", reflect.TypeOf(o))) return } - //log.Info("Read num", "num", num) rv.SetFloat(num) case reflect.Bool: @@ -281,7 +277,6 @@ func readReflectJSON(rv reflect.Value, rt reflect.Type, opts wire.Options, o int *err = errors.New(cmn.Fmt("Expected boolean but got type %v", reflect.TypeOf(o))) return } - //log.Info("Read boolean", "boolean", bl) rv.SetBool(bl) default: From 4c7a2be06afa9bea6ee8aa6f8ea2b1129d93af8e Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Sun, 30 Apr 2017 16:03:30 -0700 Subject: [PATCH 236/309] Add Tx String representation --- types/tx.go | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/types/tx.go b/types/tx.go index e62b5f666..5656638ae 100644 --- a/types/tx.go +++ b/types/tx.go @@ -3,6 +3,7 @@ package types import ( "bytes" "errors" + "fmt" abci "github.com/tendermint/abci/types" "github.com/tendermint/tmlibs/merkle" @@ -18,6 +19,10 @@ func (tx Tx) Hash() []byte { return merkle.SimpleHashFromBinary(tx) } +func (tx Tx) String() string { + return fmt.Sprintf("Tx{%X}") +} + type Txs []Tx func (txs Txs) Hash() []byte { From 556fbf0c4c755d6ff6152e7061345b9f80fb639e Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Mon, 1 May 2017 11:57:00 +0400 Subject: [PATCH 237/309] logging arch proposal [ci skip] [circleci skip] --- docs/architecture/adr-001.md | 214 +++++++++++++++++++++++++++++++++++ 1 file changed, 214 insertions(+) create mode 100644 docs/architecture/adr-001.md diff --git a/docs/architecture/adr-001.md b/docs/architecture/adr-001.md new file mode 100644 index 000000000..4881adf9a --- /dev/null +++ b/docs/architecture/adr-001.md @@ -0,0 +1,214 @@ +# ADR 1: Logging + +## Context + +Current logging system in Tendermint is very static and not flexible enough. + +Issues: [358](https://github.com/tendermint/tendermint/issues/358), [375](https://github.com/tendermint/tendermint/issues/375). + +What we want from the new system: + +- per package dynamic log levels +- dynamic logger setting (logger tied to the processing struct) +- conventions +- be more visually appealing + +"dynamic" here means the ability to set smth in runtime. + +## Decision + +### 1) An interface + +First, we will need an interface for all of our libraries (`tmlibs`, Tendermint, etc.). My personal preference is go-kit `Logger` interface (see Appendix A.), but that is too much a bigger change. Plus we will still need levels. + +```go +# log.go +type Logger interface { + Debug(msg string, keyvals ...interface{}) error + Info(msg string, keyvals ...interface{}) error + Error(msg string, keyvals ...interface{}) error +} +``` + +On a side note: difference between `Info` and `Notice` is subtle. We probably +could do without `Notice`. Don't think we need `Panic` or `Fatal` as a part of +the interface. These funcs could be implemented as helpers. In fact, we already +have some in `tmlibs/common`. + +- `Debug` - extended output for devs +- `Info` - all that is useful for a user +- `Error` - errors + +`Notice` should become `Info`, `Warn` either `Error` or `Debug` depending on the message, `Crit` -> `Error`. + +This interface should go into `tmlibs/log`. All libraries which are part of the core (tendermint/tendermint) should obey it. + +### 2) Logger with our current formatting + +On top of this interface, we will need to implement a stdout logger, which will be used when Tendermint is configured to output logs to STDOUT. + +Many people say that they like the current output, so let's stick with it. + +``` +NOTE[04-25|14:45:08] ABCI Replay Blocks module=consensus appHeight=0 storeHeight=0 stateHeight=0 +``` + +One minor change: + +``` +NOTE[04-25|14:45:08][consensus] ABCI Replay Blocks appHeight=0 storeHeight=0 stateHeight=0 +``` + +I think it makes sense to move `module` to the beginning because every message has it. + +Note: there are many other formats out there like [logfmt](https://brandur.org/logfmt). + +This logger could be implemented using any logger - [logrus](https://github.com/sirupsen/logrus), [go-kit/log](https://github.com/go-kit/kit/tree/master/log), [zap](https://github.com/uber-go/zap), log15 so far as it + +a) supports coloring output
+b) is moderately fast (buffering)
+c) conforms to the new interface or adapter could be written for it
+d) is somewhat configurable
+ +go-kit is my favorite so far. Check out how easy it is to color errors in red https://github.com/go-kit/kit/blob/master/log/term/example_test.go#L12. Although, coloring could only be applied to the whole string :( + +``` +go-kit +: flexible, modular +go-kit “-”: logfmt format https://brandur.org/logfmt + +logrus +: popular, feature rich (hooks), API and output is more like what we want +logrus -: not so flexible +``` + +```go +# tm_logger.go +// NewTmLogger returns a logger that encodes keyvals to the Writer in +// tm format. +func NewTmLogger(w io.Writer) Logger { + return &tmLogger{kitlog.NewLogfmtLogger(w)} +} + +func (l tmLogger) SetLevel(level string() { + switch (level) { + case "debug": + l.sourceLogger = level.NewFilter(l.sourceLogger, level.AllowDebug()) + } +} + +func (l tmLogger) Info(msg string, keyvals ...interface{}) error { + l.sourceLogger.Log("msg", msg, keyvals...) +} + +# log.go +func With(logger Logger, keyvals ...interface{}) Logger { + kitlog.With(logger.sourceLogger, keyvals...) +} +``` + +Usage: + +```go +logger := log.NewTmLogger(os.Stdout) +logger.SetLevel(config.GetString("log_level")) +node.SetLogger(log.With(logger, "node", Name)) +``` + +**Other log formatters** + +In the future, we may want other formatters like JSONFormatter. + +``` +{ "level": "notice", "time": "2017-04-25 14:45:08.562471297 -0400 EDT", "module": "consensus", "msg": "ABCI Replay Blocks", "appHeight": 0, "storeHeight": 0, "stateHeight": 0 } +``` + +### 3) Dynamic logger setting + +https://dave.cheney.net/2017/01/23/the-package-level-logger-anti-pattern + +This is the hardest part and where the most work will be done. logger should be tied to the processing struct, or the context if it adds some fields to the logger. + +```go +type BaseService struct { + log log15.Logger + name string + started uint32 // atomic + stopped uint32 // atomic +... +} +``` + +BaseService already contains `log` field, so most of the structs embedding it should be fine. We should rename it to `logger`. + +The only thing missing is the ability to set logger: + +``` +func (bs *BaseService) SetLogger(l log.Logger) { + bs.logger = l +} +``` + +### 4) Conventions + +Important keyvals should go first. Example: + +``` +correct +NOTE[04-25|14:45:08][consensus] ABCI Replay Blocks instance=1 appHeight=0 storeHeight=0 stateHeight=0 +``` + +not + +``` +wrong +NOTE[04-25|14:45:08][consensus] ABCI Replay Blocks appHeight=0 storeHeight=0 stateHeight=0 instance=1 +``` + +for that in most cases you'll need to add `instance` field to a logger upon creating, not when u log a particular message: + +```go +colorFn := func(keyvals ...interface{}) term.FgBgColor { + for i := 1; i < len(keyvals); i += 2 { + if keyvals[i] == "instance" && keyvals[i+1] == "1" { + return term.FgBgColor{Fg: term.Blue} + } else if keyvals[i] == "instance" && keyvals[i+1] == "1" { + return term.FgBgColor{Fg: term.Red} + } + } + return term.FgBgColor{} + } +logger := term.NewLogger(os.Stdout, log.NewTmLogger, colorFn) + +c1 := NewConsensusReactor(...) +c1.SetLogger(log.With(logger, "instance", 1)) + +c2 := NewConsensusReactor(...) +c2.SetLogger(log.With(logger, "instance", 2)) +``` + +## Status + +proposed + +## Consequences + +### Positive + +Dynamic logger, which could be turned off for some modules at runtime. Public interface for other projects using Tendermint libraries. + +### Negative + +We may loose the ability to color keys in keyvalue pairs. go-kit allow you to easily change foreground / background colors of the whole string, but not its parts. + +### Neutral + +## Appendix A. + +I really like a minimalistic approach go-kit took with his logger https://github.com/go-kit/kit/tree/master/log: + +``` +type Logger interface { + Log(keyvals ...interface{}) error +} +``` + +See [The Hunt for a Logger Interface](https://go-talks.appspot.com/github.com/ChrisHines/talks/structured-logging/structured-logging.slide). The advantage is greater composability (check out how go-kit defines colored logging or log-leveled logging on top of this interface https://github.com/go-kit/kit/tree/master/log). From b5ab74fd3853e58ffa8105211d21788af3167adb Mon Sep 17 00:00:00 2001 From: Jacob Gadikian Date: Mon, 1 May 2017 15:50:11 +0700 Subject: [PATCH 238/309] Update README.md updated mintnet to mintnet-kubernetes --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 24b3aef2e..e5e15cc94 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ Yay open source! Please see our [contributing guidelines](https://tendermint.com ### Sub-projects * [ABCI](http://github.com/tendermint/abci) -* [Mintnet](http://github.com/tendermint/mintnet) +* [Mintnet-kubernetes](http://github.com/tendermint/mintnet-kubernetes) * [Go-Wire](http://github.com/tendermint/go-wire) * [Go-P2P](http://github.com/tendermint/go-p2p) * [Go-Merkle](http://github.com/tendermint/go-merkle) From 2bf8c40cff0875f6e055dfc71dec2063e6007f69 Mon Sep 17 00:00:00 2001 From: Adrian Brink Date: Mon, 1 May 2017 17:29:44 +0200 Subject: [PATCH 239/309] Add extra memory to virtual machine and add coverage report to gitignore. --- .gitignore | 1 + Vagrantfile | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index c4694b3e1..cc6e1d679 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,4 @@ vendor test/p2p/data/ test/logs .glide +coverage.txt diff --git a/Vagrantfile b/Vagrantfile index a3b329748..c465ed73a 100644 --- a/Vagrantfile +++ b/Vagrantfile @@ -5,7 +5,7 @@ Vagrant.configure("2") do |config| config.vm.box = "ubuntu/trusty64" config.vm.provider "virtualbox" do |v| - v.memory = 3072 + v.memory = 4096 v.cpus = 2 end From f31d6ffb8ce5087e948b80dd0ba667b7cc8f8693 Mon Sep 17 00:00:00 2001 From: Adrian Brink Date: Wed, 3 May 2017 13:55:42 +0200 Subject: [PATCH 240/309] Fix Mintnet kubernetes url --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index e5e15cc94..3a0e80943 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ Yay open source! Please see our [contributing guidelines](https://tendermint.com ### Sub-projects * [ABCI](http://github.com/tendermint/abci) -* [Mintnet-kubernetes](http://github.com/tendermint/mintnet-kubernetes) +* [Mintnet-kubernetes](https://github.com/tendermint/tools/tree/master/mintnet-kubernetes) * [Go-Wire](http://github.com/tendermint/go-wire) * [Go-P2P](http://github.com/tendermint/go-p2p) * [Go-Merkle](http://github.com/tendermint/go-merkle) From 6ba799132c6423685e1ea113c0b7d0c1fac0d6c3 Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Wed, 3 May 2017 16:13:58 +0200 Subject: [PATCH 241/309] json.RawMessage in RPCRequest to defer parsing --- rpc/lib/client/http_client.go | 8 +++----- rpc/lib/client/ws_client.go | 32 ++++++++++++++------------------ rpc/lib/rpc_test.go | 9 +++------ rpc/lib/server/handlers.go | 20 ++++++++++++++------ rpc/lib/types/types.go | 30 ++++++++++++++++++++++++------ 5 files changed, 58 insertions(+), 41 deletions(-) diff --git a/rpc/lib/client/http_client.go b/rpc/lib/client/http_client.go index 5386779d3..9ad6386dc 100644 --- a/rpc/lib/client/http_client.go +++ b/rpc/lib/client/http_client.go @@ -67,11 +67,9 @@ func NewJSONRPCClient(remote string) *JSONRPCClient { } func (c *JSONRPCClient) Call(method string, params map[string]interface{}, result interface{}) (interface{}, error) { - request := types.RPCRequest{ - JSONRPC: "2.0", - Method: method, - Params: params, - ID: "", + request, err := types.MapToRequest("", method, params) + if err != nil { + return nil, err } requestBytes, err := json.Marshal(request) if err != nil { diff --git a/rpc/lib/client/ws_client.go b/rpc/lib/client/ws_client.go index df9cb3812..833668d85 100644 --- a/rpc/lib/client/ws_client.go +++ b/rpc/lib/client/ws_client.go @@ -130,35 +130,31 @@ func (wsc *WSClient) receiveEventsRoutine() { // Subscribe to an event. Note the server must have a "subscribe" route // defined. func (wsc *WSClient) Subscribe(eventid string) error { - err := wsc.WriteJSON(types.RPCRequest{ - JSONRPC: "2.0", - ID: "", - Method: "subscribe", - Params: map[string]interface{}{"event": eventid}, - }) + params := map[string]interface{}{"event": eventid} + request, err := types.MapToRequest("", "subscribe", params) + if err == nil { + err = wsc.WriteJSON(request) + } return err } // Unsubscribe from an event. Note the server must have a "unsubscribe" route // defined. func (wsc *WSClient) Unsubscribe(eventid string) error { - err := wsc.WriteJSON(types.RPCRequest{ - JSONRPC: "2.0", - ID: "", - Method: "unsubscribe", - Params: map[string]interface{}{"event": eventid}, - }) + params := map[string]interface{}{"event": eventid} + request, err := types.MapToRequest("", "unsubscribe", params) + if err == nil { + err = wsc.WriteJSON(request) + } return err } // Call asynchronously calls a given method by sending an RPCRequest to the // server. Results will be available on ResultsCh, errors, if any, on ErrorsCh. func (wsc *WSClient) Call(method string, params map[string]interface{}) error { - err := wsc.WriteJSON(types.RPCRequest{ - JSONRPC: "2.0", - Method: method, - Params: params, - ID: "", - }) + request, err := types.MapToRequest("", method, params) + if err == nil { + err = wsc.WriteJSON(request) + } return err } diff --git a/rpc/lib/rpc_test.go b/rpc/lib/rpc_test.go index a14551f4f..3a2b36d51 100644 --- a/rpc/lib/rpc_test.go +++ b/rpc/lib/rpc_test.go @@ -306,12 +306,9 @@ func TestWSHandlesArrayParams(t *testing.T) { val := "acbd" params := []interface{}{val} - err = cl.WriteJSON(types.RPCRequest{ - JSONRPC: "2.0", - ID: "", - Method: "echo_ws", - Params: params, - }) + request, err := types.ArrayToRequest("", "echo_ws", params) + require.Nil(t, err) + err = cl.WriteJSON(request) require.Nil(t, err) select { diff --git a/rpc/lib/server/handlers.go b/rpc/lib/server/handlers.go index 51eaf1401..321b72d6d 100644 --- a/rpc/lib/server/handlers.go +++ b/rpc/lib/server/handlers.go @@ -140,15 +140,23 @@ func makeJSONRPCHandler(funcMap map[string]*RPCFunc) http.HandlerFunc { } } -// Convert a []interface{} OR a map[string]interface{} to properly typed values +// raw is unparsed json (from json.RawMessage). It either has +// and array or a map behind it, let's parse this all without resorting to wire... // // argsOffset should be 0 for RPC calls, and 1 for WS requests, where len(rpcFunc.args) != len(rpcFunc.argNames). // Example: // rpcFunc.args = [rpctypes.WSRPCContext string] // rpcFunc.argNames = ["arg"] -func jsonParamsToArgs(rpcFunc *RPCFunc, paramsI interface{}, argsOffset int) ([]reflect.Value, error) { +func jsonParamsToArgs(rpcFunc *RPCFunc, raw []byte, argsOffset int) ([]reflect.Value, error) { values := make([]reflect.Value, len(rpcFunc.argNames)) + // right now, this is the same as before, but the whole parsing is in one function... + var paramsI interface{} + err := json.Unmarshal(raw, ¶msI) + if err != nil { + return nil, err + } + switch params := paramsI.(type) { case map[string]interface{}: @@ -188,13 +196,13 @@ func jsonParamsToArgs(rpcFunc *RPCFunc, paramsI interface{}, argsOffset int) ([] } // Convert a []interface{} OR a map[string]interface{} to properly typed values -func jsonParamsToArgsRPC(rpcFunc *RPCFunc, paramsI interface{}) ([]reflect.Value, error) { - return jsonParamsToArgs(rpcFunc, paramsI, 0) +func jsonParamsToArgsRPC(rpcFunc *RPCFunc, params *json.RawMessage) ([]reflect.Value, error) { + return jsonParamsToArgs(rpcFunc, *params, 0) } // Same as above, but with the first param the websocket connection -func jsonParamsToArgsWS(rpcFunc *RPCFunc, paramsI interface{}, wsCtx types.WSRPCContext) ([]reflect.Value, error) { - values, err := jsonParamsToArgs(rpcFunc, paramsI, 1) +func jsonParamsToArgsWS(rpcFunc *RPCFunc, params *json.RawMessage, wsCtx types.WSRPCContext) ([]reflect.Value, error) { + values, err := jsonParamsToArgs(rpcFunc, *params, 1) if err != nil { return nil, err } diff --git a/rpc/lib/types/types.go b/rpc/lib/types/types.go index a91811e53..8076e4b0d 100644 --- a/rpc/lib/types/types.go +++ b/rpc/lib/types/types.go @@ -8,21 +8,39 @@ import ( ) type RPCRequest struct { - JSONRPC string `json:"jsonrpc"` - ID string `json:"id"` - Method string `json:"method"` - Params interface{} `json:"params"` // must be map[string]interface{} or []interface{} + JSONRPC string `json:"jsonrpc"` + ID string `json:"id"` + Method string `json:"method"` + Params *json.RawMessage `json:"params"` // must be map[string]interface{} or []interface{} } -func NewRPCRequest(id string, method string, params map[string]interface{}) RPCRequest { +func NewRPCRequest(id string, method string, params json.RawMessage) RPCRequest { return RPCRequest{ JSONRPC: "2.0", ID: id, Method: method, - Params: params, + Params: ¶ms, } } +func MapToRequest(id string, method string, params map[string]interface{}) (RPCRequest, error) { + payload, err := json.Marshal(params) + if err != nil { + return RPCRequest{}, err + } + request := NewRPCRequest(id, method, payload) + return request, nil +} + +func ArrayToRequest(id string, method string, params []interface{}) (RPCRequest, error) { + payload, err := json.Marshal(params) + if err != nil { + return RPCRequest{}, err + } + request := NewRPCRequest(id, method, payload) + return request, nil +} + //---------------------------------------- type RPCResponse struct { From 4c1d41c12ed238d81598cc6c49db43d520c96b9a Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Wed, 3 May 2017 16:26:18 +0200 Subject: [PATCH 242/309] Test json rpc parsing --- rpc/lib/server/parse_test.go | 41 ++++++++++++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/rpc/lib/server/parse_test.go b/rpc/lib/server/parse_test.go index 5b0478b64..3c6d6edde 100644 --- a/rpc/lib/server/parse_test.go +++ b/rpc/lib/server/parse_test.go @@ -2,6 +2,7 @@ package rpcserver import ( "encoding/json" + "strconv" "testing" "github.com/stretchr/testify/assert" @@ -131,3 +132,43 @@ func TestParseJSONArray(t *testing.T) { } } } + +func TestParseRPC(t *testing.T) { + assert := assert.New(t) + + demo := func(height int, name string) {} + call := NewRPCFunc(demo, "height,name") + + cases := []struct { + raw string + height int64 + name string + fail bool + }{ + // should parse + {`[7, "flew"]`, 7, "flew", false}, + {`{"name": "john", "height": 22}`, 22, "john", false}, + // defaults + {`{"name": "solo", "unused": "stuff"}`, 0, "solo", false}, + // should fail - wrong types/lenght + {`["flew", 7]`, 0, "", true}, + {`[7,"flew",100]`, 0, "", true}, + {`{"name": -12, "height": "fred"}`, 0, "", true}, + } + for idx, tc := range cases { + i := strconv.Itoa(idx) + data := []byte(tc.raw) + vals, err := jsonParamsToArgs(call, data, 0) + if tc.fail { + assert.NotNil(err, i) + } else { + assert.Nil(err, "%s: %+v", i, err) + if assert.Equal(2, len(vals), i) { + assert.Equal(tc.height, vals[0].Int(), i) + assert.Equal(tc.name, vals[1].String(), i) + } + } + + } + +} From 4a1b714ca4decaa3fdc3b08c855220ad09aa8121 Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Wed, 3 May 2017 16:42:30 +0200 Subject: [PATCH 243/309] All tests pass without go-wire json ptr madness --- rpc/lib/server/handlers.go | 106 +++++++------- rpc/lib/server/wire.go | 285 ------------------------------------- 2 files changed, 53 insertions(+), 338 deletions(-) delete mode 100644 rpc/lib/server/wire.go diff --git a/rpc/lib/server/handlers.go b/rpc/lib/server/handlers.go index 321b72d6d..588af2765 100644 --- a/rpc/lib/server/handlers.go +++ b/rpc/lib/server/handlers.go @@ -15,6 +15,7 @@ import ( "github.com/gorilla/websocket" "github.com/pkg/errors" //wire "github.com/tendermint/go-wire" + types "github.com/tendermint/tendermint/rpc/lib/types" cmn "github.com/tendermint/tmlibs/common" events "github.com/tendermint/tmlibs/events" @@ -140,6 +141,45 @@ func makeJSONRPCHandler(funcMap map[string]*RPCFunc) http.HandlerFunc { } } +func mapParamsToArgs(rpcFunc *RPCFunc, params map[string]*json.RawMessage, argsOffset int) ([]reflect.Value, error) { + values := make([]reflect.Value, len(rpcFunc.argNames)) + for i, argName := range rpcFunc.argNames { + argType := rpcFunc.args[i+argsOffset] + + if p, ok := params[argName]; ok && len(*p) > 0 { + val := reflect.New(argType) + err := json.Unmarshal(*p, val.Interface()) + if err != nil { + return nil, err + } + values[i] = val.Elem() + } else { // use default for that type + values[i] = reflect.Zero(argType) + } + } + + return values, nil +} + +func arrayParamsToArgs(rpcFunc *RPCFunc, params []*json.RawMessage, argsOffset int) ([]reflect.Value, error) { + if len(rpcFunc.argNames) != len(params) { + return nil, errors.Errorf("Expected %v parameters (%v), got %v (%v)", + len(rpcFunc.argNames), rpcFunc.argNames, len(params), params) + } + + values := make([]reflect.Value, len(params)) + for i, p := range params { + argType := rpcFunc.args[i+argsOffset] + val := reflect.New(argType) + err := json.Unmarshal(*p, val.Interface()) + if err != nil { + return nil, err + } + values[i] = val.Elem() + } + return values, nil +} + // raw is unparsed json (from json.RawMessage). It either has // and array or a map behind it, let's parse this all without resorting to wire... // @@ -148,51 +188,22 @@ func makeJSONRPCHandler(funcMap map[string]*RPCFunc) http.HandlerFunc { // rpcFunc.args = [rpctypes.WSRPCContext string] // rpcFunc.argNames = ["arg"] func jsonParamsToArgs(rpcFunc *RPCFunc, raw []byte, argsOffset int) ([]reflect.Value, error) { - values := make([]reflect.Value, len(rpcFunc.argNames)) - - // right now, this is the same as before, but the whole parsing is in one function... - var paramsI interface{} - err := json.Unmarshal(raw, ¶msI) - if err != nil { - return nil, err + // first, try to get the map.. + var m map[string]*json.RawMessage + err := json.Unmarshal(raw, &m) + if err == nil { + return mapParamsToArgs(rpcFunc, m, argsOffset) } - switch params := paramsI.(type) { - - case map[string]interface{}: - for i, argName := range rpcFunc.argNames { - argType := rpcFunc.args[i+argsOffset] - - // decode param if provided - if param, ok := params[argName]; ok && "" != param { - v, err := _jsonObjectToArg(argType, param) - if err != nil { - return nil, err - } - values[i] = v - } else { // use default for that type - values[i] = reflect.Zero(argType) - } - } - case []interface{}: - if len(rpcFunc.argNames) != len(params) { - return nil, errors.New(fmt.Sprintf("Expected %v parameters (%v), got %v (%v)", - len(rpcFunc.argNames), rpcFunc.argNames, len(params), params)) - } - values := make([]reflect.Value, len(params)) - for i, p := range params { - ty := rpcFunc.args[i+argsOffset] - v, err := _jsonObjectToArg(ty, p) - if err != nil { - return nil, err - } - values[i] = v - } - return values, nil - default: - return nil, fmt.Errorf("Unknown type for JSON params %v. Expected map[string]interface{} or []interface{}", reflect.TypeOf(paramsI)) + // otherwise, try an array + var a []*json.RawMessage + err = json.Unmarshal(raw, &a) + if err == nil { + return arrayParamsToArgs(rpcFunc, a, argsOffset) } - return values, nil + + // otherwise, bad format, we cannot parse + return nil, errors.Errorf("Unknown type for JSON params: %v. Expected map or array", err) } // Convert a []interface{} OR a map[string]interface{} to properly typed values @@ -209,17 +220,6 @@ func jsonParamsToArgsWS(rpcFunc *RPCFunc, params *json.RawMessage, wsCtx types.W return append([]reflect.Value{reflect.ValueOf(wsCtx)}, values...), nil } -func _jsonObjectToArg(ty reflect.Type, object interface{}) (reflect.Value, error) { - var err error - v := reflect.New(ty) - readJSONObjectPtr(v.Interface(), object, &err) - if err != nil { - return v, err - } - v = v.Elem() - return v, nil -} - // rpc.json //----------------------------------------------------------------------------- // rpc.http diff --git a/rpc/lib/server/wire.go b/rpc/lib/server/wire.go deleted file mode 100644 index 4ed9771a1..000000000 --- a/rpc/lib/server/wire.go +++ /dev/null @@ -1,285 +0,0 @@ -package rpcserver - -import ( - "encoding/base64" - "encoding/hex" - "reflect" - "time" - - "github.com/pkg/errors" - - "github.com/tendermint/go-wire" - "github.com/tendermint/go-wire/data" - cmn "github.com/tendermint/tmlibs/common" -) - -// NOTE: This code is copied from go-wire in order to allow byte arrays to be treated -// differently whether they are data.Bytes (hex) or not (base64). We can't build this -// into wire directly without refactoring since we'd need to import data but data imports wire - -var ( - timeType = wire.GetTypeFromStructDeclaration(struct{ time.Time }{}) -) - -func readJSONObjectPtr(o interface{}, object interface{}, err *error) interface{} { - rv, rt := reflect.ValueOf(o), reflect.TypeOf(o) - if rv.Kind() == reflect.Ptr { - readReflectJSON(rv.Elem(), rt.Elem(), wire.Options{}, object, err) - } else { - cmn.PanicSanity("ReadJSON(Object)Ptr expects o to be a pointer") - } - return o -} - -func readByteJSON(o interface{}) (typeByte byte, rest interface{}, err error) { - oSlice, ok := o.([]interface{}) - if !ok { - err = errors.New(cmn.Fmt("Expected type [Byte,?] but got type %v", reflect.TypeOf(o))) - return - } - if len(oSlice) != 2 { - err = errors.New(cmn.Fmt("Expected [Byte,?] len 2 but got len %v", len(oSlice))) - return - } - typeByte_, ok := oSlice[0].(float64) - typeByte = byte(typeByte_) - rest = oSlice[1] - return -} - -// Contract: Caller must ensure that rt is supported -// (e.g. is recursively composed of supported native types, and structs and slices.) -// rv and rt refer to the object we're unmarhsaling into, whereas o is the result of naiive json unmarshal (map[string]interface{}) -func readReflectJSON(rv reflect.Value, rt reflect.Type, opts wire.Options, o interface{}, err *error) { - - // Get typeInfo - typeInfo := wire.GetTypeInfo(rt) - - if rt.Kind() == reflect.Interface { - if !typeInfo.IsRegisteredInterface { - // There's no way we can read such a thing. - *err = errors.New(cmn.Fmt("Cannot read unregistered interface type %v", rt)) - return - } - if o == nil { - return // nil - } - typeByte, rest, err_ := readByteJSON(o) - if err_ != nil { - *err = err_ - return - } - crt, ok := typeInfo.ByteToType[typeByte] - if !ok { - *err = errors.New(cmn.Fmt("Byte %X not registered for interface %v", typeByte, rt)) - return - } - if crt.Kind() == reflect.Ptr { - crt = crt.Elem() - crv := reflect.New(crt) - readReflectJSON(crv.Elem(), crt, opts, rest, err) - rv.Set(crv) // NOTE: orig rv is ignored. - } else { - crv := reflect.New(crt).Elem() - readReflectJSON(crv, crt, opts, rest, err) - rv.Set(crv) // NOTE: orig rv is ignored. - } - return - } - - if rt.Kind() == reflect.Ptr { - if o == nil { - return // nil - } - // Create new struct if rv is nil. - if rv.IsNil() { - newRv := reflect.New(rt.Elem()) - rv.Set(newRv) - rv = newRv - } - // Dereference pointer - rv, rt = rv.Elem(), rt.Elem() - typeInfo = wire.GetTypeInfo(rt) - // continue... - } - - switch rt.Kind() { - case reflect.Array: - elemRt := rt.Elem() - length := rt.Len() - if elemRt.Kind() == reflect.Uint8 { - // Special case: Bytearrays - oString, ok := o.(string) - if !ok { - *err = errors.New(cmn.Fmt("Expected string but got type %v", reflect.TypeOf(o))) - return - } - - // if its data.Bytes, use hex; else use base64 - dbty := reflect.TypeOf(data.Bytes{}) - var buf []byte - var err_ error - if rt == dbty { - buf, err_ = hex.DecodeString(oString) - } else { - buf, err_ = base64.StdEncoding.DecodeString(oString) - } - if err_ != nil { - *err = err_ - return - } - if len(buf) != length { - *err = errors.New(cmn.Fmt("Expected bytearray of length %v but got %v", length, len(buf))) - return - } - reflect.Copy(rv, reflect.ValueOf(buf)) - } else { - oSlice, ok := o.([]interface{}) - if !ok { - *err = errors.New(cmn.Fmt("Expected array of %v but got type %v", rt, reflect.TypeOf(o))) - return - } - if len(oSlice) != length { - *err = errors.New(cmn.Fmt("Expected array of length %v but got %v", length, len(oSlice))) - return - } - for i := 0; i < length; i++ { - elemRv := rv.Index(i) - readReflectJSON(elemRv, elemRt, opts, oSlice[i], err) - } - } - - case reflect.Slice: - elemRt := rt.Elem() - if elemRt.Kind() == reflect.Uint8 { - // Special case: Byteslices - oString, ok := o.(string) - if !ok { - *err = errors.New(cmn.Fmt("Expected string but got type %v", reflect.TypeOf(o))) - return - } - // if its data.Bytes, use hex; else use base64 - dbty := reflect.TypeOf(data.Bytes{}) - var buf []byte - var err_ error - if rt == dbty { - buf, err_ = hex.DecodeString(oString) - } else { - buf, err_ = base64.StdEncoding.DecodeString(oString) - } - if err_ != nil { - *err = err_ - return - } - rv.Set(reflect.ValueOf(buf)) - } else { - // Read length - oSlice, ok := o.([]interface{}) - if !ok { - *err = errors.New(cmn.Fmt("Expected array of %v but got type %v", rt, reflect.TypeOf(o))) - return - } - length := len(oSlice) - sliceRv := reflect.MakeSlice(rt, length, length) - // Read elems - for i := 0; i < length; i++ { - elemRv := sliceRv.Index(i) - readReflectJSON(elemRv, elemRt, opts, oSlice[i], err) - } - rv.Set(sliceRv) - } - - case reflect.Struct: - if rt == timeType { - // Special case: time.Time - str, ok := o.(string) - if !ok { - *err = errors.New(cmn.Fmt("Expected string but got type %v", reflect.TypeOf(o))) - return - } - // try three ways, seconds, milliseconds, or microseconds... - t, err_ := time.Parse(time.RFC3339Nano, str) - if err_ != nil { - *err = err_ - return - } - rv.Set(reflect.ValueOf(t)) - } else { - if typeInfo.Unwrap { - f := typeInfo.Fields[0] - fieldIdx, fieldType, opts := f.Index, f.Type, f.Options - fieldRv := rv.Field(fieldIdx) - readReflectJSON(fieldRv, fieldType, opts, o, err) - } else { - oMap, ok := o.(map[string]interface{}) - if !ok { - *err = errors.New(cmn.Fmt("Expected map but got type %v", reflect.TypeOf(o))) - return - } - // TODO: ensure that all fields are set? - // TODO: disallow unknown oMap fields? - for _, fieldInfo := range typeInfo.Fields { - f := fieldInfo - fieldIdx, fieldType, opts := f.Index, f.Type, f.Options - value, ok := oMap[opts.JSONName] - if !ok { - continue // Skip missing fields. - } - fieldRv := rv.Field(fieldIdx) - readReflectJSON(fieldRv, fieldType, opts, value, err) - } - } - } - - case reflect.String: - str, ok := o.(string) - if !ok { - *err = errors.New(cmn.Fmt("Expected string but got type %v", reflect.TypeOf(o))) - return - } - rv.SetString(str) - - case reflect.Int64, reflect.Int32, reflect.Int16, reflect.Int8, reflect.Int: - num, ok := o.(float64) - if !ok { - *err = errors.New(cmn.Fmt("Expected numeric but got type %v", reflect.TypeOf(o))) - return - } - rv.SetInt(int64(num)) - - case reflect.Uint64, reflect.Uint32, reflect.Uint16, reflect.Uint8, reflect.Uint: - num, ok := o.(float64) - if !ok { - *err = errors.New(cmn.Fmt("Expected numeric but got type %v", reflect.TypeOf(o))) - return - } - if num < 0 { - *err = errors.New(cmn.Fmt("Expected unsigned numeric but got %v", num)) - return - } - rv.SetUint(uint64(num)) - - case reflect.Float64, reflect.Float32: - if !opts.Unsafe { - *err = errors.New("Wire float* support requires `wire:\"unsafe\"`") - return - } - num, ok := o.(float64) - if !ok { - *err = errors.New(cmn.Fmt("Expected numeric but got type %v", reflect.TypeOf(o))) - return - } - rv.SetFloat(num) - - case reflect.Bool: - bl, ok := o.(bool) - if !ok { - *err = errors.New(cmn.Fmt("Expected boolean but got type %v", reflect.TypeOf(o))) - return - } - rv.SetBool(bl) - - default: - cmn.PanicSanity(cmn.Fmt("Unknown field type %v", rt.Kind())) - } -} From 7ebf011fcd200ee51bfbb5315ed9ebb9f8c02989 Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Wed, 3 May 2017 16:58:21 +0200 Subject: [PATCH 244/309] Fixed rpctypes.Request creation to new format --- benchmarks/simu/counter.go | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/benchmarks/simu/counter.go b/benchmarks/simu/counter.go index a22162b97..e9502f956 100644 --- a/benchmarks/simu/counter.go +++ b/benchmarks/simu/counter.go @@ -7,11 +7,11 @@ import ( "fmt" "github.com/gorilla/websocket" - . "github.com/tendermint/tmlibs/common" - "github.com/tendermint/tendermint/rpc/lib/client" - "github.com/tendermint/tendermint/rpc/lib/types" "github.com/tendermint/go-wire" _ "github.com/tendermint/tendermint/rpc/core/types" // Register RPCResponse > Result types + "github.com/tendermint/tendermint/rpc/lib/client" + "github.com/tendermint/tendermint/rpc/lib/types" + . "github.com/tendermint/tmlibs/common" ) func main() { @@ -37,13 +37,16 @@ func main() { for i := 0; ; i++ { binary.BigEndian.PutUint64(buf, uint64(i)) //txBytes := hex.EncodeToString(buf[:n]) - request := rpctypes.NewRPCRequest("fakeid", + request, err := rpctypes.MapToRequest("fakeid", "broadcast_tx", map[string]interface{}{"tx": buf[:8]}) + if err != nil { + Exit(err.Error()) + } reqBytes := wire.JSONBytes(request) //fmt.Println("!!", string(reqBytes)) fmt.Print(".") - err := ws.WriteMessage(websocket.TextMessage, reqBytes) + err = ws.WriteMessage(websocket.TextMessage, reqBytes) if err != nil { Exit(err.Error()) } From 9860c8fee14bfd4f6f14b62ee6d8e938a485387a Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Wed, 3 May 2017 14:33:00 -0400 Subject: [PATCH 245/309] rpc: cleanup some comments [ci skip] --- rpc/lib/server/handlers.go | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/rpc/lib/server/handlers.go b/rpc/lib/server/handlers.go index 588af2765..f780fba44 100644 --- a/rpc/lib/server/handlers.go +++ b/rpc/lib/server/handlers.go @@ -14,7 +14,6 @@ import ( "github.com/gorilla/websocket" "github.com/pkg/errors" - //wire "github.com/tendermint/go-wire" types "github.com/tendermint/tendermint/rpc/lib/types" cmn "github.com/tendermint/tmlibs/common" @@ -180,8 +179,7 @@ func arrayParamsToArgs(rpcFunc *RPCFunc, params []*json.RawMessage, argsOffset i return values, nil } -// raw is unparsed json (from json.RawMessage). It either has -// and array or a map behind it, let's parse this all without resorting to wire... +// raw is unparsed json (from json.RawMessage) encoding either a map or an array. // // argsOffset should be 0 for RPC calls, and 1 for WS requests, where len(rpcFunc.args) != len(rpcFunc.argNames). // Example: @@ -277,7 +275,6 @@ func httpParamsToArgs(rpcFunc *RPCFunc, r *http.Request) ([]reflect.Value, error continue } - // Pass values to go-wire values[i], err = _jsonStringToArg(argType, arg) if err != nil { return nil, err From 809e0e8c5933604ba8b2d096803ada7c5ec4dfd3 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Thu, 4 May 2017 13:32:24 +0400 Subject: [PATCH 246/309] update Dockerfile [ci skip] [circleci skip] --- DOCKER/Dockerfile | 4 ++-- DOCKER/Makefile | 6 ++++-- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/DOCKER/Dockerfile b/DOCKER/Dockerfile index 08a7b2674..a5f734f19 100644 --- a/DOCKER/Dockerfile +++ b/DOCKER/Dockerfile @@ -1,8 +1,8 @@ FROM alpine:3.5 # This is the release of tendermint to pull in. -ENV TM_VERSION 0.9.0 -ENV TM_SHA256SUM 697033ea0f34f8b34a8a2b74c4dd730b47dd4efcfce65e53e953bdae8eb14364 +ENV TM_VERSION 0.9.1 +ENV TM_SHA256SUM da34234755937140dcd953afcc965555fad7e05afd546711bc5bdc2df3d54226 # Tendermint will be looking for genesis file in /tendermint (unless you change # `genesis_file` in config.toml). You can put your config.toml and private diff --git a/DOCKER/Makefile b/DOCKER/Makefile index 092233017..612b9a694 100644 --- a/DOCKER/Makefile +++ b/DOCKER/Makefile @@ -1,10 +1,12 @@ build: # TAG=0.8.0 TAG_NO_PATCH=0.8 - docker build -t "tendermint/tendermint" -t "tendermint/tendermint:$TAG" -t "tendermint/tendermint:$TAG_NO_PATCH" . + docker build -t "tendermint/tendermint" -t "tendermint/tendermint:$(TAG)" -t "tendermint/tendermint:$(TAG_NO_PATCH)" . push: # TAG=0.8.0 TAG_NO_PATCH=0.8 - docker push "tendermint/tendermint" "tendermint/tendermint:$TAG" "tendermint/tendermint:$TAG_NO_PATCH" + docker push "tendermint/tendermint:latest" + docker push "tendermint/tendermint:$(TAG)" + docker push "tendermint/tendermint:$(TAG_NO_PATCH)" build_develop: docker build -t "tendermint/tendermint:develop" -f Dockerfile.develop . From 4871e64b0307e79f3335c835ae0c5ab2b4ac0c42 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Thu, 4 May 2017 13:36:27 +0400 Subject: [PATCH 247/309] update docker README [ci skip] [circleci skip] --- DOCKER/README.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/DOCKER/README.md b/DOCKER/README.md index b7b9f3815..a1f9f28c9 100644 --- a/DOCKER/README.md +++ b/DOCKER/README.md @@ -1,6 +1,7 @@ # Supported tags and respective `Dockerfile` links -- `0.9.0`, `0.9`, `latest` [(Dockerfile)](https://github.com/tendermint/tendermint/blob/d474baeeea6c22b289e7402449572f7c89ee21da/DOCKER/Dockerfile) +- `0.9.1`, `0.9`, `latest` [(Dockerfile)](https://github.com/tendermint/tendermint/blob/809e0e8c5933604ba8b2d096803ada7c5ec4dfd3/DOCKER/Dockerfile) +- `0.9.0` [(Dockerfile)](https://github.com/tendermint/tendermint/blob/d474baeeea6c22b289e7402449572f7c89ee21da/DOCKER/Dockerfile) - `0.8.0`, `0.8` [(Dockerfile)](https://github.com/tendermint/tendermint/blob/bf64dd21fdb193e54d8addaaaa2ecf7ac371de8c/DOCKER/Dockerfile) - `develop` [(Dockerfile)](https://github.com/tendermint/tendermint/blob/master/DOCKER/Dockerfile.develop) From 56a1a2d917017bc6cf4194303b9d78f1cc64ec14 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 28 Apr 2017 23:43:03 -0400 Subject: [PATCH 248/309] remove logrotate.config --- config/tendermint/logrotate.config | 22 ---------------------- 1 file changed, 22 deletions(-) delete mode 100644 config/tendermint/logrotate.config diff --git a/config/tendermint/logrotate.config b/config/tendermint/logrotate.config deleted file mode 100644 index 73eaf74e7..000000000 --- a/config/tendermint/logrotate.config +++ /dev/null @@ -1,22 +0,0 @@ -// If you wanted to use logrotate, I suppose this might be the config you want. -// Instead, I'll just write our own, that way we don't need sudo to install. - -$HOME/.tendermint/logs/tendermint.log { - missingok - notifempty - rotate 12 - daily - size 10M - compress - delaycompress -} - -$HOME/.barak/logs/barak.log { - missingok - notifempty - rotate 12 - weekly - size 10M - compress - delaycompress -} From 29c0e6e4f49c664c8c708085c7ad7541c2daf2f6 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 28 Apr 2017 23:50:24 -0400 Subject: [PATCH 249/309] remove viper from blockchain and state --- blockchain/reactor.go | 8 ++------ node/node.go | 4 ++-- state/state.go | 5 ++--- types/block.go | 5 ++++- 4 files changed, 10 insertions(+), 12 deletions(-) diff --git a/blockchain/reactor.go b/blockchain/reactor.go index 1ea5650ed..0d51d124c 100644 --- a/blockchain/reactor.go +++ b/blockchain/reactor.go @@ -6,8 +6,6 @@ import ( "reflect" "time" - "github.com/spf13/viper" - "github.com/tendermint/go-wire" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/proxy" @@ -44,7 +42,6 @@ type consensusReactor interface { type BlockchainReactor struct { p2p.BaseReactor - config *viper.Viper state *sm.State proxyAppConn proxy.AppConnConsensus // same as consensus.proxyAppConn store *BlockStore @@ -58,7 +55,7 @@ type BlockchainReactor struct { } // NewBlockchainReactor returns new reactor instance. -func NewBlockchainReactor(config *viper.Viper, state *sm.State, proxyAppConn proxy.AppConnConsensus, store *BlockStore, fastSync bool) *BlockchainReactor { +func NewBlockchainReactor(state *sm.State, proxyAppConn proxy.AppConnConsensus, store *BlockStore, fastSync bool) *BlockchainReactor { if state.LastBlockHeight == store.Height()-1 { store.height-- // XXX HACK, make this better } @@ -73,7 +70,6 @@ func NewBlockchainReactor(config *viper.Viper, state *sm.State, proxyAppConn pro timeoutsCh, ) bcR := &BlockchainReactor{ - config: config, state: state, proxyAppConn: proxyAppConn, store: store, @@ -226,7 +222,7 @@ FOR_LOOP: // We need both to sync the first block. break SYNC_LOOP } - firstParts := first.MakePartSet(bcR.config.GetInt("block_part_size")) // TODO: put part size in parts header? + firstParts := first.MakePartSet(types.DefaultPartSetSize) firstPartsHeader := firstParts.Header() // Finally, verify the first block using the second's commit // NOTE: we can probably make this more efficient, but note that calling diff --git a/node/node.go b/node/node.go index e34f8c726..0471bf3c7 100644 --- a/node/node.go +++ b/node/node.go @@ -73,7 +73,7 @@ func NewNode(config *viper.Viper, privValidator *types.PrivValidator, clientCrea // Get State stateDB := dbm.NewDB("state", config.GetString("db_backend"), config.GetString("db_dir")) - state := sm.GetState(config, stateDB) + state := sm.GetState(stateDB, config.GetString("genesis_file")) // add the chainid and number of validators to the global config config.Set("chain_id", state.ChainID) @@ -121,7 +121,7 @@ func NewNode(config *viper.Viper, privValidator *types.PrivValidator, clientCrea } // Make BlockchainReactor - bcReactor := bc.NewBlockchainReactor(config, state.Copy(), proxyApp.Consensus(), blockStore, fastSync) + bcReactor := bc.NewBlockchainReactor(state.Copy(), proxyApp.Consensus(), blockStore, fastSync) // Make MempoolReactor mempool := mempl.NewMempool(config, proxyApp.Mempool()) diff --git a/state/state.go b/state/state.go index 2625cbc71..bacde0ab5 100644 --- a/state/state.go +++ b/state/state.go @@ -6,7 +6,6 @@ import ( "sync" "time" - "github.com/spf13/viper" abci "github.com/tendermint/abci/types" cmn "github.com/tendermint/tmlibs/common" dbm "github.com/tendermint/tmlibs/db" @@ -169,10 +168,10 @@ func (s *State) GetValidators() (*types.ValidatorSet, *types.ValidatorSet) { // Load the most recent state from "state" db, // or create a new one (and save) from genesis. -func GetState(config *viper.Viper, stateDB dbm.DB) *State { +func GetState(stateDB dbm.DB, genesisFile string) *State { state := LoadState(stateDB) if state == nil { - state = MakeGenesisStateFromFile(stateDB, config.GetString("genesis_file")) + state = MakeGenesisStateFromFile(stateDB, genesisFile) state.Save() } diff --git a/types/block.go b/types/block.go index 65d4031da..afa3be4e7 100644 --- a/types/block.go +++ b/types/block.go @@ -14,7 +14,10 @@ import ( "github.com/tendermint/tmlibs/merkle" ) -const MaxBlockSize = 22020096 // 21MB TODO make it configurable +const ( + MaxBlockSize = 22020096 // 21MB TODO make it configurable + DefaultPartSetSize = 65536 // 64kB TODO: put part size in parts header? +) type Block struct { *Header `json:"header"` From 7c0f51e24bab2144dcdae7f23c4d392be161f8e7 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 28 Apr 2017 23:59:02 -0400 Subject: [PATCH 250/309] remove viper from mempool --- consensus/replay_file.go | 5 +---- mempool/mempool.go | 28 +++++++++++++--------------- mempool/reactor.go | 18 ++++++++++++------ node/node.go | 15 +++++++++++++-- 4 files changed, 39 insertions(+), 27 deletions(-) diff --git a/consensus/replay_file.go b/consensus/replay_file.go index 1d2a91f31..5717adda8 100644 --- a/consensus/replay_file.go +++ b/consensus/replay_file.go @@ -11,7 +11,6 @@ import ( "github.com/spf13/viper" bc "github.com/tendermint/tendermint/blockchain" - mempl "github.com/tendermint/tendermint/mempool" "github.com/tendermint/tendermint/proxy" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" @@ -262,9 +261,7 @@ func newConsensusStateForReplay(config *viper.Viper) *ConsensusState { cmn.Exit(cmn.Fmt("Failed to start event switch: %v", err)) } - mempool := mempl.NewMempool(config, proxyApp.Mempool()) - - consensusState := NewConsensusState(config, state.Copy(), proxyApp.Consensus(), blockStore, mempool) + consensusState := NewConsensusState(config, state.Copy(), proxyApp.Consensus(), blockStore, types.MockMempool{}) consensusState.SetEventSwitch(eventSwitch) return consensusState } diff --git a/mempool/mempool.go b/mempool/mempool.go index 621f0931e..46a78d268 100644 --- a/mempool/mempool.go +++ b/mempool/mempool.go @@ -7,14 +7,13 @@ import ( "sync/atomic" "time" - "github.com/spf13/viper" - abci "github.com/tendermint/abci/types" - "github.com/tendermint/tendermint/proxy" - "github.com/tendermint/tendermint/types" auto "github.com/tendermint/tmlibs/autofile" "github.com/tendermint/tmlibs/clist" - . "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tmlibs/common" + + "github.com/tendermint/tendermint/proxy" + "github.com/tendermint/tendermint/types" ) /* @@ -48,7 +47,7 @@ TODO: Better handle abci client errors. (make it automatically handle connection const cacheSize = 100000 type Mempool struct { - config *viper.Viper + config Config proxyMtx sync.Mutex proxyAppConn proxy.AppConnMempool @@ -67,7 +66,7 @@ type Mempool struct { wal *auto.AutoFile } -func NewMempool(config *viper.Viper, proxyAppConn proxy.AppConnMempool) *Mempool { +func NewMempool(config Config, proxyAppConn proxy.AppConnMempool) *Mempool { mempool := &Mempool{ config: config, proxyAppConn: proxyAppConn, @@ -86,17 +85,17 @@ func NewMempool(config *viper.Viper, proxyAppConn proxy.AppConnMempool) *Mempool } func (mem *Mempool) initWAL() { - walDir := mem.config.GetString("mempool_wal_dir") + walDir := mem.config.WalDir if walDir != "" { - err := EnsureDir(walDir, 0700) + err := cmn.EnsureDir(walDir, 0700) if err != nil { log.Error("Error ensuring Mempool wal dir", "error", err) - PanicSanity(err) + cmn.PanicSanity(err) } af, err := auto.OpenAutoFile(walDir + "/wal") if err != nil { log.Error("Error opening Mempool wal file", "error", err) - PanicSanity(err) + cmn.PanicSanity(err) } mem.wal = af } @@ -220,7 +219,7 @@ func (mem *Mempool) resCbRecheck(req *abci.Request, res *abci.Response) { case *abci.Response_CheckTx: memTx := mem.recheckCursor.Value.(*mempoolTx) if !bytes.Equal(req.GetCheckTx().Tx, memTx.tx) { - PanicSanity(Fmt("Unexpected tx response from proxy during recheck\n"+ + cmn.PanicSanity(cmn.Fmt("Unexpected tx response from proxy during recheck\n"+ "Expected %X, got %X", r.CheckTx.Data, memTx.tx)) } if r.CheckTx.Code == abci.CodeType_OK { @@ -270,7 +269,7 @@ func (mem *Mempool) collectTxs(maxTxs int) types.Txs { } else if maxTxs < 0 { maxTxs = mem.txs.Len() } - txs := make([]types.Tx, 0, MinInt(mem.txs.Len(), maxTxs)) + txs := make([]types.Tx, 0, cmn.MinInt(mem.txs.Len(), maxTxs)) for e := mem.txs.Front(); e != nil && len(txs) < maxTxs; e = e.Next() { memTx := e.Value.(*mempoolTx) txs = append(txs, memTx.tx) @@ -299,8 +298,7 @@ func (mem *Mempool) Update(height int, txs types.Txs) { // Recheck mempool txs if any txs were committed in the block // NOTE/XXX: in some apps a tx could be invalidated due to EndBlock, // so we really still do need to recheck, but this is for debugging - if mem.config.GetBool("mempool_recheck") && - (mem.config.GetBool("mempool_recheck_empty") || len(txs) > 0) { + if mem.config.Recheck && (mem.config.RecheckEmpty || len(txs) > 0) { log.Info("Recheck txs", "numtxs", len(goodTxs)) mem.recheckTxs(goodTxs) // At this point, mem.txs are being rechecked. diff --git a/mempool/reactor.go b/mempool/reactor.go index 6bea53b0c..3f25cc562 100644 --- a/mempool/reactor.go +++ b/mempool/reactor.go @@ -6,13 +6,12 @@ import ( "reflect" "time" - "github.com/spf13/viper" - abci "github.com/tendermint/abci/types" "github.com/tendermint/go-wire" + "github.com/tendermint/tmlibs/clist" + "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/types" - "github.com/tendermint/tmlibs/clist" ) const ( @@ -22,15 +21,22 @@ const ( peerCatchupSleepIntervalMS = 100 // If peer is behind, sleep this amount ) +type Config struct { + Recheck bool // true + RecheckEmpty bool // true + Broadcast bool // true + WalDir string // rootDir+"/data/mempool.wal") +} + // MempoolReactor handles mempool tx broadcasting amongst peers. type MempoolReactor struct { p2p.BaseReactor - config *viper.Viper + config Config Mempool *Mempool evsw types.EventSwitch } -func NewMempoolReactor(config *viper.Viper, mempool *Mempool) *MempoolReactor { +func NewMempoolReactor(config Config, mempool *Mempool) *MempoolReactor { memR := &MempoolReactor{ config: config, Mempool: mempool, @@ -103,7 +109,7 @@ type Peer interface { // TODO: Handle mempool or reactor shutdown? // As is this routine may block forever if no new txs come in. func (memR *MempoolReactor) broadcastTxRoutine(peer Peer) { - if !memR.config.GetBool("mempool_broadcast") { + if !memR.config.Broadcast { return } diff --git a/node/node.go b/node/node.go index 0471bf3c7..f7aca6d05 100644 --- a/node/node.go +++ b/node/node.go @@ -124,8 +124,8 @@ func NewNode(config *viper.Viper, privValidator *types.PrivValidator, clientCrea bcReactor := bc.NewBlockchainReactor(state.Copy(), proxyApp.Consensus(), blockStore, fastSync) // Make MempoolReactor - mempool := mempl.NewMempool(config, proxyApp.Mempool()) - mempoolReactor := mempl.NewMempoolReactor(config, mempool) + mempool := mempl.NewMempool(mempoolConfig(config), proxyApp.Mempool()) + mempoolReactor := mempl.NewMempoolReactor(mempoolConfig(config), mempool) // Make ConsensusReactor consensusState := consensus.NewConsensusState(config, state.Copy(), proxyApp.Consensus(), blockStore, mempool) @@ -431,3 +431,14 @@ func ProtocolAndAddress(listenAddr string) (string, string) { } return protocol, address } + +//------------------------------------------------------------------------------ + +func mempoolConfig(config *viper.Viper) mempl.Config { + return mempl.Config{ + Recheck: config.GetBool("mempool_recheck"), + RecheckEmpty: config.GetBool("mempool_recheck_empty"), + Broadcast: config.GetBool("mempool_broadcast"), + WalDir: config.GetString("mempool_wal_dir"), + } +} From 1fcc9dc6542d037f60dcdda2103a4d10e74faa89 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Sat, 29 Apr 2017 00:04:01 -0400 Subject: [PATCH 251/309] remove viper from proxy --- consensus/replay_file.go | 3 ++- node/node.go | 8 ++++++-- proxy/client.go | 9 ++------- proxy/multi_app_conn.go | 10 +++------- 4 files changed, 13 insertions(+), 17 deletions(-) diff --git a/consensus/replay_file.go b/consensus/replay_file.go index 5717adda8..9bcfafe6c 100644 --- a/consensus/replay_file.go +++ b/consensus/replay_file.go @@ -246,7 +246,8 @@ func newConsensusStateForReplay(config *viper.Viper) *ConsensusState { state := sm.MakeGenesisStateFromFile(stateDB, config.GetString("genesis_file")) // Create proxyAppConn connection (consensus, mempool, query) - proxyApp := proxy.NewAppConns(config, proxy.DefaultClientCreator(config), NewHandshaker(config, state, blockStore)) + clientCreator := proxy.DefaultClientCreator(config.GetString("proxy_app"), config.GetString("abci"), config.GetString("db_dir")) + proxyApp := proxy.NewAppConns(clientCreator, NewHandshaker(config, state, blockStore)) _, err := proxyApp.Start() if err != nil { cmn.Exit(cmn.Fmt("Error starting proxy app conns: %v", err)) diff --git a/node/node.go b/node/node.go index f7aca6d05..2958f98ef 100644 --- a/node/node.go +++ b/node/node.go @@ -62,7 +62,11 @@ func NewNodeDefault(config *viper.Viper) *Node { // Get PrivValidator privValidatorFile := config.GetString("priv_validator_file") privValidator := types.LoadOrGenPrivValidator(privValidatorFile) - return NewNode(config, privValidator, proxy.DefaultClientCreator(config)) + return NewNode(config, privValidator, proxy.DefaultClientCreator( + config.GetString("proxy_app"), + config.GetString("abci"), + config.GetString("db_dir"), + )) } func NewNode(config *viper.Viper, privValidator *types.PrivValidator, clientCreator proxy.ClientCreator) *Node { @@ -81,7 +85,7 @@ func NewNode(config *viper.Viper, privValidator *types.PrivValidator, clientCrea // Create the proxyApp, which manages connections (consensus, mempool, query) // and sync tendermint and the app by replaying any necessary blocks - proxyApp := proxy.NewAppConns(config, clientCreator, consensus.NewHandshaker(config, state, blockStore)) + proxyApp := proxy.NewAppConns(clientCreator, consensus.NewHandshaker(config, state, blockStore)) if _, err := proxyApp.Start(); err != nil { cmn.Exit(cmn.Fmt("Error starting proxy app connections: %v", err)) } diff --git a/proxy/client.go b/proxy/client.go index 4c50f38b3..5720cce30 100644 --- a/proxy/client.go +++ b/proxy/client.go @@ -4,8 +4,6 @@ import ( "fmt" "sync" - "github.com/spf13/viper" - abcicli "github.com/tendermint/abci/client" "github.com/tendermint/abci/example/dummy" "github.com/tendermint/abci/types" @@ -64,15 +62,12 @@ func (r *remoteClientCreator) NewABCIClient() (abcicli.Client, error) { //----------------------------------------------------------------- // default -func DefaultClientCreator(config *viper.Viper) ClientCreator { - addr := config.GetString("proxy_app") - transport := config.GetString("abci") - +func DefaultClientCreator(addr, transport, dbDir string) ClientCreator { switch addr { case "dummy": return NewLocalClientCreator(dummy.NewDummyApplication()) case "persistent_dummy": - return NewLocalClientCreator(dummy.NewPersistentDummyApplication(config.GetString("db_dir"))) + return NewLocalClientCreator(dummy.NewPersistentDummyApplication(dbDir)) case "nilapp": return NewLocalClientCreator(types.NewBaseApplication()) default: diff --git a/proxy/multi_app_conn.go b/proxy/multi_app_conn.go index 9f70713eb..8043f4818 100644 --- a/proxy/multi_app_conn.go +++ b/proxy/multi_app_conn.go @@ -1,7 +1,6 @@ package proxy import ( - "github.com/spf13/viper" cmn "github.com/tendermint/tmlibs/common" ) @@ -16,8 +15,8 @@ type AppConns interface { Query() AppConnQuery } -func NewAppConns(config *viper.Viper, clientCreator ClientCreator, handshaker Handshaker) AppConns { - return NewMultiAppConn(config, clientCreator, handshaker) +func NewAppConns(clientCreator ClientCreator, handshaker Handshaker) AppConns { + return NewMultiAppConn(clientCreator, handshaker) } //----------------------------- @@ -34,8 +33,6 @@ type Handshaker interface { type multiAppConn struct { cmn.BaseService - config *viper.Viper - handshaker Handshaker mempoolConn *appConnMempool @@ -46,9 +43,8 @@ type multiAppConn struct { } // Make all necessary abci connections to the application -func NewMultiAppConn(config *viper.Viper, clientCreator ClientCreator, handshaker Handshaker) *multiAppConn { +func NewMultiAppConn(clientCreator ClientCreator, handshaker Handshaker) *multiAppConn { multiAppConn := &multiAppConn{ - config: config, handshaker: handshaker, clientCreator: clientCreator, } From f0e7f0acf894f9b49924904ed2bcb08f9777d56d Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Sat, 29 Apr 2017 00:07:50 -0400 Subject: [PATCH 252/309] remove viper from rpc except test --- node/node.go | 1 - rpc/core/dev.go | 27 ------------------- rpc/core/pipe.go | 7 ----- rpc/core/routes.go | 9 ++++--- rpc/core/types/responses.go | 3 +-- rpc/test/client_test.go | 54 ++----------------------------------- 6 files changed, 9 insertions(+), 92 deletions(-) diff --git a/node/node.go b/node/node.go index 2958f98ef..4b344ffc0 100644 --- a/node/node.go +++ b/node/node.go @@ -293,7 +293,6 @@ func (n *Node) AddListener(l p2p.Listener) { // ConfigureRPC sets all variables in rpccore so they will serve // rpc calls from this node func (n *Node) ConfigureRPC() { - rpccore.SetConfig(n.config) rpccore.SetEventSwitch(n.evsw) rpccore.SetBlockStore(n.blockStore) rpccore.SetConsensusState(n.consensusState) diff --git a/rpc/core/dev.go b/rpc/core/dev.go index 43a989534..a3c970d48 100644 --- a/rpc/core/dev.go +++ b/rpc/core/dev.go @@ -1,10 +1,8 @@ package core import ( - "fmt" "os" "runtime/pprof" - "strconv" ctypes "github.com/tendermint/tendermint/rpc/core/types" ) @@ -14,31 +12,6 @@ func UnsafeFlushMempool() (*ctypes.ResultUnsafeFlushMempool, error) { return &ctypes.ResultUnsafeFlushMempool{}, nil } -func UnsafeSetConfig(typ, key, value string) (*ctypes.ResultUnsafeSetConfig, error) { - switch typ { - case "string": - config.Set(key, value) - case "int": - val, err := strconv.Atoi(value) - if err != nil { - return nil, fmt.Errorf("non-integer value found. key:%s; value:%s; err:%v", key, value, err) - } - config.Set(key, val) - case "bool": - switch value { - case "true": - config.Set(key, true) - case "false": - config.Set(key, false) - default: - return nil, fmt.Errorf("bool value must be true or false. got %s", value) - } - default: - return nil, fmt.Errorf("Unknown type %s", typ) - } - return &ctypes.ResultUnsafeSetConfig{}, nil -} - var profFile *os.File func UnsafeStartCPUProfiler(filename string) (*ctypes.ResultUnsafeProfile, error) { diff --git a/rpc/core/pipe.go b/rpc/core/pipe.go index b10ff4737..7a6a2d326 100644 --- a/rpc/core/pipe.go +++ b/rpc/core/pipe.go @@ -1,8 +1,6 @@ package core import ( - "github.com/spf13/viper" - crypto "github.com/tendermint/go-crypto" "github.com/tendermint/tendermint/consensus" p2p "github.com/tendermint/tendermint/p2p" @@ -34,7 +32,6 @@ var ( // external, thread safe interfaces eventSwitch types.EventSwitch proxyAppQuery proxy.AppConnQuery - config *viper.Viper // interfaces defined in types and above blockStore types.BlockStore @@ -49,10 +46,6 @@ var ( txIndexer txindex.TxIndexer ) -func SetConfig(c *viper.Viper) { - config = c -} - func SetEventSwitch(evsw types.EventSwitch) { eventSwitch = evsw } diff --git a/rpc/core/routes.go b/rpc/core/routes.go index b662ae48c..5e045d49d 100644 --- a/rpc/core/routes.go +++ b/rpc/core/routes.go @@ -2,6 +2,12 @@ package core import ( rpc "github.com/tendermint/tendermint/rpc/lib/server" + + data "github.com/tendermint/go-wire/data" + ctypes "github.com/tendermint/tendermint/rpc/core/types" + rpc "github.com/tendermint/tendermint/rpc/lib/server" + "github.com/tendermint/tendermint/rpc/lib/types" + "github.com/tendermint/tendermint/types" ) // TODO: better system than "unsafe" prefix @@ -36,9 +42,6 @@ var Routes = map[string]*rpc.RPCFunc{ "dial_seeds": rpc.NewRPCFunc(UnsafeDialSeeds, "seeds"), "unsafe_flush_mempool": rpc.NewRPCFunc(UnsafeFlushMempool, ""), - // config is not in general thread safe. expose specifics if you need em - // "unsafe_set_config": rpc.NewRPCFunc(UnsafeSetConfig, "type,key,value"), - // profiler API "unsafe_start_cpu_profiler": rpc.NewRPCFunc(UnsafeStartCPUProfiler, "filename"), "unsafe_stop_cpu_profiler": rpc.NewRPCFunc(UnsafeStopCPUProfiler, ""), diff --git a/rpc/core/types/responses.go b/rpc/core/types/responses.go index 7fa9e70b6..b9c22a8b0 100644 --- a/rpc/core/types/responses.go +++ b/rpc/core/types/responses.go @@ -6,6 +6,7 @@ import ( abci "github.com/tendermint/abci/types" "github.com/tendermint/go-crypto" "github.com/tendermint/go-wire/data" + "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/types" ) @@ -116,8 +117,6 @@ type ResultABCIQuery struct { type ResultUnsafeFlushMempool struct{} -type ResultUnsafeSetConfig struct{} - type ResultUnsafeProfile struct{} type ResultSubscribe struct{} diff --git a/rpc/test/client_test.go b/rpc/test/client_test.go index aed179d47..bd972f919 100644 --- a/rpc/test/client_test.go +++ b/rpc/test/client_test.go @@ -13,12 +13,13 @@ import ( abci "github.com/tendermint/abci/types" "github.com/tendermint/go-wire/data" + . "github.com/tendermint/tmlibs/common" + "github.com/tendermint/tendermint/rpc/core" ctypes "github.com/tendermint/tendermint/rpc/core/types" rpc "github.com/tendermint/tendermint/rpc/lib/client" "github.com/tendermint/tendermint/state/txindex/null" "github.com/tendermint/tendermint/types" - . "github.com/tendermint/tmlibs/common" ) //-------------------------------------------------------------------------------- @@ -349,54 +350,3 @@ func TestWSDoubleFire(t *testing.T) { return nil }) }*/ - -//-------------------------------------------------------------------------------- -//TODO needs to be refactored so we don't use a mutable config but rather update specific values we're interested in -// unsafe_set_config - -//var stringVal = "my string" -//var intVal = 987654321 -//var boolVal = true -// -//// don't change these -//var testCasesUnsafeSetConfig = [][]string{ -// []string{"string", "key1", stringVal}, -// []string{"int", "key2", fmt.Sprintf("%v", intVal)}, -// []string{"bool", "key3", fmt.Sprintf("%v", boolVal)}, -//} -// -//func TestURIUnsafeSetConfig(t *testing.T) { -// for _, testCase := range testCasesUnsafeSetConfig { -// result := new(ctypes.TMResult) -// _, err := GetURIClient().Call("unsafe_set_config", map[string]interface{}{ -// "type": testCase[0], -// "key": testCase[1], -// "value": testCase[2], -// }, result) -// require.Nil(t, err) -// } -// testUnsafeSetConfig(t) -//} -// -//func TestJSONUnsafeSetConfig(t *testing.T) { -// for _, testCase := range testCasesUnsafeSetConfig { -// result := new(ctypes.TMResult) -// _, err := GetJSONClient().Call("unsafe_set_config", -// map[string]interface{}{"type": testCase[0], "key": testCase[1], "value": testCase[2]}, -// result) -// require.Nil(t, err) -// } -// testUnsafeSetConfig(t) -//} -// -//func testUnsafeSetConfig(t *testing.T) { -// require := require.New(t) -// s := config.GetString("key1") -// require.Equal(stringVal, s) -// -// i := config.GetInt("key2") -// require.Equal(intVal, i) -// -// b := config.GetBool("key3") -// require.Equal(boolVal, b) -//} From 95c74b2ccdafe2241054f5f0fea53cb7e35733a8 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Sat, 29 Apr 2017 00:18:30 -0400 Subject: [PATCH 253/309] remove some more viper --- .../commands/reset_priv_validator.go | 27 +++++++++---------- consensus/replay.go | 11 +++----- consensus/replay_file.go | 2 +- node/node.go | 2 +- 4 files changed, 18 insertions(+), 24 deletions(-) diff --git a/cmd/tendermint/commands/reset_priv_validator.go b/cmd/tendermint/commands/reset_priv_validator.go index a611935bb..448a1869f 100644 --- a/cmd/tendermint/commands/reset_priv_validator.go +++ b/cmd/tendermint/commands/reset_priv_validator.go @@ -4,7 +4,6 @@ import ( "os" "github.com/spf13/cobra" - "github.com/spf13/viper" "github.com/tendermint/log15" "github.com/tendermint/tendermint/types" @@ -30,36 +29,34 @@ func init() { // XXX: this is totally unsafe. // it's only suitable for testnets. func resetAll(cmd *cobra.Command, args []string) { - ResetAll(config, log) + ResetAll(config.GetString("db_dir"), config.GetString("priv_validator_file"), log) } // XXX: this is totally unsafe. // it's only suitable for testnets. func resetPrivValidator(cmd *cobra.Command, args []string) { - resetPrivValidatorLocal(config, log) + resetPrivValidatorLocal(config.GetString("priv_validator_file"), log) } // Exported so other CLI tools can use it -func ResetAll(c *viper.Viper, l log15.Logger) { - resetPrivValidatorLocal(c, l) - dataDir := c.GetString("db_dir") - os.RemoveAll(dataDir) - l.Notice("Removed all data", "dir", dataDir) +func ResetAll(dbDir, privValFile string, l log15.Logger) { + resetPrivValidatorLocal(privValFile, l) + os.RemoveAll(dbDir) + l.Notice("Removed all data", "dir", dbDir) } -func resetPrivValidatorLocal(c *viper.Viper, l log15.Logger) { +func resetPrivValidatorLocal(privValFile string, l log15.Logger) { // Get PrivValidator var privValidator *types.PrivValidator - privValidatorFile := c.GetString("priv_validator_file") - if _, err := os.Stat(privValidatorFile); err == nil { - privValidator = types.LoadPrivValidator(privValidatorFile) + if _, err := os.Stat(privValFile); err == nil { + privValidator = types.LoadPrivValidator(privValFile) privValidator.Reset() - l.Notice("Reset PrivValidator", "file", privValidatorFile) + l.Notice("Reset PrivValidator", "file", privValFile) } else { privValidator = types.GenPrivValidator() - privValidator.SetFile(privValidatorFile) + privValidator.SetFile(privValFile) privValidator.Save() - l.Notice("Generated PrivValidator", "file", privValidatorFile) + l.Notice("Generated PrivValidator", "file", privValFile) } } diff --git a/consensus/replay.go b/consensus/replay.go index ecb29e3d5..01199007e 100644 --- a/consensus/replay.go +++ b/consensus/replay.go @@ -10,8 +10,6 @@ import ( "strings" "time" - "github.com/spf13/viper" - abci "github.com/tendermint/abci/types" "github.com/tendermint/go-wire" auto "github.com/tendermint/tmlibs/autofile" @@ -200,15 +198,14 @@ func makeHeightSearchFunc(height int) auto.SearchFunc { // we were last and using the WAL to recover there type Handshaker struct { - config *viper.Viper - state *sm.State - store types.BlockStore + state *sm.State + store types.BlockStore nBlocks int // number of blocks applied to the state } -func NewHandshaker(config *viper.Viper, state *sm.State, store types.BlockStore) *Handshaker { - return &Handshaker{config, state, store, 0} +func NewHandshaker(state *sm.State, store types.BlockStore) *Handshaker { + return &Handshaker{state, store, 0} } func (h *Handshaker) NBlocks() int { diff --git a/consensus/replay_file.go b/consensus/replay_file.go index 9bcfafe6c..1f4de893a 100644 --- a/consensus/replay_file.go +++ b/consensus/replay_file.go @@ -247,7 +247,7 @@ func newConsensusStateForReplay(config *viper.Viper) *ConsensusState { // Create proxyAppConn connection (consensus, mempool, query) clientCreator := proxy.DefaultClientCreator(config.GetString("proxy_app"), config.GetString("abci"), config.GetString("db_dir")) - proxyApp := proxy.NewAppConns(clientCreator, NewHandshaker(config, state, blockStore)) + proxyApp := proxy.NewAppConns(clientCreator, NewHandshaker(state, blockStore)) _, err := proxyApp.Start() if err != nil { cmn.Exit(cmn.Fmt("Error starting proxy app conns: %v", err)) diff --git a/node/node.go b/node/node.go index 4b344ffc0..764c89b87 100644 --- a/node/node.go +++ b/node/node.go @@ -85,7 +85,7 @@ func NewNode(config *viper.Viper, privValidator *types.PrivValidator, clientCrea // Create the proxyApp, which manages connections (consensus, mempool, query) // and sync tendermint and the app by replaying any necessary blocks - proxyApp := proxy.NewAppConns(clientCreator, consensus.NewHandshaker(config, state, blockStore)) + proxyApp := proxy.NewAppConns(clientCreator, consensus.NewHandshaker(state, blockStore)) if _, err := proxyApp.Start(); err != nil { cmn.Exit(cmn.Fmt("Error starting proxy app connections: %v", err)) } From d8fb226ec49fc29cf4694a46adac522f2b96925a Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Sat, 29 Apr 2017 10:55:26 -0400 Subject: [PATCH 254/309] new config --- cmd/tendermint/commands/root.go | 4 +- cmd/tendermint/commands/run_node.go | 41 ++++++------- config/tendermint/config.go | 83 +++++++++++++-------------- config/tendermint/types.go | 89 +++++++++++++++++++++++++++++ node/node.go | 18 ++++-- 5 files changed, 163 insertions(+), 72 deletions(-) create mode 100644 config/tendermint/types.go diff --git a/cmd/tendermint/commands/root.go b/cmd/tendermint/commands/root.go index de5b71bd1..4a97c44fd 100644 --- a/cmd/tendermint/commands/root.go +++ b/cmd/tendermint/commands/root.go @@ -20,12 +20,12 @@ var RootCmd = &cobra.Command{ Short: "Tendermint Core (BFT Consensus) in Go", PersistentPreRun: func(cmd *cobra.Command, args []string) { // set the log level in the config and logger - config.Set("log_level", logLevel) + config.Set("node.log_level", logLevel) logger.SetLogLevel(logLevel) }, } func init() { //parse flag and set config - RootCmd.PersistentFlags().StringVar(&logLevel, "log_level", config.GetString("log_level"), "Log level") + RootCmd.PersistentFlags().StringVar(&logLevel, "log_level", config.GetString("node.log_level"), "Log level") } diff --git a/cmd/tendermint/commands/run_node.go b/cmd/tendermint/commands/run_node.go index b2b23af5c..2ddc50a02 100644 --- a/cmd/tendermint/commands/run_node.go +++ b/cmd/tendermint/commands/run_node.go @@ -7,6 +7,7 @@ import ( "github.com/spf13/cobra" + //cfg "github.com/tendermint/tendermint/config/tendermint" "github.com/tendermint/tendermint/node" "github.com/tendermint/tendermint/types" cmn "github.com/tendermint/tmlibs/common" @@ -36,23 +37,23 @@ var ( func init() { // configuration options - runNodeCmd.Flags().StringVar(&moniker, "moniker", config.GetString("moniker"), + runNodeCmd.Flags().StringVar(&moniker, "moniker", config.GetString("node.moniker"), "Node Name") - runNodeCmd.Flags().StringVar(&nodeLaddr, "node_laddr", config.GetString("node_laddr"), + runNodeCmd.Flags().StringVar(&nodeLaddr, "node_laddr", config.GetString("node.listen_addr"), "Node listen address. (0.0.0.0:0 means any interface, any port)") - runNodeCmd.Flags().StringVar(&seeds, "seeds", config.GetString("seeds"), + runNodeCmd.Flags().StringVar(&seeds, "seeds", config.GetString("network.seeds"), "Comma delimited host:port seed nodes") - runNodeCmd.Flags().BoolVar(&fastSync, "fast_sync", config.GetBool("fast_sync"), + runNodeCmd.Flags().BoolVar(&fastSync, "fast_sync", config.GetBool("blockchain.fast_sync"), "Fast blockchain syncing") - runNodeCmd.Flags().BoolVar(&skipUPNP, "skip_upnp", config.GetBool("skip_upnp"), + runNodeCmd.Flags().BoolVar(&skipUPNP, "skip_upnp", config.GetBool("network.skip_upnp"), "Skip UPNP configuration") - runNodeCmd.Flags().StringVar(&rpcLaddr, "rpc_laddr", config.GetString("rpc_laddr"), + runNodeCmd.Flags().StringVar(&rpcLaddr, "rpc_laddr", config.GetString("rpc.listen_addr"), "RPC listen address. Port required") - runNodeCmd.Flags().StringVar(&grpcLaddr, "grpc_laddr", config.GetString("grpc_laddr"), + runNodeCmd.Flags().StringVar(&grpcLaddr, "grpc_laddr", config.GetString("grpc.listen_addr"), "GRPC listen address (BroadcastTx only). Port required") - runNodeCmd.Flags().StringVar(&proxyApp, "proxy_app", config.GetString("proxy_app"), + runNodeCmd.Flags().StringVar(&proxyApp, "proxy_app", config.GetString("abci.proxy_app"), "Proxy app address, or 'nilapp' or 'dummy' for local testing.") - runNodeCmd.Flags().StringVar(&abciTransport, "abci", config.GetString("abci"), + runNodeCmd.Flags().StringVar(&abciTransport, "abci", config.GetString("abci.mode"), "Specify abci transport (socket | grpc)") // feature flags @@ -65,16 +66,16 @@ func init() { func setConfigFlags(cmd *cobra.Command, args []string) { // Merge parsed flag values onto config - config.Set("moniker", moniker) - config.Set("node_laddr", nodeLaddr) - config.Set("seeds", seeds) - config.Set("fast_sync", fastSync) - config.Set("skip_upnp", skipUPNP) - config.Set("rpc_laddr", rpcLaddr) - config.Set("grpc_laddr", grpcLaddr) - config.Set("proxy_app", proxyApp) - config.Set("abci", abciTransport) - config.Set("pex_reactor", pex) + config.Set("node.moniker", moniker) + config.Set("node.listen_addr", nodeLaddr) + config.Set("network.seeds", seeds) + config.Set("network.skip_upnp", skipUPNP) + config.Set("network.pex_reactor", pex) + config.Set("blockchain.fast_sync", fastSync) + config.Set("rpc.listen_addr", rpcLaddr) + config.Set("rpc.grpc_listen_addr", grpcLaddr) + config.Set("abci.proxy_app", proxyApp) + config.Set("abci.mode", abciTransport) } // Users wishing to: @@ -113,7 +114,7 @@ func runNode(cmd *cobra.Command, args []string) error { } // Create & start node - n := node.NewNodeDefault(config) + n := node.NewNodeDefault(config) //tmConfig) if _, err := n.Start(); err != nil { return fmt.Errorf("Failed to start node: %v", err) } else { diff --git a/config/tendermint/config.go b/config/tendermint/config.go index 9011e0154..0ac3e1f74 100644 --- a/config/tendermint/config.go +++ b/config/tendermint/config.go @@ -53,59 +53,54 @@ func GetConfig(rootDir string) *viper.Viper { //config.WatchConfig() // Set defaults or panic - if config.IsSet("chain_id") { + if config.IsSet("chain.chain_id") { cmn.Exit("Cannot set 'chain_id' via config.toml") } - if config.IsSet("revision_file") { - cmn.Exit("Cannot set 'revision_file' via config.toml. It must match what's in the Makefile") - } //mapConfig.SetRequired("chain_id") // blows up if you try to use it before setting. - config.SetDefault("genesis_file", rootDir+"/genesis.json") - config.SetDefault("proxy_app", "tcp://127.0.0.1:46658") - config.SetDefault("abci", "socket") - config.SetDefault("moniker", "anonymous") - config.SetDefault("node_laddr", "tcp://0.0.0.0:46656") - config.SetDefault("seeds", "") - // config.SetDefault("seeds", "goldenalchemist.chaintest.net:46656") - config.SetDefault("fast_sync", true) - config.SetDefault("skip_upnp", false) - config.SetDefault("addrbook_file", rootDir+"/addrbook.json") - config.SetDefault("addrbook_strict", true) // disable to allow connections locally - config.SetDefault("pex_reactor", false) // enable for peer exchange - config.SetDefault("priv_validator_file", rootDir+"/priv_validator.json") - config.SetDefault("db_backend", "leveldb") - config.SetDefault("db_dir", rootDir+"/data") - config.SetDefault("log_level", "info") - config.SetDefault("rpc_laddr", "tcp://0.0.0.0:46657") - config.SetDefault("grpc_laddr", "") - config.SetDefault("prof_laddr", "") - config.SetDefault("revision_file", rootDir+"/revision") - config.SetDefault("cs_wal_file", rootDir+"/data/cs.wal/wal") - config.SetDefault("cs_wal_light", false) - config.SetDefault("filter_peers", false) + config.SetDefault("node.moniker", "anonymous") + config.SetDefault("node.log_level", "info") + config.SetDefault("node.prof_laddr", "") + config.SetDefault("chain.genesis_file", rootDir+"/genesis.json") + config.SetDefault("abci.proxy_app", "tcp://127.0.0.1:46658") + config.SetDefault("abci.mode", "socket") + config.SetDefault("abci.filter_peers", false) + config.SetDefault("network.listen_addr", "tcp://0.0.0.0:46656") + config.SetDefault("network.seeds", "") + config.SetDefault("network.skip_upnp", false) + config.SetDefault("blockchain.fast_sync", true) + config.SetDefault("network.addrbook_file", rootDir+"/addrbook.json") + config.SetDefault("network.addrbook_strict", true) // disable to allow connections locally + config.SetDefault("network.pex_reactor", false) // enable for peer exchange + config.SetDefault("node.priv_validator_file", rootDir+"/priv_validator.json") + config.SetDefault("db.backend", "leveldb") + config.SetDefault("db.dir", rootDir+"/data") + config.SetDefault("rpc.listen_addr", "tcp://0.0.0.0:46657") + config.SetDefault("rpc.grpc_listen_addr", "") + config.SetDefault("consensus.wal_file", rootDir+"/data/cs.wal/wal") + config.SetDefault("consensus.wal_light", false) - config.SetDefault("block_size", 10000) // max number of txs - config.SetDefault("block_part_size", 65536) // part size 64K - config.SetDefault("disable_data_hash", false) + config.SetDefault("block.max_txs", 10000) // max number of txs + config.SetDefault("block.part_size", 65536) // part size 64K + config.SetDefault("block.disable_data_hash", false) // all timeouts are in ms - config.SetDefault("timeout_handshake", 10000) - config.SetDefault("timeout_propose", 3000) - config.SetDefault("timeout_propose_delta", 500) - config.SetDefault("timeout_prevote", 1000) - config.SetDefault("timeout_prevote_delta", 500) - config.SetDefault("timeout_precommit", 1000) - config.SetDefault("timeout_precommit_delta", 500) - config.SetDefault("timeout_commit", 1000) + config.SetDefault("consensus.timeout_handshake", 10000) + config.SetDefault("consensus.timeout_propose", 3000) + config.SetDefault("consensus.timeout_propose_delta", 500) + config.SetDefault("consensus.timeout_prevote", 1000) + config.SetDefault("consensus.timeout_prevote_delta", 500) + config.SetDefault("consensus.timeout_precommit", 1000) + config.SetDefault("consensus.timeout_precommit_delta", 500) + config.SetDefault("consensus.timeout_commit", 1000) // make progress asap (no `timeout_commit`) on full precommit votes - config.SetDefault("skip_timeout_commit", false) - config.SetDefault("mempool_recheck", true) - config.SetDefault("mempool_recheck_empty", true) - config.SetDefault("mempool_broadcast", true) - config.SetDefault("mempool_wal_dir", rootDir+"/data/mempool.wal") + config.SetDefault("consensus.skip_timeout_commit", false) + config.SetDefault("mempool.recheck", true) + config.SetDefault("mempool.recheck_empty", true) + config.SetDefault("mempool.broadcast", true) + config.SetDefault("mempool.wal_dir", rootDir+"/data/mempool.wal") - config.SetDefault("tx_index", "kv") + config.SetDefault("db.tx_index", "kv") return config } diff --git a/config/tendermint/types.go b/config/tendermint/types.go new file mode 100644 index 000000000..7f0d421d8 --- /dev/null +++ b/config/tendermint/types.go @@ -0,0 +1,89 @@ +package tendermint + +type Config struct { + Node NodeConfig `mapstructure:"node"` + Chain ChainConfig `mapstructure:"chain"` + ABCI ABCIConfig `mapstructure:"abci"` + Network NetworkConfig `mapstructure:"network"` + Blockchain BlockchainConfig `mapstructure:"blockchain"` + Consensus ConsensusConfig `mapstructure:"consensus"` + Block BlockConfig `mapstructure:"block"` + Mempool MempoolConfig `mapstructure:"mempool"` + RPC RPCConfig `mapstructure:"rpc"` + DB DBConfig `mapstructure:"db"` +} + +type NodeConfig struct { + Moniker string `mapstructure:"moniker"` // "anonymous" + PrivValidatorFile string `mapstructure:"priv_validator_file"` // rootDir+"/priv_validator.json") + + LogLevel string `mapstructure:"log_level"` // info + ProfListenAddr string `mapstructure:"prof_laddr"` // "" +} + +type ChainConfig struct { + ChainID string `mapstructure:"chain_id"` + GenesisFile string `mapstructure:"genesis_file"` // rootDir/genesis.json +} + +type ABCIConfig struct { + ProxyApp string `mapstructure:"proxy_app"` // tcp://0.0.0.0:46658 + Mode string `mapstructure:"mode"` // socket + + FilterPeers bool `mapstructure:"filter_peers"` // false +} + +type NetworkConfig struct { + ListenAddr string `mapstructure:"listen_adddr"` // "tcp://0.0.0.0:46656") + Seeds string `mapstructure:"seeds"` // []string ... + SkipUPNP bool `mapstructure:"skip_upnp"` + AddrBookFile string `mapstructure:"addr_book_file"` // rootDir+"/addrbook.json") + AddrBookString bool `mapstructure:"addr_book_string"` // true + PexReactor bool `mapstructure:"pex_reactor"` // false +} + +type BlockchainConfig struct { + FastSync bool `mapstructure:"fast_sync"` // true +} + +type ConsensusConfig struct { + WalFile string `mapstructure:"wal_file"` //rootDir+"/data/cs.wal/wal") + WalLight bool `mapstructure:"wal_light"` // false + + // all timeouts are in ms + TimeoutPropose int `mapstructure:"timeout_propose"` // 3000 + TimeoutProposeDelta int `mapstructure:"timeout_propose_delta"` // 500 + TimeoutPrevote int `mapstructure:"timeout_prevote"` // 1000 + TimeoutPrevoteDelta int `mapstructure:"timeout_prevote_delta"` // 500 + TimeoutPrecommit int `mapstructure:"timeout_precommit"` // 1000 + TimeoutPrecommitDelta int `mapstructure:"timeout_precommit_delta"` // 500 + TimeoutCommit int `mapstructure:"timeout_commit"` // 1000 + + // make progress asap (no `timeout_commit`) on full precommit votes + SkipTimeoutCommit bool `mapstructure:"skip_timeout_commit"` // false +} + +type BlockConfig struct { + MaxTxs int `mapstructure:"max_txs"` // 10000 + PartSize int `mapstructure:"part_size"` // 65536 + DisableDataHash bool `mapstructure:"disable_data_hash"` // false +} + +type MempoolConfig struct { + Recheck bool `mapstructure:"recheck"` // true + RecheckEmpty bool `mapstructure:"recheck_empty"` // true + Broadcast bool `mapstructure:"broadcast"` // true + WalDir string `mapstructure:"wal_dir"` // rootDir+"/data/mempool.wal") +} + +type RPCConfig struct { + RPCListenAddress string `mapstructure:"rpc_listen_addr"` // "tcp://0.0.0.0:46657") + GRPCListenAddress string `mapstructure:"grpc_listen_addr"` // "" +} + +type DBConfig struct { + Backend string `mapstructure:"backend"` // leveldb + Dir string `mapstructure:"dir"` // rootDir/data + + TxIndex string `mapstructure:"tx_index"` // "kv" +} diff --git a/node/node.go b/node/node.go index 764c89b87..c4000a1fe 100644 --- a/node/node.go +++ b/node/node.go @@ -13,6 +13,7 @@ import ( crypto "github.com/tendermint/go-crypto" wire "github.com/tendermint/go-wire" bc "github.com/tendermint/tendermint/blockchain" + tmcfg "github.com/tendermint/tendermint/config/tendermint" "github.com/tendermint/tendermint/consensus" mempl "github.com/tendermint/tendermint/mempool" p2p "github.com/tendermint/tendermint/p2p" @@ -67,21 +68,26 @@ func NewNodeDefault(config *viper.Viper) *Node { config.GetString("abci"), config.GetString("db_dir"), )) + // config.ABCI.ProxyApp, config.ABCI.Mode, config.DB.Dir)) } func NewNode(config *viper.Viper, privValidator *types.PrivValidator, clientCreator proxy.ClientCreator) *Node { + tmConfig := new(tmcfg.Config) + if err := config.Unmarshal(tmConfig); err != nil { + panic(err) + } + // Get BlockStore - blockStoreDB := dbm.NewDB("blockstore", config.GetString("db_backend"), config.GetString("db_dir")) + blockStoreDB := dbm.NewDB("blockstore", tmConfig.DB.Backend, tmConfig.DB.Dir) blockStore := bc.NewBlockStore(blockStoreDB) // Get State - stateDB := dbm.NewDB("state", config.GetString("db_backend"), config.GetString("db_dir")) - state := sm.GetState(stateDB, config.GetString("genesis_file")) + stateDB := dbm.NewDB("state", tmConfig.DB.Backend, tmConfig.DB.Dir) + state := sm.GetState(stateDB, tmConfig.Chain.GenesisFile) // add the chainid and number of validators to the global config config.Set("chain_id", state.ChainID) - config.Set("num_vals", state.Validators.Size()) // Create the proxyApp, which manages connections (consensus, mempool, query) // and sync tendermint and the app by replaying any necessary blocks @@ -95,9 +101,9 @@ func NewNode(config *viper.Viper, privValidator *types.PrivValidator, clientCrea // Transaction indexing var txIndexer txindex.TxIndexer - switch config.GetString("tx_index") { + switch tmConfig.DB.TxIndex { case "kv": - store := dbm.NewDB("tx_index", config.GetString("db_backend"), config.GetString("db_dir")) + store := dbm.NewDB("tx_index", tmConfig.DB.Backend, tmConfig.DB.Dir) txIndexer = kv.NewTxIndex(store) default: txIndexer = &null.TxIndex{} From 75b6c5215f8db613f1a8451f63a3ccbb93f8c2c5 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Mon, 1 May 2017 20:09:29 -0400 Subject: [PATCH 255/309] fewer structs. remove viper from consensus --- blockchain/reactor.go | 2 +- cmd/tendermint/commands/init.go | 10 +- cmd/tendermint/commands/replay.go | 24 +-- .../commands/reset_priv_validator.go | 6 +- cmd/tendermint/commands/root.go | 33 +++- cmd/tendermint/commands/run_node.go | 82 +++++---- cmd/tendermint/commands/show_validator.go | 4 +- config/config.go | 73 ++++++++ config/tendermint/types.go | 89 ---------- consensus/common_test.go | 1 + consensus/replay_file.go | 24 ++- consensus/state.go | 163 +++++++++++------- mempool/mempool.go | 4 +- mempool/reactor.go | 21 ++- node/node.go | 113 ++++++------ p2p/config.go | 17 ++ types/block.go | 4 +- 17 files changed, 371 insertions(+), 299 deletions(-) create mode 100644 config/config.go delete mode 100644 config/tendermint/types.go diff --git a/blockchain/reactor.go b/blockchain/reactor.go index 0d51d124c..b39de838d 100644 --- a/blockchain/reactor.go +++ b/blockchain/reactor.go @@ -222,7 +222,7 @@ FOR_LOOP: // We need both to sync the first block. break SYNC_LOOP } - firstParts := first.MakePartSet(types.DefaultPartSetSize) + firstParts := first.MakePartSet(types.DefaultBlockPartSize) firstPartsHeader := firstParts.Header() // Finally, verify the first block using the second's commit // NOTE: we can probably make this more efficient, but note that calling diff --git a/cmd/tendermint/commands/init.go b/cmd/tendermint/commands/init.go index 75bc2bf95..bb8aa45dc 100644 --- a/cmd/tendermint/commands/init.go +++ b/cmd/tendermint/commands/init.go @@ -5,8 +5,8 @@ import ( "github.com/spf13/cobra" - cmn "github.com/tendermint/tmlibs/common" "github.com/tendermint/tendermint/types" + cmn "github.com/tendermint/tmlibs/common" ) var initFilesCmd = &cobra.Command{ @@ -20,13 +20,13 @@ func init() { } func initFiles(cmd *cobra.Command, args []string) { - privValFile := config.GetString("priv_validator_file") + privValFile := config.PrivValidatorFile if _, err := os.Stat(privValFile); os.IsNotExist(err) { privValidator := types.GenPrivValidator() privValidator.SetFile(privValFile) privValidator.Save() - genFile := config.GetString("genesis_file") + genFile := config.GenesisFile if _, err := os.Stat(genFile); os.IsNotExist(err) { genDoc := types.GenesisDoc{ @@ -40,8 +40,8 @@ func initFiles(cmd *cobra.Command, args []string) { genDoc.SaveAs(genFile) } - log.Notice("Initialized tendermint", "genesis", config.GetString("genesis_file"), "priv_validator", config.GetString("priv_validator_file")) + log.Notice("Initialized tendermint", "genesis", config.GenesisFile, "priv_validator", config.PrivValidatorFile) } else { - log.Notice("Already initialized", "priv_validator", config.GetString("priv_validator_file")) + log.Notice("Already initialized", "priv_validator", config.PrivValidatorFile) } } diff --git a/cmd/tendermint/commands/replay.go b/cmd/tendermint/commands/replay.go index 2f0e3266e..611a96a63 100644 --- a/cmd/tendermint/commands/replay.go +++ b/cmd/tendermint/commands/replay.go @@ -1,36 +1,26 @@ package commands import ( - "fmt" + "github.com/spf13/cobra" "github.com/tendermint/tendermint/consensus" - - "github.com/spf13/cobra" ) var replayCmd = &cobra.Command{ - Use: "replay [walfile]", + Use: "replay", Short: "Replay messages from WAL", Run: func(cmd *cobra.Command, args []string) { - - if len(args) > 1 { - consensus.RunReplayFile(config, args[1], false) - } else { - fmt.Println("replay requires an argument (walfile)") - } + config := getConfig() + consensus.RunReplayFile(config.Config, config.Consensus, false) }, } var replayConsoleCmd = &cobra.Command{ - Use: "replay_console [walfile]", + Use: "replay_console", Short: "Replay messages from WAL in a console", Run: func(cmd *cobra.Command, args []string) { - - if len(args) > 1 { - consensus.RunReplayFile(config, args[1], true) - } else { - fmt.Println("replay_console requires an argument (walfile)") - } + config := getConfig() + consensus.RunReplayFile(config.Config, config.Consensus, true) }, } diff --git a/cmd/tendermint/commands/reset_priv_validator.go b/cmd/tendermint/commands/reset_priv_validator.go index 448a1869f..8f03c11d5 100644 --- a/cmd/tendermint/commands/reset_priv_validator.go +++ b/cmd/tendermint/commands/reset_priv_validator.go @@ -29,13 +29,15 @@ func init() { // XXX: this is totally unsafe. // it's only suitable for testnets. func resetAll(cmd *cobra.Command, args []string) { - ResetAll(config.GetString("db_dir"), config.GetString("priv_validator_file"), log) + config := getConfig() + ResetAll(config.DBDir, config.PrivValidatorFile, log) } // XXX: this is totally unsafe. // it's only suitable for testnets. func resetPrivValidator(cmd *cobra.Command, args []string) { - resetPrivValidatorLocal(config.GetString("priv_validator_file"), log) + config := getConfig() + resetPrivValidatorLocal(config.PrivValidatorFile, log) } // Exported so other CLI tools can use it diff --git a/cmd/tendermint/commands/root.go b/cmd/tendermint/commands/root.go index 4a97c44fd..515ef9dc6 100644 --- a/cmd/tendermint/commands/root.go +++ b/cmd/tendermint/commands/root.go @@ -2,16 +2,34 @@ package commands import ( "github.com/spf13/cobra" + "github.com/spf13/viper" - tmcfg "github.com/tendermint/tendermint/config/tendermint" + "github.com/tendermint/tendermint/node" "github.com/tendermint/tmlibs/logger" ) var ( - config = tmcfg.GetConfig("") - log = logger.New("module", "main") + viperConfig *viper.Viper + config *node.Config + log = logger.New("module", "main") ) +func init() { + // Set config to be used as defaults by flags. + // This will be overwritten by whatever is unmarshalled from viper + config = node.NewDefaultConfig("") + +} + +// unmarshal viper into the Tendermint config +func getConfig() *node.Config { + config := new(node.Config) + if err := viperConfig.Unmarshal(config); err != nil { + panic(err) + } + return config +} + //global flag var logLevel string @@ -19,13 +37,14 @@ var RootCmd = &cobra.Command{ Use: "tendermint", Short: "Tendermint Core (BFT Consensus) in Go", PersistentPreRun: func(cmd *cobra.Command, args []string) { - // set the log level in the config and logger - config.Set("node.log_level", logLevel) - logger.SetLogLevel(logLevel) + // set the log level + config := getConfig() + logger.SetLogLevel(config.LogLevel) }, } func init() { //parse flag and set config - RootCmd.PersistentFlags().StringVar(&logLevel, "log_level", config.GetString("node.log_level"), "Log level") + RootCmd.PersistentFlags().StringVar(&logLevel, "log_level", config.LogLevel, "Log level") + viperConfig.BindPFlag("log_level", RootCmd.Flags().Lookup("log_level")) } diff --git a/cmd/tendermint/commands/run_node.go b/cmd/tendermint/commands/run_node.go index 2ddc50a02..c4d06efbf 100644 --- a/cmd/tendermint/commands/run_node.go +++ b/cmd/tendermint/commands/run_node.go @@ -14,10 +14,9 @@ import ( ) var runNodeCmd = &cobra.Command{ - Use: "node", - Short: "Run the tendermint node", - PreRun: setConfigFlags, - RunE: runNode, + Use: "node", + Short: "Run the tendermint node", + RunE: runNode, } //flags @@ -35,49 +34,55 @@ var ( ) func init() { + // bind flags - // configuration options - runNodeCmd.Flags().StringVar(&moniker, "moniker", config.GetString("node.moniker"), + // node flags + runNodeCmd.Flags().StringVar(&moniker, "moniker", config.Moniker, "Node Name") - runNodeCmd.Flags().StringVar(&nodeLaddr, "node_laddr", config.GetString("node.listen_addr"), - "Node listen address. (0.0.0.0:0 means any interface, any port)") - runNodeCmd.Flags().StringVar(&seeds, "seeds", config.GetString("network.seeds"), - "Comma delimited host:port seed nodes") - runNodeCmd.Flags().BoolVar(&fastSync, "fast_sync", config.GetBool("blockchain.fast_sync"), + viperConfig.BindPFlag("moniker", runNodeCmd.Flags().Lookup("moniker")) + + runNodeCmd.Flags().BoolVar(&fastSync, "fast_sync", config.FastSync, "Fast blockchain syncing") - runNodeCmd.Flags().BoolVar(&skipUPNP, "skip_upnp", config.GetBool("network.skip_upnp"), - "Skip UPNP configuration") - runNodeCmd.Flags().StringVar(&rpcLaddr, "rpc_laddr", config.GetString("rpc.listen_addr"), - "RPC listen address. Port required") - runNodeCmd.Flags().StringVar(&grpcLaddr, "grpc_laddr", config.GetString("grpc.listen_addr"), - "GRPC listen address (BroadcastTx only). Port required") - runNodeCmd.Flags().StringVar(&proxyApp, "proxy_app", config.GetString("abci.proxy_app"), + viperConfig.BindPFlag("fast_sync", runNodeCmd.Flags().Lookup("fast_sync")) + + // abci flags + runNodeCmd.Flags().StringVar(&proxyApp, "proxy_app", config.ProxyApp, "Proxy app address, or 'nilapp' or 'dummy' for local testing.") - runNodeCmd.Flags().StringVar(&abciTransport, "abci", config.GetString("abci.mode"), + viperConfig.BindPFlag("proxy_app", runNodeCmd.Flags().Lookup("proxy_app")) + + runNodeCmd.Flags().StringVar(&abciTransport, "abci", config.ABCI, "Specify abci transport (socket | grpc)") + viperConfig.BindPFlag("abci", runNodeCmd.Flags().Lookup("abci")) + + // rpc flags + runNodeCmd.Flags().StringVar(&rpcLaddr, "rpc_laddr", config.RPCListenAddress, + "RPC listen address. Port required") + viperConfig.BindPFlag("rpc_laddr", runNodeCmd.Flags().Lookup("rpc_laddr")) + + runNodeCmd.Flags().StringVar(&grpcLaddr, "grpc_laddr", config.GRPCListenAddress, + "GRPC listen address (BroadcastTx only). Port required") + viperConfig.BindPFlag("grpc_laddr", runNodeCmd.Flags().Lookup("grpc_laddr")) + + // p2p flags + runNodeCmd.Flags().StringVar(&nodeLaddr, "p2p.laddr", config.P2P.ListenAddress, + "Node listen address. (0.0.0.0:0 means any interface, any port)") + viperConfig.BindPFlag("p2p.laddr", runNodeCmd.Flags().Lookup("p2p.laddr")) + + runNodeCmd.Flags().StringVar(&seeds, "p2p.seeds", config.P2P.Seeds, + "Comma delimited host:port seed nodes") + viperConfig.BindPFlag("p2p.seeds", runNodeCmd.Flags().Lookup("p2p.seeds")) + + runNodeCmd.Flags().BoolVar(&skipUPNP, "p2p.skip_upnp", config.P2P.SkipUPNP, + "Skip UPNP configuration") + viperConfig.BindPFlag("p2p.skip_upnp", runNodeCmd.Flags().Lookup("p2p.skip_upnp")) // feature flags - runNodeCmd.Flags().BoolVar(&pex, "pex", config.GetBool("pex_reactor"), + runNodeCmd.Flags().BoolVar(&pex, "p2p.pex", config.P2P.PexReactor, "Enable Peer-Exchange (dev feature)") RootCmd.AddCommand(runNodeCmd) } -func setConfigFlags(cmd *cobra.Command, args []string) { - - // Merge parsed flag values onto config - config.Set("node.moniker", moniker) - config.Set("node.listen_addr", nodeLaddr) - config.Set("network.seeds", seeds) - config.Set("network.skip_upnp", skipUPNP) - config.Set("network.pex_reactor", pex) - config.Set("blockchain.fast_sync", fastSync) - config.Set("rpc.listen_addr", rpcLaddr) - config.Set("rpc.grpc_listen_addr", grpcLaddr) - config.Set("abci.proxy_app", proxyApp) - config.Set("abci.mode", abciTransport) -} - // Users wishing to: // * Use an external signer for their validators // * Supply an in-proc abci app @@ -90,7 +95,7 @@ func runNode(cmd *cobra.Command, args []string) error { // This is for Mintnet compatibility. // TODO: If Mintnet gets deprecated or genesis_file is // always available, remove. - genDocFile := config.GetString("genesis_file") + genDocFile := config.GenesisFile if !cmn.FileExists(genDocFile) { log.Notice(cmn.Fmt("Waiting for genesis file %v...", genDocFile)) for { @@ -109,12 +114,13 @@ func runNode(cmd *cobra.Command, args []string) error { if genDoc.ChainID == "" { return fmt.Errorf("Genesis doc %v must include non-empty chain_id", genDocFile) } - config.Set("chain_id", genDoc.ChainID) + + // config.SetChainID("chain_id", genDoc.ChainID) TODO } } // Create & start node - n := node.NewNodeDefault(config) //tmConfig) + n := node.NewNodeDefault(getConfig()) if _, err := n.Start(); err != nil { return fmt.Errorf("Failed to start node: %v", err) } else { diff --git a/cmd/tendermint/commands/show_validator.go b/cmd/tendermint/commands/show_validator.go index 951fd5a8c..16dfe1ff4 100644 --- a/cmd/tendermint/commands/show_validator.go +++ b/cmd/tendermint/commands/show_validator.go @@ -20,8 +20,8 @@ func init() { } func showValidator(cmd *cobra.Command, args []string) { - privValidatorFile := config.GetString("priv_validator_file") - privValidator := types.LoadOrGenPrivValidator(privValidatorFile) + config := getConfig() + privValidator := types.LoadOrGenPrivValidator(config.PrivValidatorFile) pubKeyJSONBytes, _ := data.ToJSON(privValidator.PubKey) fmt.Println(string(pubKeyJSONBytes)) } diff --git a/config/config.go b/config/config.go new file mode 100644 index 000000000..5f4f28a83 --- /dev/null +++ b/config/config.go @@ -0,0 +1,73 @@ +package config + +// Config struct for a Tendermint node +type Config struct { + // The ID of the chain to join (should be signed with every transaction and vote) + ChainID string `mapstructure:"chain_id"` + + // A JSON file containing the initial validator set and other meta data + GenesisFile string `mapstructure:"genesis_file"` + + // A JSON file containing the private key to use as a validator in the consensus protocol + PrivValidatorFile string `mapstructure:"priv_validator_file"` + + // A custom human readable name for this node + Moniker string `mapstructure:"moniker"` + + // TCP or UNIX socket address of the ABCI application, + // or the name of an ABCI application compiled in with the Tendermint binary + ProxyApp string `mapstructure:"proxy_app"` + + // Mechanism to connect to the ABCI application: socket | grpc + ABCI string `mapstructure:"abci"` + + // Output level for logging + LogLevel string `mapstructure:"log_level"` + + // TCP or UNIX socket address for the profiling server to listen on + ProfListenAddress string `mapstructure:"prof_laddr"` + + // If this node is many blocks behind the tip of the chain, FastSync + // allows them to catchup quickly by downloading blocks in parallel + // and verifying their commits + FastSync bool `mapstructure:"fast_sync"` + + // If true, query the ABCI app on connecting to a new peer + // so the app can decide if we should keep the connection or not + FilterPeers bool `mapstructure:"filter_peers"` // false + + // What indexer to use for transactions + TxIndex string `mapstructure:"tx_index"` + + // Database backend: leveldb | memdb + DBBackend string `mapstructure:"db_backend"` + + // Database directory + DBDir string `mapstructure:"db_dir"` + + // TCP or UNIX socket address for the RPC server to listen on + RPCListenAddress string `mapstructure:"rpc_laddr"` + + // TCP or UNIX socket address for the gRPC server to listen on + // NOTE: This server only supports /broadcast_tx_commit + GRPCListenAddress string `mapstructure:"grpc_laddr"` +} + +func NewDefaultConfig(rootDir string) *Config { + return &Config{ + GenesisFile: rootDir + "/genesis.json", + PrivValidatorFile: rootDir + "/priv_validator.json", + Moniker: "anonymous", + ProxyApp: "tcp://127.0.0.1:46658", + ABCI: "socket", + LogLevel: "info", + ProfListenAddress: "", + FastSync: true, + FilterPeers: false, + TxIndex: "kv", + DBBackend: "leveldb", + DBDir: rootDir + "/data", + RPCListenAddress: "tcp://0.0.0.0:46657", + GRPCListenAddress: "", + } +} diff --git a/config/tendermint/types.go b/config/tendermint/types.go deleted file mode 100644 index 7f0d421d8..000000000 --- a/config/tendermint/types.go +++ /dev/null @@ -1,89 +0,0 @@ -package tendermint - -type Config struct { - Node NodeConfig `mapstructure:"node"` - Chain ChainConfig `mapstructure:"chain"` - ABCI ABCIConfig `mapstructure:"abci"` - Network NetworkConfig `mapstructure:"network"` - Blockchain BlockchainConfig `mapstructure:"blockchain"` - Consensus ConsensusConfig `mapstructure:"consensus"` - Block BlockConfig `mapstructure:"block"` - Mempool MempoolConfig `mapstructure:"mempool"` - RPC RPCConfig `mapstructure:"rpc"` - DB DBConfig `mapstructure:"db"` -} - -type NodeConfig struct { - Moniker string `mapstructure:"moniker"` // "anonymous" - PrivValidatorFile string `mapstructure:"priv_validator_file"` // rootDir+"/priv_validator.json") - - LogLevel string `mapstructure:"log_level"` // info - ProfListenAddr string `mapstructure:"prof_laddr"` // "" -} - -type ChainConfig struct { - ChainID string `mapstructure:"chain_id"` - GenesisFile string `mapstructure:"genesis_file"` // rootDir/genesis.json -} - -type ABCIConfig struct { - ProxyApp string `mapstructure:"proxy_app"` // tcp://0.0.0.0:46658 - Mode string `mapstructure:"mode"` // socket - - FilterPeers bool `mapstructure:"filter_peers"` // false -} - -type NetworkConfig struct { - ListenAddr string `mapstructure:"listen_adddr"` // "tcp://0.0.0.0:46656") - Seeds string `mapstructure:"seeds"` // []string ... - SkipUPNP bool `mapstructure:"skip_upnp"` - AddrBookFile string `mapstructure:"addr_book_file"` // rootDir+"/addrbook.json") - AddrBookString bool `mapstructure:"addr_book_string"` // true - PexReactor bool `mapstructure:"pex_reactor"` // false -} - -type BlockchainConfig struct { - FastSync bool `mapstructure:"fast_sync"` // true -} - -type ConsensusConfig struct { - WalFile string `mapstructure:"wal_file"` //rootDir+"/data/cs.wal/wal") - WalLight bool `mapstructure:"wal_light"` // false - - // all timeouts are in ms - TimeoutPropose int `mapstructure:"timeout_propose"` // 3000 - TimeoutProposeDelta int `mapstructure:"timeout_propose_delta"` // 500 - TimeoutPrevote int `mapstructure:"timeout_prevote"` // 1000 - TimeoutPrevoteDelta int `mapstructure:"timeout_prevote_delta"` // 500 - TimeoutPrecommit int `mapstructure:"timeout_precommit"` // 1000 - TimeoutPrecommitDelta int `mapstructure:"timeout_precommit_delta"` // 500 - TimeoutCommit int `mapstructure:"timeout_commit"` // 1000 - - // make progress asap (no `timeout_commit`) on full precommit votes - SkipTimeoutCommit bool `mapstructure:"skip_timeout_commit"` // false -} - -type BlockConfig struct { - MaxTxs int `mapstructure:"max_txs"` // 10000 - PartSize int `mapstructure:"part_size"` // 65536 - DisableDataHash bool `mapstructure:"disable_data_hash"` // false -} - -type MempoolConfig struct { - Recheck bool `mapstructure:"recheck"` // true - RecheckEmpty bool `mapstructure:"recheck_empty"` // true - Broadcast bool `mapstructure:"broadcast"` // true - WalDir string `mapstructure:"wal_dir"` // rootDir+"/data/mempool.wal") -} - -type RPCConfig struct { - RPCListenAddress string `mapstructure:"rpc_listen_addr"` // "tcp://0.0.0.0:46657") - GRPCListenAddress string `mapstructure:"grpc_listen_addr"` // "" -} - -type DBConfig struct { - Backend string `mapstructure:"backend"` // leveldb - Dir string `mapstructure:"dir"` // rootDir/data - - TxIndex string `mapstructure:"tx_index"` // "kv" -} diff --git a/consensus/common_test.go b/consensus/common_test.go index 1443232a6..7ebef78e9 100644 --- a/consensus/common_test.go +++ b/consensus/common_test.go @@ -28,6 +28,7 @@ import ( "github.com/tendermint/abci/example/dummy" ) +// genesis, chain_id, priv_val var config *viper.Viper // NOTE: must be reset for each _test.go file var ensureTimeout = time.Duration(2) diff --git a/consensus/replay_file.go b/consensus/replay_file.go index 1f4de893a..4e0f40b65 100644 --- a/consensus/replay_file.go +++ b/consensus/replay_file.go @@ -8,9 +8,8 @@ import ( "strconv" "strings" - "github.com/spf13/viper" - bc "github.com/tendermint/tendermint/blockchain" + cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/proxy" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" @@ -21,10 +20,10 @@ import ( //-------------------------------------------------------- // replay messages interactively or all at once -func RunReplayFile(config *viper.Viper, walFile string, console bool) { - consensusState := newConsensusStateForReplay(config) +func RunReplayFile(config *cfg.Config, csConfig *Config, console bool) { + consensusState := newConsensusStateForReplay(config, csConfig) - if err := consensusState.ReplayFile(walFile, console); err != nil { + if err := consensusState.ReplayFile(csConfig.WalFile, console); err != nil { cmn.Exit(cmn.Fmt("Error during consensus replay: %v", err)) } } @@ -236,33 +235,30 @@ func (pb *playback) replayConsoleLoop() int { //-------------------------------------------------------------------------------- // convenience for replay mode -func newConsensusStateForReplay(config *viper.Viper) *ConsensusState { +func newConsensusStateForReplay(config *cfg.Config, csConfig *Config) *ConsensusState { // Get BlockStore - blockStoreDB := dbm.NewDB("blockstore", config.GetString("db_backend"), config.GetString("db_dir")) + blockStoreDB := dbm.NewDB("blockstore", config.DBBackend, config.DBDir) blockStore := bc.NewBlockStore(blockStoreDB) // Get State - stateDB := dbm.NewDB("state", config.GetString("db_backend"), config.GetString("db_dir")) - state := sm.MakeGenesisStateFromFile(stateDB, config.GetString("genesis_file")) + stateDB := dbm.NewDB("state", config.DBBackend, config.DBDir) + state := sm.MakeGenesisStateFromFile(stateDB, config.GenesisFile) // Create proxyAppConn connection (consensus, mempool, query) - clientCreator := proxy.DefaultClientCreator(config.GetString("proxy_app"), config.GetString("abci"), config.GetString("db_dir")) + clientCreator := proxy.DefaultClientCreator(config.ProxyApp, config.ABCI, config.DBDir) proxyApp := proxy.NewAppConns(clientCreator, NewHandshaker(state, blockStore)) _, err := proxyApp.Start() if err != nil { cmn.Exit(cmn.Fmt("Error starting proxy app conns: %v", err)) } - // add the chainid to the global config - config.Set("chain_id", state.ChainID) - // Make event switch eventSwitch := types.NewEventSwitch() if _, err := eventSwitch.Start(); err != nil { cmn.Exit(cmn.Fmt("Failed to start event switch: %v", err)) } - consensusState := NewConsensusState(config, state.Copy(), proxyApp.Consensus(), blockStore, types.MockMempool{}) + consensusState := NewConsensusState(csConfig, state.Copy(), proxyApp.Consensus(), blockStore, types.MockMempool{}) consensusState.SetEventSwitch(eventSwitch) return consensusState } diff --git a/consensus/state.go b/consensus/state.go index 28836a079..a77e8a669 100644 --- a/consensus/state.go +++ b/consensus/state.go @@ -10,7 +10,6 @@ import ( "time" "github.com/ebuchman/fail-test" - "github.com/spf13/viper" "github.com/tendermint/go-wire" "github.com/tendermint/tendermint/proxy" @@ -20,53 +19,90 @@ import ( ) //----------------------------------------------------------------------------- -// Timeout Parameters +// Config -// TimeoutParams holds timeouts and deltas for each round step. -// All timeouts and deltas in milliseconds. -type TimeoutParams struct { - Propose0 int - ProposeDelta int - Prevote0 int - PrevoteDelta int - Precommit0 int - PrecommitDelta int - Commit0 int - SkipTimeoutCommit bool +// Config holds timeouts and details about the WAL, the block structure, +// and timeouts in the consensus protocol. +type Config struct { + WalFile string `mapstructure:"wal_file"` + WalLight bool `mapstructure:"wal_light"` + + // All timeouts are in ms + TimeoutPropose int `mapstructure:"timeout_propose"` + TimeoutProposeDelta int `mapstructure:"timeout_propose_delta"` + TimeoutPrevote int `mapstructure:"timeout_prevote"` + TimeoutPrevoteDelta int `mapstructure:"timeout_prevote_delta"` + TimeoutPrecommit int `mapstructure:"timeout_precommit"` + TimeoutPrecommitDelta int `mapstructure:"timeout_precommit_delta"` + TimeoutCommit int `mapstructure:"timeout_commit"` + + // Make progress as soon as we have all the precommits (as if TimeoutCommit = 0) + SkipTimeoutCommit bool `mapstructure:"skip_timeout_commit"` + + // BlockSize + MaxBlockSizeTxs int `mapstructure:"block_size_txs"` + MaxBlockSizeBytes int `mapstructure:"block_size_bytes"` + + // TODO: This probably shouldn't be exposed but it makes it + // easy to write tests for the wal/replay + BlockPartSize int `mapstructure:"block_part_size"` + + chainID string +} + +func NewDefaultConfig(rootDir string) *Config { + return &Config{ + WalFile: rootDir + "/data/cs.wal/wal", + WalLight: false, + TimeoutPropose: 3000, + TimeoutProposeDelta: 500, + TimeoutPrevote: 1000, + TimeoutPrevoteDelta: 500, + TimeoutPrecommit: 1000, + TimeoutPrecommitDelta: 500, + TimeoutCommit: 1000, + SkipTimeoutCommit: false, + MaxBlockSizeTxs: 10000, + MaxBlockSizeBytes: 1, // TODO + BlockPartSize: types.DefaultBlockPartSize, + } +} + +func NewTestConfig(rootDir string) *Config { + config := NewDefaultConfig(rootDir) + config.TimeoutPropose = 2000 + config.TimeoutProposeDelta = 1 + config.TimeoutPrevote = 10 + config.TimeoutPrevoteDelta = 1 + config.TimeoutPrecommit = 10 + config.TimeoutPrecommitDelta = 1 + config.TimeoutCommit = 10 + config.SkipTimeoutCommit = true + return config +} + +func (cfg *Config) SetChainID(chainID string) { + cfg.chainID = chainID } // Wait this long for a proposal -func (tp *TimeoutParams) Propose(round int) time.Duration { - return time.Duration(tp.Propose0+tp.ProposeDelta*round) * time.Millisecond +func (cfg *Config) Propose(round int) time.Duration { + return time.Duration(cfg.TimeoutPropose+cfg.TimeoutProposeDelta*round) * time.Millisecond } // After receiving any +2/3 prevote, wait this long for stragglers -func (tp *TimeoutParams) Prevote(round int) time.Duration { - return time.Duration(tp.Prevote0+tp.PrevoteDelta*round) * time.Millisecond +func (cfg *Config) Prevote(round int) time.Duration { + return time.Duration(cfg.TimeoutPrevote+cfg.TimeoutPrevoteDelta*round) * time.Millisecond } // After receiving any +2/3 precommits, wait this long for stragglers -func (tp *TimeoutParams) Precommit(round int) time.Duration { - return time.Duration(tp.Precommit0+tp.PrecommitDelta*round) * time.Millisecond +func (cfg *Config) Precommit(round int) time.Duration { + return time.Duration(cfg.TimeoutPrecommit+cfg.TimeoutPrecommitDelta*round) * time.Millisecond } // After receiving +2/3 precommits for a single block (a commit), wait this long for stragglers in the next height's RoundStepNewHeight -func (tp *TimeoutParams) Commit(t time.Time) time.Time { - return t.Add(time.Duration(tp.Commit0) * time.Millisecond) -} - -// InitTimeoutParamsFromConfig initializes parameters from config -func InitTimeoutParamsFromConfig(config *viper.Viper) *TimeoutParams { - return &TimeoutParams{ - Propose0: config.GetInt("timeout_propose"), - ProposeDelta: config.GetInt("timeout_propose_delta"), - Prevote0: config.GetInt("timeout_prevote"), - PrevoteDelta: config.GetInt("timeout_prevote_delta"), - Precommit0: config.GetInt("timeout_precommit"), - PrecommitDelta: config.GetInt("timeout_precommit_delta"), - Commit0: config.GetInt("timeout_commit"), - SkipTimeoutCommit: config.GetBool("skip_timeout_commit"), - } +func (cfg *Config) Commit(t time.Time) time.Time { + return t.Add(time.Duration(cfg.TimeoutCommit) * time.Millisecond) } //----------------------------------------------------------------------------- @@ -224,38 +260,48 @@ type PrivValidator interface { type ConsensusState struct { cmn.BaseService - config *viper.Viper + // config details + config *Config + privValidator PrivValidator // for signing votes + + // services for creating and executing blocks proxyAppConn proxy.AppConnConsensus blockStore types.BlockStore mempool types.Mempool - privValidator PrivValidator // for signing votes - + // internal state mtx sync.Mutex RoundState state *sm.State // State until height-1. - peerMsgQueue chan msgInfo // serializes msgs affecting state (proposals, block parts, votes) - internalMsgQueue chan msgInfo // like peerMsgQueue but for our own proposals, parts, votes - timeoutTicker TimeoutTicker // ticker for timeouts - timeoutParams *TimeoutParams // parameters and functions for timeout intervals + // state changes may be triggered by msgs from peers, + // msgs from ourself, or by timeouts + peerMsgQueue chan msgInfo + internalMsgQueue chan msgInfo + timeoutTicker TimeoutTicker + // we use PubSub to trigger msg broadcasts in the reactor, + // and to notify external subscribers, eg. through a websocket evsw types.EventSwitch + // a Write-Ahead Log ensures we can recover from any kind of crash + // and helps us avoid signing conflicting votes wal *WAL replayMode bool // so we don't log signing errors during replay - nSteps int // used for testing to limit the number of transitions the state makes + // for tests where we want to limit the number of transitions the state makes + nSteps int - // allow certain function to be overwritten for testing + // some functions can be overwritten for testing decideProposal func(height, round int) doPrevote func(height, round int) setProposal func(proposal *types.Proposal) error + // closed when we finish shutting down done chan struct{} } -func NewConsensusState(config *viper.Viper, state *sm.State, proxyAppConn proxy.AppConnConsensus, blockStore types.BlockStore, mempool types.Mempool) *ConsensusState { +func NewConsensusState(config *Config, state *sm.State, proxyAppConn proxy.AppConnConsensus, blockStore types.BlockStore, mempool types.Mempool) *ConsensusState { cs := &ConsensusState{ config: config, proxyAppConn: proxyAppConn, @@ -264,7 +310,6 @@ func NewConsensusState(config *viper.Viper, state *sm.State, proxyAppConn proxy. peerMsgQueue: make(chan msgInfo, msgQueueSize), internalMsgQueue: make(chan msgInfo, msgQueueSize), timeoutTicker: NewTimeoutTicker(), - timeoutParams: InitTimeoutParamsFromConfig(config), done: make(chan struct{}), } // set function defaults (may be overwritten before calling Start) @@ -341,7 +386,7 @@ func (cs *ConsensusState) LoadCommit(height int) *types.Commit { func (cs *ConsensusState) OnStart() error { - walFile := cs.config.GetString("cs_wal_file") + walFile := cs.config.WalFile if err := cs.OpenWAL(walFile); err != nil { log.Error("Error loading ConsensusState wal", "error", err.Error()) return err @@ -406,7 +451,7 @@ func (cs *ConsensusState) OpenWAL(walFile string) (err error) { cs.mtx.Lock() defer cs.mtx.Unlock() - wal, err := NewWAL(walFile, cs.config.GetBool("cs_wal_light")) + wal, err := NewWAL(walFile, cs.config.WalLight) if err != nil { return err } @@ -512,7 +557,7 @@ func (cs *ConsensusState) reconstructLastCommit(state *sm.State) { return } seenCommit := cs.blockStore.LoadSeenCommit(state.LastBlockHeight) - lastPrecommits := types.NewVoteSet(cs.config.GetString("chain_id"), state.LastBlockHeight, seenCommit.Round(), types.VoteTypePrecommit, state.LastValidators) + lastPrecommits := types.NewVoteSet(cs.config.chainID, state.LastBlockHeight, seenCommit.Round(), types.VoteTypePrecommit, state.LastValidators) for _, precommit := range seenCommit.Precommits { if precommit == nil { continue @@ -572,9 +617,9 @@ func (cs *ConsensusState) updateToState(state *sm.State) { // to be gathered for the first block. // And alternative solution that relies on clocks: // cs.StartTime = state.LastBlockTime.Add(timeoutCommit) - cs.StartTime = cs.timeoutParams.Commit(time.Now()) + cs.StartTime = cs.config.Commit(time.Now()) } else { - cs.StartTime = cs.timeoutParams.Commit(cs.CommitTime) + cs.StartTime = cs.config.Commit(cs.CommitTime) } cs.Validators = validators cs.Proposal = nil @@ -583,7 +628,7 @@ func (cs *ConsensusState) updateToState(state *sm.State) { cs.LockedRound = 0 cs.LockedBlock = nil cs.LockedBlockParts = nil - cs.Votes = NewHeightVoteSet(cs.config.GetString("chain_id"), height, validators) + cs.Votes = NewHeightVoteSet(cs.config.chainID, height, validators) cs.CommitRound = -1 cs.LastCommit = lastPrecommits cs.LastValidators = state.LastValidators @@ -799,7 +844,7 @@ func (cs *ConsensusState) enterPropose(height int, round int) { }() // If we don't get the proposal and all block parts quick enough, enterPrevote - cs.scheduleTimeout(cs.timeoutParams.Propose(round), height, round, RoundStepPropose) + cs.scheduleTimeout(cs.config.Propose(round), height, round, RoundStepPropose) // Nothing more to do if we're not a validator if cs.privValidator == nil { @@ -893,10 +938,10 @@ func (cs *ConsensusState) createProposalBlock() (block *types.Block, blockParts } // Mempool validated transactions - txs := cs.mempool.Reap(cs.config.GetInt("block_size")) + txs := cs.mempool.Reap(cs.config.MaxBlockSizeTxs) return types.MakeBlock(cs.Height, cs.state.ChainID, txs, commit, - cs.state.LastBlockID, cs.state.Validators.Hash(), cs.state.AppHash, cs.config.GetInt("block_part_size")) + cs.state.LastBlockID, cs.state.Validators.Hash(), cs.state.AppHash, cs.config.BlockPartSize) } // Enter: `timeoutPropose` after entering Propose. @@ -982,7 +1027,7 @@ func (cs *ConsensusState) enterPrevoteWait(height int, round int) { }() // Wait for some more prevotes; enterPrecommit - cs.scheduleTimeout(cs.timeoutParams.Prevote(round), height, round, RoundStepPrevoteWait) + cs.scheduleTimeout(cs.config.Prevote(round), height, round, RoundStepPrevoteWait) } // Enter: +2/3 precomits for block or nil. @@ -1102,7 +1147,7 @@ func (cs *ConsensusState) enterPrecommitWait(height int, round int) { }() // Wait for some more precommits; enterNewRound - cs.scheduleTimeout(cs.timeoutParams.Precommit(round), height, round, RoundStepPrecommitWait) + cs.scheduleTimeout(cs.config.Precommit(round), height, round, RoundStepPrecommitWait) } @@ -1397,7 +1442,7 @@ func (cs *ConsensusState) addVote(vote *types.Vote, peerKey string) (added bool, types.FireEventVote(cs.evsw, types.EventDataVote{vote}) // if we can skip timeoutCommit and have all the votes now, - if cs.timeoutParams.SkipTimeoutCommit && cs.LastCommit.HasAll() { + if cs.config.SkipTimeoutCommit && cs.LastCommit.HasAll() { // go straight to new round (skip timeout commit) // cs.scheduleTimeout(time.Duration(0), cs.Height, 0, RoundStepNewHeight) cs.enterNewRound(cs.Height, 0) @@ -1460,7 +1505,7 @@ func (cs *ConsensusState) addVote(vote *types.Vote, peerKey string) (added bool, cs.enterPrecommit(height, vote.Round) cs.enterCommit(height, vote.Round) - if cs.timeoutParams.SkipTimeoutCommit && precommits.HasAll() { + if cs.config.SkipTimeoutCommit && precommits.HasAll() { // if we have all the votes now, // go straight to new round (skip timeout commit) // cs.scheduleTimeout(time.Duration(0), cs.Height, 0, RoundStepNewHeight) diff --git a/mempool/mempool.go b/mempool/mempool.go index 46a78d268..daf9f6524 100644 --- a/mempool/mempool.go +++ b/mempool/mempool.go @@ -47,7 +47,7 @@ TODO: Better handle abci client errors. (make it automatically handle connection const cacheSize = 100000 type Mempool struct { - config Config + config *Config proxyMtx sync.Mutex proxyAppConn proxy.AppConnMempool @@ -66,7 +66,7 @@ type Mempool struct { wal *auto.AutoFile } -func NewMempool(config Config, proxyAppConn proxy.AppConnMempool) *Mempool { +func NewMempool(config *Config, proxyAppConn proxy.AppConnMempool) *Mempool { mempool := &Mempool{ config: config, proxyAppConn: proxyAppConn, diff --git a/mempool/reactor.go b/mempool/reactor.go index 3f25cc562..a0e7d518c 100644 --- a/mempool/reactor.go +++ b/mempool/reactor.go @@ -22,21 +22,30 @@ const ( ) type Config struct { - Recheck bool // true - RecheckEmpty bool // true - Broadcast bool // true - WalDir string // rootDir+"/data/mempool.wal") + Recheck bool `mapstructure:"recheck"` // true + RecheckEmpty bool `mapstructure:"recheck_empty"` // true + Broadcast bool `mapstructure:"broadcast"` // true + WalDir string `mapstructure:"wal_dir"` // +} + +func NewDefaultConfig(rootDir string) *Config { + return &Config{ + Recheck: true, + RecheckEmpty: true, + Broadcast: true, + WalDir: rootDir + "/data/mempool.wal", + } } // MempoolReactor handles mempool tx broadcasting amongst peers. type MempoolReactor struct { p2p.BaseReactor - config Config + config *Config Mempool *Mempool evsw types.EventSwitch } -func NewMempoolReactor(config Config, mempool *Mempool) *MempoolReactor { +func NewMempoolReactor(config *Config, mempool *Mempool) *MempoolReactor { memR := &MempoolReactor{ config: config, Mempool: mempool, diff --git a/node/node.go b/node/node.go index c4000a1fe..742c9984c 100644 --- a/node/node.go +++ b/node/node.go @@ -13,7 +13,8 @@ import ( crypto "github.com/tendermint/go-crypto" wire "github.com/tendermint/go-wire" bc "github.com/tendermint/tendermint/blockchain" - tmcfg "github.com/tendermint/tendermint/config/tendermint" + cfg "github.com/tendermint/tendermint/config" + // tmcfg "github.com/tendermint/tendermint/config/tendermint" "github.com/tendermint/tendermint/consensus" mempl "github.com/tendermint/tendermint/mempool" p2p "github.com/tendermint/tendermint/p2p" @@ -34,11 +35,30 @@ import ( _ "net/http/pprof" ) +type Config struct { + // Top level options use an anonymous struct + *cfg.Config `mapstructure:",squash"` + + // Options for services + P2P *p2p.NetworkConfig `mapstructure:"p2p"` + Mempool *mempl.Config `mapstructure:"mempool"` + Consensus *consensus.Config `mapstructure:"consensus"` +} + +func NewDefaultConfig(rootDir string) *Config { + return &Config{ + Config: cfg.NewDefaultConfig(rootDir), + P2P: p2p.NewDefaultConfig(rootDir), + Mempool: mempl.NewDefaultConfig(rootDir), + Consensus: consensus.NewDefaultConfig(rootDir), + } +} + type Node struct { cmn.BaseService // config - config *viper.Viper // user config + config *Config genesisDoc *types.GenesisDoc // initial validator set privValidator *types.PrivValidator // local node's validator key @@ -59,35 +79,27 @@ type Node struct { txIndexer txindex.TxIndexer } -func NewNodeDefault(config *viper.Viper) *Node { +func NewNodeDefault(config *Config) *Node { // Get PrivValidator - privValidatorFile := config.GetString("priv_validator_file") - privValidator := types.LoadOrGenPrivValidator(privValidatorFile) - return NewNode(config, privValidator, proxy.DefaultClientCreator( - config.GetString("proxy_app"), - config.GetString("abci"), - config.GetString("db_dir"), - )) - // config.ABCI.ProxyApp, config.ABCI.Mode, config.DB.Dir)) + privValidator := types.LoadOrGenPrivValidator(config.PrivValidatorFile) + return NewNode(config, privValidator, + proxy.DefaultClientCreator(config.ProxyApp, config.ABCI, config.DBDir)) } -func NewNode(config *viper.Viper, privValidator *types.PrivValidator, clientCreator proxy.ClientCreator) *Node { - - tmConfig := new(tmcfg.Config) - if err := config.Unmarshal(tmConfig); err != nil { - panic(err) - } +func NewNode(config *Config, privValidator *types.PrivValidator, clientCreator proxy.ClientCreator) *Node { // Get BlockStore - blockStoreDB := dbm.NewDB("blockstore", tmConfig.DB.Backend, tmConfig.DB.Dir) + blockStoreDB := dbm.NewDB("blockstore", config.DBBackend, config.DBDir) blockStore := bc.NewBlockStore(blockStoreDB) // Get State - stateDB := dbm.NewDB("state", tmConfig.DB.Backend, tmConfig.DB.Dir) - state := sm.GetState(stateDB, tmConfig.Chain.GenesisFile) + stateDB := dbm.NewDB("state", config.DBBackend, config.DBDir) + state := sm.GetState(stateDB, config.GenesisFile) // add the chainid and number of validators to the global config - config.Set("chain_id", state.ChainID) + // TODO: Set ChainID. eg: + // config.Consensus.SetChainID(state.ChainID) // ... + // but actually consensus doesnt need it since the cs has the state ... // Create the proxyApp, which manages connections (consensus, mempool, query) // and sync tendermint and the app by replaying any necessary blocks @@ -101,9 +113,9 @@ func NewNode(config *viper.Viper, privValidator *types.PrivValidator, clientCrea // Transaction indexing var txIndexer txindex.TxIndexer - switch tmConfig.DB.TxIndex { + switch config.TxIndex { case "kv": - store := dbm.NewDB("tx_index", tmConfig.DB.Backend, tmConfig.DB.Dir) + store := dbm.NewDB("tx_index", config.DBBackend, config.DBDir) txIndexer = kv.NewTxIndex(store) default: txIndexer = &null.TxIndex{} @@ -122,7 +134,7 @@ func NewNode(config *viper.Viper, privValidator *types.PrivValidator, clientCrea // Decide whether to fast-sync or not // We don't fast-sync when the only validator is us. - fastSync := config.GetBool("fast_sync") + fastSync := config.FastSync if state.Validators.Size() == 1 { addr, _ := state.Validators.GetByIndex(0) if bytes.Equal(privValidator.Address, addr) { @@ -134,21 +146,20 @@ func NewNode(config *viper.Viper, privValidator *types.PrivValidator, clientCrea bcReactor := bc.NewBlockchainReactor(state.Copy(), proxyApp.Consensus(), blockStore, fastSync) // Make MempoolReactor - mempool := mempl.NewMempool(mempoolConfig(config), proxyApp.Mempool()) - mempoolReactor := mempl.NewMempoolReactor(mempoolConfig(config), mempool) + mempool := mempl.NewMempool(config.Mempool, proxyApp.Mempool()) + mempoolReactor := mempl.NewMempoolReactor(config.Mempool, mempool) // Make ConsensusReactor - consensusState := consensus.NewConsensusState(config, state.Copy(), proxyApp.Consensus(), blockStore, mempool) + consensusState := consensus.NewConsensusState(config.Consensus, state.Copy(), proxyApp.Consensus(), blockStore, mempool) if privValidator != nil { consensusState.SetPrivValidator(privValidator) } consensusReactor := consensus.NewConsensusReactor(consensusState, fastSync) // Make p2p network switch + // TODO : p2pConfig := config.P2P p2pConfig := viper.New() - if config.IsSet("p2p") { //TODO verify this necessary, where is this ever set? - p2pConfig = config.Get("p2p").(*viper.Viper) - } + sw := p2p.NewSwitch(p2pConfig) sw.AddReactor("MEMPOOL", mempoolReactor) sw.AddReactor("BLOCKCHAIN", bcReactor) @@ -156,8 +167,8 @@ func NewNode(config *viper.Viper, privValidator *types.PrivValidator, clientCrea // Optionally, start the pex reactor var addrBook *p2p.AddrBook - if config.GetBool("pex_reactor") { - addrBook = p2p.NewAddrBook(config.GetString("addrbook_file"), config.GetBool("addrbook_strict")) + if config.P2P.PexReactor { + addrBook = p2p.NewAddrBook(config.P2P.AddrBookFile, config.P2P.AddrBookStrict) pexReactor := p2p.NewPEXReactor(addrBook) sw.AddReactor("PEX", pexReactor) } @@ -165,7 +176,7 @@ func NewNode(config *viper.Viper, privValidator *types.PrivValidator, clientCrea // Filter peers by addr or pubkey with an ABCI query. // If the query return code is OK, add peer. // XXX: Query format subject to change - if config.GetBool("filter_peers") { + if config.FilterPeers { // NOTE: addr is ip:port sw.SetAddrFilter(func(addr net.Addr) error { resQuery, err := proxyApp.Query().QuerySync(abci.RequestQuery{Path: cmn.Fmt("/p2p/filter/addr/%s", addr.String())}) @@ -194,7 +205,7 @@ func NewNode(config *viper.Viper, privValidator *types.PrivValidator, clientCrea SetEventSwitch(eventSwitch, bcReactor, mempoolReactor, consensusReactor) // run the profile server - profileHost := config.GetString("prof_laddr") + profileHost := config.ProfListenAddress if profileHost != "" { go func() { @@ -227,8 +238,8 @@ func NewNode(config *viper.Viper, privValidator *types.PrivValidator, clientCrea func (n *Node) OnStart() error { // Create & add listener - protocol, address := ProtocolAndAddress(n.config.GetString("node_laddr")) - l := p2p.NewDefaultListener(protocol, address, n.config.GetBool("skip_upnp")) + protocol, address := ProtocolAndAddress(n.config.P2P.ListenAddress) + l := p2p.NewDefaultListener(protocol, address, n.config.P2P.SkipUPNP) n.sw.AddListener(l) // Start the switch @@ -240,16 +251,16 @@ func (n *Node) OnStart() error { } // If seeds exist, add them to the address book and dial out - if n.config.GetString("seeds") != "" { + if n.config.P2P.Seeds != "" { // dial out - seeds := strings.Split(n.config.GetString("seeds"), ",") + seeds := strings.Split(n.config.P2P.Seeds, ",") if err := n.DialSeeds(seeds); err != nil { return err } } // Run the RPC server - if n.config.GetString("rpc_laddr") != "" { + if n.config.RPCListenAddress != "" { listeners, err := n.startRPC() if err != nil { return err @@ -313,7 +324,7 @@ func (n *Node) ConfigureRPC() { func (n *Node) startRPC() ([]net.Listener, error) { n.ConfigureRPC() - listenAddrs := strings.Split(n.config.GetString("rpc_laddr"), ",") + listenAddrs := strings.Split(n.config.RPCListenAddress, ",") // we may expose the rpc over both a unix and tcp socket listeners := make([]net.Listener, len(listenAddrs)) @@ -330,7 +341,7 @@ func (n *Node) startRPC() ([]net.Listener, error) { } // we expose a simplified api over grpc for convenience to app devs - grpcListenAddr := n.config.GetString("grpc_laddr") + grpcListenAddr := n.config.GRPCListenAddress if grpcListenAddr != "" { listener, err := grpccore.StartGRPCServer(grpcListenAddr) if err != nil { @@ -387,8 +398,8 @@ func (n *Node) makeNodeInfo() *p2p.NodeInfo { nodeInfo := &p2p.NodeInfo{ PubKey: n.privKey.PubKey().Unwrap().(crypto.PubKeyEd25519), - Moniker: n.config.GetString("moniker"), - Network: n.config.GetString("chain_id"), + Moniker: n.config.Moniker, + Network: n.consensusState.GetState().ChainID, Version: version.Version, Other: []string{ cmn.Fmt("wire_version=%v", wire.Version), @@ -400,9 +411,10 @@ func (n *Node) makeNodeInfo() *p2p.NodeInfo { } // include git hash in the nodeInfo if available - if rev, err := cmn.ReadFile(n.config.GetString("revision_file")); err == nil { + // TODO: use ld-flags + /*if rev, err := cmn.ReadFile(n.config.GetString("revision_file")); err == nil { nodeInfo.Other = append(nodeInfo.Other, cmn.Fmt("revision=%v", string(rev))) - } + }*/ if !n.sw.IsListening() { return nodeInfo @@ -411,7 +423,7 @@ func (n *Node) makeNodeInfo() *p2p.NodeInfo { p2pListener := n.sw.Listeners()[0] p2pHost := p2pListener.ExternalAddress().IP.String() p2pPort := p2pListener.ExternalAddress().Port - rpcListenAddr := n.config.GetString("rpc_laddr") + rpcListenAddr := n.config.RPCListenAddress // We assume that the rpcListener has the same ExternalAddress. // This is probably true because both P2P and RPC listeners use UPnP, @@ -442,12 +454,3 @@ func ProtocolAndAddress(listenAddr string) (string, string) { } //------------------------------------------------------------------------------ - -func mempoolConfig(config *viper.Viper) mempl.Config { - return mempl.Config{ - Recheck: config.GetBool("mempool_recheck"), - RecheckEmpty: config.GetBool("mempool_recheck_empty"), - Broadcast: config.GetBool("mempool_broadcast"), - WalDir: config.GetString("mempool_wal_dir"), - } -} diff --git a/p2p/config.go b/p2p/config.go index 2e70d16df..4eccd4be7 100644 --- a/p2p/config.go +++ b/p2p/config.go @@ -4,6 +4,23 @@ import ( "github.com/spf13/viper" ) +// for node.Config +type NetworkConfig struct { + ListenAddress string `mapstructure:"laddr"` + Seeds string `mapstructure:"seeds"` + SkipUPNP bool `mapstructure:"skip_upnp"` + AddrBookFile string `mapstructure:"addr_book_file"` + AddrBookStrict bool `mapstructure:"addr_book_strict"` + PexReactor bool `mapstructure:"pex_reactor"` +} + +func NewDefaultConfig(rootDir string) *NetworkConfig { + return &NetworkConfig{ + AddrBookFile: rootDir + "/addrbook.json", + AddrBookStrict: true, + } +} + const ( // Switch config keys configKeyDialTimeoutSeconds = "dial_timeout_seconds" diff --git a/types/block.go b/types/block.go index afa3be4e7..0f0fc75b6 100644 --- a/types/block.go +++ b/types/block.go @@ -15,8 +15,8 @@ import ( ) const ( - MaxBlockSize = 22020096 // 21MB TODO make it configurable - DefaultPartSetSize = 65536 // 64kB TODO: put part size in parts header? + MaxBlockSize = 22020096 // 21MB TODO make it configurable + DefaultBlockPartSize = 65536 // 64kB TODO: put part size in parts header? ) type Block struct { From 24ce90fc72a2bd339a1accd5d3863e5025b4be45 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Mon, 1 May 2017 21:19:04 -0400 Subject: [PATCH 256/309] fix up config defaults --- config/tendermint/config.go | 40 +++++++++++++------------- config/tendermint_test/config.go | 49 ++++++++++++++++---------------- 2 files changed, 43 insertions(+), 46 deletions(-) diff --git a/config/tendermint/config.go b/config/tendermint/config.go index 0ac3e1f74..9f9a06849 100644 --- a/config/tendermint/config.go +++ b/config/tendermint/config.go @@ -57,32 +57,32 @@ func GetConfig(rootDir string) *viper.Viper { cmn.Exit("Cannot set 'chain_id' via config.toml") } //mapConfig.SetRequired("chain_id") // blows up if you try to use it before setting. - config.SetDefault("node.moniker", "anonymous") - config.SetDefault("node.log_level", "info") - config.SetDefault("node.prof_laddr", "") - config.SetDefault("chain.genesis_file", rootDir+"/genesis.json") - config.SetDefault("abci.proxy_app", "tcp://127.0.0.1:46658") - config.SetDefault("abci.mode", "socket") - config.SetDefault("abci.filter_peers", false) + config.SetDefault("moniker", "anonymous") + config.SetDefault("log_level", "info") + config.SetDefault("prof_laddr", "") + config.SetDefault("genesis_file", rootDir+"/genesis.json") + config.SetDefault("proxy_app", "tcp://127.0.0.1:46658") + config.SetDefault("abci", "socket") + config.SetDefault("filter_peers", false) + config.SetDefault("fast_sync", true) + config.SetDefault("priv_validator_file", rootDir+"/priv_validator.json") + config.SetDefault("db_backend", "leveldb") + config.SetDefault("db_dir", rootDir+"/data") + config.SetDefault("rpc_laddr", "tcp://0.0.0.0:46657") + config.SetDefault("grpc_laddr", "") + config.SetDefault("tx_index", "kv") + config.SetDefault("network.listen_addr", "tcp://0.0.0.0:46656") config.SetDefault("network.seeds", "") config.SetDefault("network.skip_upnp", false) - config.SetDefault("blockchain.fast_sync", true) config.SetDefault("network.addrbook_file", rootDir+"/addrbook.json") config.SetDefault("network.addrbook_strict", true) // disable to allow connections locally config.SetDefault("network.pex_reactor", false) // enable for peer exchange - config.SetDefault("node.priv_validator_file", rootDir+"/priv_validator.json") - config.SetDefault("db.backend", "leveldb") - config.SetDefault("db.dir", rootDir+"/data") - config.SetDefault("rpc.listen_addr", "tcp://0.0.0.0:46657") - config.SetDefault("rpc.grpc_listen_addr", "") + config.SetDefault("consensus.wal_file", rootDir+"/data/cs.wal/wal") config.SetDefault("consensus.wal_light", false) - - config.SetDefault("block.max_txs", 10000) // max number of txs - config.SetDefault("block.part_size", 65536) // part size 64K - config.SetDefault("block.disable_data_hash", false) - + config.SetDefault("consensus.max_block_size_txs", 10000) // max number of txs + config.SetDefault("consensus.block_part_size", 65536) // part size 64K // all timeouts are in ms config.SetDefault("consensus.timeout_handshake", 10000) config.SetDefault("consensus.timeout_propose", 3000) @@ -92,16 +92,14 @@ func GetConfig(rootDir string) *viper.Viper { config.SetDefault("consensus.timeout_precommit", 1000) config.SetDefault("consensus.timeout_precommit_delta", 500) config.SetDefault("consensus.timeout_commit", 1000) - // make progress asap (no `timeout_commit`) on full precommit votes config.SetDefault("consensus.skip_timeout_commit", false) + config.SetDefault("mempool.recheck", true) config.SetDefault("mempool.recheck_empty", true) config.SetDefault("mempool.broadcast", true) config.SetDefault("mempool.wal_dir", rootDir+"/data/mempool.wal") - config.SetDefault("db.tx_index", "kv") - return config } diff --git a/config/tendermint_test/config.go b/config/tendermint_test/config.go index 1a87d5261..7c3ff72c0 100644 --- a/config/tendermint_test/config.go +++ b/config/tendermint_test/config.go @@ -80,10 +80,6 @@ func ResetConfig(localPath string) *viper.Viper { config.SetDefault("moniker", "anonymous") config.SetDefault("node_laddr", "tcp://0.0.0.0:36656") config.SetDefault("fast_sync", false) - config.SetDefault("skip_upnp", true) - config.SetDefault("addrbook_file", rootDir+"/addrbook.json") - config.SetDefault("addrbook_strict", true) // disable to allow connections locally - config.SetDefault("pex_reactor", false) // enable for peer exchange config.SetDefault("priv_validator_file", rootDir+"/priv_validator.json") config.SetDefault("db_backend", "memdb") config.SetDefault("db_dir", rootDir+"/data") @@ -91,30 +87,33 @@ func ResetConfig(localPath string) *viper.Viper { config.SetDefault("rpc_laddr", "tcp://0.0.0.0:36657") config.SetDefault("grpc_laddr", "tcp://0.0.0.0:36658") config.SetDefault("prof_laddr", "") - config.SetDefault("revision_file", rootDir+"/revision") - config.SetDefault("cs_wal_file", rootDir+"/data/cs.wal/wal") - config.SetDefault("cs_wal_light", false) config.SetDefault("filter_peers", false) - - config.SetDefault("block_size", 10000) - config.SetDefault("block_part_size", 65536) // part size 64K - config.SetDefault("disable_data_hash", false) - config.SetDefault("timeout_handshake", 10000) - config.SetDefault("timeout_propose", 2000) - config.SetDefault("timeout_propose_delta", 1) - config.SetDefault("timeout_prevote", 10) - config.SetDefault("timeout_prevote_delta", 1) - config.SetDefault("timeout_precommit", 10) - config.SetDefault("timeout_precommit_delta", 1) - config.SetDefault("timeout_commit", 10) - config.SetDefault("skip_timeout_commit", true) - config.SetDefault("mempool_recheck", true) - config.SetDefault("mempool_recheck_empty", true) - config.SetDefault("mempool_broadcast", true) - config.SetDefault("mempool_wal_dir", "") - config.SetDefault("tx_index", "kv") + config.SetDefault("p2p.skip_upnp", true) + config.SetDefault("p2p.addrbook_file", rootDir+"/addrbook.json") + config.SetDefault("p2p.addrbook_strict", true) // disable to allow connections locally + config.SetDefault("p2p.pex_reactor", false) // enable for peer exchange + + config.SetDefault("consensus.wal_file", rootDir+"/data/cs.wal/wal") + config.SetDefault("consensus.wal_light", false) + config.SetDefault("consensus.max_block_size_txs", 10000) + config.SetDefault("consensus.block_part_size", 65536) // part size 64K + config.SetDefault("consensus.timeout_handshake", 10000) + config.SetDefault("consensus.timeout_propose", 2000) + config.SetDefault("consensus.timeout_propose_delta", 1) + config.SetDefault("consensus.timeout_prevote", 10) + config.SetDefault("consensus.timeout_prevote_delta", 1) + config.SetDefault("consensus.timeout_precommit", 10) + config.SetDefault("consensus.timeout_precommit_delta", 1) + config.SetDefault("consensus.timeout_commit", 10) + config.SetDefault("consensus.skip_timeout_commit", true) + + config.SetDefault("mempool.recheck", true) + config.SetDefault("mempool.recheck_empty", true) + config.SetDefault("mempool.broadcast", true) + config.SetDefault("mempool.wal_dir", "") + logger.SetLogLevel(config.GetString("log_level")) return config From 4982cb4d1f7730d4c534a200e72aee661a3eb4b1 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Mon, 1 May 2017 21:25:10 -0400 Subject: [PATCH 257/309] fix tests for state and mempool --- mempool/mempool_test.go | 18 ++++++++++++++++-- state/execution_test.go | 10 +++------- state/state_test.go | 32 ++++++++++++++++++++++---------- 3 files changed, 41 insertions(+), 19 deletions(-) diff --git a/mempool/mempool_test.go b/mempool/mempool_test.go index 9ac8fe33d..a1bd188d4 100644 --- a/mempool/mempool_test.go +++ b/mempool/mempool_test.go @@ -4,14 +4,28 @@ import ( "encoding/binary" "testing" + "github.com/tendermint/abci/example/counter" + cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/config/tendermint_test" "github.com/tendermint/tendermint/proxy" "github.com/tendermint/tendermint/types" - "github.com/tendermint/abci/example/counter" ) +func ResetConfig(name string) *Config { + viperConfig := tendermint_test.ResetConfig(name) + config := new(struct { + cfg.Config `mapstructure:",squash"` + Mempool *Config `mapstructure:"mempool"` + }) + if err := viperConfig.Unmarshal(config); err != nil { + panic(err) + } + return config.Mempool + +} + func TestSerialReap(t *testing.T) { - config := tendermint_test.ResetConfig("mempool_mempool_test") + config := ResetConfig("mempool_test") app := counter.NewCounterApplication(true) app.SetOption("serial", "on") diff --git a/state/execution_test.go b/state/execution_test.go index 40e4044a4..68c318448 100644 --- a/state/execution_test.go +++ b/state/execution_test.go @@ -7,12 +7,10 @@ import ( "github.com/stretchr/testify/require" "github.com/tendermint/abci/example/dummy" crypto "github.com/tendermint/go-crypto" - dbm "github.com/tendermint/tmlibs/db" - cfg "github.com/tendermint/tendermint/config/tendermint_test" - "github.com/tendermint/tendermint/mempool" "github.com/tendermint/tendermint/proxy" "github.com/tendermint/tendermint/state/txindex" "github.com/tendermint/tendermint/types" + dbm "github.com/tendermint/tmlibs/db" ) var ( @@ -24,12 +22,10 @@ var ( func TestApplyBlock(t *testing.T) { cc := proxy.NewLocalClientCreator(dummy.NewDummyApplication()) - config := cfg.ResetConfig("execution_test_") - proxyApp := proxy.NewAppConns(config, cc, nil) + proxyApp := proxy.NewAppConns(cc, nil) _, err := proxyApp.Start() require.Nil(t, err) defer proxyApp.Stop() - mempool := mempool.NewMempool(config, proxyApp.Mempool()) state := state() indexer := &dummyIndexer{0} @@ -38,7 +34,7 @@ func TestApplyBlock(t *testing.T) { // make block block := makeBlock(1, state) - err = state.ApplyBlock(nil, proxyApp.Consensus(), block, block.MakePartSet(testPartSize).Header(), mempool) + err = state.ApplyBlock(nil, proxyApp.Consensus(), block, block.MakePartSet(testPartSize).Header(), types.MockMempool{}) require.Nil(t, err) assert.Equal(t, nTxsPerBlock, indexer.Indexed) // test indexing works diff --git a/state/state_test.go b/state/state_test.go index f80c08fe5..97df5cab4 100644 --- a/state/state_test.go +++ b/state/state_test.go @@ -7,15 +7,27 @@ import ( "github.com/stretchr/testify/assert" abci "github.com/tendermint/abci/types" "github.com/tendermint/go-crypto" - dbm "github.com/tendermint/tmlibs/db" + cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/config/tendermint_test" + dbm "github.com/tendermint/tmlibs/db" ) +func ResetConfig(name string) *cfg.Config { + viperConfig := tendermint_test.ResetConfig(name) + config := new(struct { + cfg.Config `mapstructure:",squash"` + }) + if err := viperConfig.Unmarshal(config); err != nil { + panic(err) + } + return &config.Config +} + func TestStateCopyEquals(t *testing.T) { - config := tendermint_test.ResetConfig("state_") + config := ResetConfig("state_") // Get State db - stateDB := dbm.NewDB("state", config.GetString("db_backend"), config.GetString("db_dir")) - state := GetState(config, stateDB) + stateDB := dbm.NewDB("state", config.DBBackend, config.DBDir) + state := GetState(stateDB, config.GenesisFile) stateCopy := state.Copy() @@ -31,10 +43,10 @@ func TestStateCopyEquals(t *testing.T) { } func TestStateSaveLoad(t *testing.T) { - config := tendermint_test.ResetConfig("state_") + config := ResetConfig("state_") // Get State db - stateDB := dbm.NewDB("state", config.GetString("db_backend"), config.GetString("db_dir")) - state := GetState(config, stateDB) + stateDB := dbm.NewDB("state", config.DBBackend, config.DBDir) + state := GetState(stateDB, config.GenesisFile) state.LastBlockHeight += 1 state.Save() @@ -48,9 +60,9 @@ func TestStateSaveLoad(t *testing.T) { func TestABCIResponsesSaveLoad(t *testing.T) { assert := assert.New(t) - config := tendermint_test.ResetConfig("state_") - stateDB := dbm.NewDB("state", config.GetString("db_backend"), config.GetString("db_dir")) - state := GetState(config, stateDB) + config := ResetConfig("state_") + stateDB := dbm.NewDB("state", config.DBBackend, config.DBDir) + state := GetState(stateDB, config.GenesisFile) state.LastBlockHeight += 1 From 5d660e073ac3cb752896fc49b10f7a0a8107793d Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Mon, 1 May 2017 22:05:26 -0400 Subject: [PATCH 258/309] remove viper from p2p --- p2p/config.go | 62 -------------------------------------- p2p/connection.go | 4 +-- p2p/peer.go | 21 +++++++------ p2p/pex_reactor_test.go | 4 +-- p2p/switch.go | 67 ++++++++++++++++++++--------------------- p2p/switch_test.go | 22 ++++++-------- 6 files changed, 58 insertions(+), 122 deletions(-) delete mode 100644 p2p/config.go diff --git a/p2p/config.go b/p2p/config.go deleted file mode 100644 index 4eccd4be7..000000000 --- a/p2p/config.go +++ /dev/null @@ -1,62 +0,0 @@ -package p2p - -import ( - "github.com/spf13/viper" -) - -// for node.Config -type NetworkConfig struct { - ListenAddress string `mapstructure:"laddr"` - Seeds string `mapstructure:"seeds"` - SkipUPNP bool `mapstructure:"skip_upnp"` - AddrBookFile string `mapstructure:"addr_book_file"` - AddrBookStrict bool `mapstructure:"addr_book_strict"` - PexReactor bool `mapstructure:"pex_reactor"` -} - -func NewDefaultConfig(rootDir string) *NetworkConfig { - return &NetworkConfig{ - AddrBookFile: rootDir + "/addrbook.json", - AddrBookStrict: true, - } -} - -const ( - // Switch config keys - configKeyDialTimeoutSeconds = "dial_timeout_seconds" - configKeyHandshakeTimeoutSeconds = "handshake_timeout_seconds" - configKeyMaxNumPeers = "max_num_peers" - configKeyAuthEnc = "authenticated_encryption" - - // MConnection config keys - configKeySendRate = "send_rate" - configKeyRecvRate = "recv_rate" - - // Fuzz params - configFuzzEnable = "fuzz_enable" // use the fuzz wrapped conn - configFuzzMode = "fuzz_mode" // eg. drop, delay - configFuzzMaxDelayMilliseconds = "fuzz_max_delay_milliseconds" - configFuzzProbDropRW = "fuzz_prob_drop_rw" - configFuzzProbDropConn = "fuzz_prob_drop_conn" - configFuzzProbSleep = "fuzz_prob_sleep" -) - -func setConfigDefaults(config *viper.Viper) { - // Switch default config - config.SetDefault(configKeyDialTimeoutSeconds, 3) - config.SetDefault(configKeyHandshakeTimeoutSeconds, 20) - config.SetDefault(configKeyMaxNumPeers, 50) - config.SetDefault(configKeyAuthEnc, true) - - // MConnection default config - config.SetDefault(configKeySendRate, 512000) // 500KB/s - config.SetDefault(configKeyRecvRate, 512000) // 500KB/s - - // Fuzz defaults - config.SetDefault(configFuzzEnable, false) - config.SetDefault(configFuzzMode, FuzzModeDrop) - config.SetDefault(configFuzzMaxDelayMilliseconds, 3000) - config.SetDefault(configFuzzProbDropRW, 0.2) - config.SetDefault(configFuzzProbDropConn, 0.00) - config.SetDefault(configFuzzProbSleep, 0.00) -} diff --git a/p2p/connection.go b/p2p/connection.go index 629ab7b0d..b8b000553 100644 --- a/p2p/connection.go +++ b/p2p/connection.go @@ -87,8 +87,8 @@ type MConnection struct { // MConnConfig is a MConnection configuration. type MConnConfig struct { - SendRate int64 - RecvRate int64 + SendRate int64 `mapstructure:"send_rate"` + RecvRate int64 `mapstructure:"recv_rate"` } // DefaultMConnConfig returns the default config. diff --git a/p2p/peer.go b/p2p/peer.go index bf819087d..a1a37a2ae 100644 --- a/p2p/peer.go +++ b/p2p/peer.go @@ -35,23 +35,24 @@ type Peer struct { // PeerConfig is a Peer configuration. type PeerConfig struct { - AuthEnc bool // authenticated encryption + AuthEnc bool `mapstructure:"auth_enc"` // authenticated encryption - HandshakeTimeout time.Duration - DialTimeout time.Duration + // times are in seconds + HandshakeTimeout time.Duration `mapstructure:"handshake_timeout"` + DialTimeout time.Duration `mapstructure:"dial_timeout"` - MConfig *MConnConfig + MConfig *MConnConfig `mapstructure:"connection"` - Fuzz bool // fuzz connection (for testing) - FuzzConfig *FuzzConnConfig + Fuzz bool `mapstructure:"fuzz"` // fuzz connection (for testing) + FuzzConfig *FuzzConnConfig `mapstructure:"fuzz_config"` } // DefaultPeerConfig returns the default config. func DefaultPeerConfig() *PeerConfig { return &PeerConfig{ AuthEnc: true, - HandshakeTimeout: 2 * time.Second, - DialTimeout: 3 * time.Second, + HandshakeTimeout: 20, // * time.Second, + DialTimeout: 3, // * time.Second, MConfig: DefaultMConnConfig(), Fuzz: false, FuzzConfig: DefaultFuzzConnConfig(), @@ -95,7 +96,7 @@ func newPeerFromConnAndConfig(rawConn net.Conn, outbound bool, reactorsByCh map[ // Encrypt connection if config.AuthEnc { - conn.SetDeadline(time.Now().Add(config.HandshakeTimeout)) + conn.SetDeadline(time.Now().Add(config.HandshakeTimeout * time.Second)) var err error conn, err = MakeSecretConnection(conn, ourNodePrivKey) @@ -279,7 +280,7 @@ func (p *Peer) Get(key string) interface{} { func dial(addr *NetAddress, config *PeerConfig) (net.Conn, error) { log.Info("Dialing address", "address", addr) - conn, err := addr.DialTimeout(config.DialTimeout) + conn, err := addr.DialTimeout(config.DialTimeout * time.Second) if err != nil { log.Info("Failed dialing address", "address", addr, "error", err) return nil, err diff --git a/p2p/pex_reactor_test.go b/p2p/pex_reactor_test.go index aed6c758d..ef2629027 100644 --- a/p2p/pex_reactor_test.go +++ b/p2p/pex_reactor_test.go @@ -9,8 +9,8 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" - cmn "github.com/tendermint/tmlibs/common" wire "github.com/tendermint/go-wire" + cmn "github.com/tendermint/tmlibs/common" ) func TestPEXReactorBasic(t *testing.T) { @@ -68,7 +68,7 @@ func TestPEXReactorRunning(t *testing.T) { // create switches for i := 0; i < N; i++ { - switches[i] = makeSwitch(i, "127.0.0.1", "123.123.123", func(i int, sw *Switch) *Switch { + switches[i] = makeSwitch(config, i, "127.0.0.1", "123.123.123", func(i int, sw *Switch) *Switch { r := NewPEXReactor(book) r.SetEnsurePeersPeriod(250 * time.Millisecond) sw.AddReactor("pex", r) diff --git a/p2p/switch.go b/p2p/switch.go index 7e9c0a9c6..e30060c43 100644 --- a/p2p/switch.go +++ b/p2p/switch.go @@ -7,8 +7,6 @@ import ( "net" "time" - "github.com/spf13/viper" - crypto "github.com/tendermint/go-crypto" "github.com/tendermint/log15" . "github.com/tendermint/tmlibs/common" @@ -19,6 +17,29 @@ const ( reconnectInterval = 3 * time.Second ) +// for node.Config +type Config struct { + ListenAddress string `mapstructure:"laddr"` + Seeds string `mapstructure:"seeds"` + SkipUPNP bool `mapstructure:"skip_upnp"` + AddrBookFile string `mapstructure:"addr_book_file"` + AddrBookStrict bool `mapstructure:"addr_book_strict"` + PexReactor bool `mapstructure:"pex_reactor"` + MaxNumPeers int `mapstructure:"max_num_peers"` + + Peer *PeerConfig `mapstructure:"peer"` +} + +func NewDefaultConfig(rootDir string) *Config { + return &Config{ + ListenAddress: "tcp://0.0.0.0:46656", + AddrBookFile: rootDir + "/addrbook.json", + AddrBookStrict: true, + MaxNumPeers: 50, + Peer: DefaultPeerConfig(), + } +} + type Reactor interface { Service // Start, Stop @@ -62,7 +83,7 @@ incoming messages are received on the reactor. type Switch struct { BaseService - config *viper.Viper + config *Config listeners []Listener reactors map[string]Reactor chDescs []*ChannelDescriptor @@ -81,9 +102,7 @@ var ( ErrSwitchMaxPeersPerIPRange = errors.New("IP range has too many peers") ) -func NewSwitch(config *viper.Viper) *Switch { - setConfigDefaults(config) - +func NewSwitch(config *Config) *Switch { sw := &Switch{ config: config, reactors: make(map[string]Reactor), @@ -209,7 +228,7 @@ func (sw *Switch) AddPeer(peer *Peer) error { return err } - if err := peer.HandshakeTimeout(sw.nodeInfo, time.Duration(sw.config.GetInt(configKeyHandshakeTimeoutSeconds))*time.Second); err != nil { + if err := peer.HandshakeTimeout(sw.nodeInfo, time.Duration(sw.config.Peer.HandshakeTimeout*time.Second)); err != nil { return err } @@ -318,7 +337,7 @@ func (sw *Switch) DialPeerWithAddress(addr *NetAddress, persistent bool) (*Peer, sw.dialing.Set(addr.IP.String(), addr) defer sw.dialing.Delete(addr.IP.String()) - peer, err := newOutboundPeerWithConfig(addr, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey, peerConfigFromGoConfig(sw.config)) + peer, err := newOutboundPeerWithConfig(addr, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey, sw.config.Peer) if err != nil { log.Info("Failed dialing peer", "address", addr, "error", err) return nil, err @@ -430,14 +449,14 @@ func (sw *Switch) listenerRoutine(l Listener) { } // ignore connection if we already have enough - maxPeers := sw.config.GetInt(configKeyMaxNumPeers) + maxPeers := sw.config.MaxNumPeers if maxPeers <= sw.peers.Size() { log.Info("Ignoring inbound connection: already have enough peers", "address", inConn.RemoteAddr().String(), "numPeers", sw.peers.Size(), "max", maxPeers) continue } // New inbound connection! - err := sw.addPeerWithConnectionAndConfig(inConn, peerConfigFromGoConfig(sw.config)) + err := sw.addPeerWithConnectionAndConfig(inConn, sw.config.Peer) if err != nil { log.Notice("Ignoring inbound connection: error while adding peer", "address", inConn.RemoteAddr().String(), "error", err) continue @@ -469,10 +488,10 @@ type SwitchEventDonePeer struct { // If connect==Connect2Switches, the switches will be fully connected. // initSwitch defines how the ith switch should be initialized (ie. with what reactors). // NOTE: panics if any switch fails to start. -func MakeConnectedSwitches(n int, initSwitch func(int, *Switch) *Switch, connect func([]*Switch, int, int)) []*Switch { +func MakeConnectedSwitches(cfg *Config, n int, initSwitch func(int, *Switch) *Switch, connect func([]*Switch, int, int)) []*Switch { switches := make([]*Switch, n) for i := 0; i < n; i++ { - switches[i] = makeSwitch(i, "testing", "123.123.123", initSwitch) + switches[i] = makeSwitch(cfg, i, "testing", "123.123.123", initSwitch) } if err := StartSwitches(switches); err != nil { @@ -526,11 +545,11 @@ func StartSwitches(switches []*Switch) error { return nil } -func makeSwitch(i int, network, version string, initSwitch func(int, *Switch) *Switch) *Switch { +func makeSwitch(cfg *Config, i int, network, version string, initSwitch func(int, *Switch) *Switch) *Switch { privKey := crypto.GenPrivKeyEd25519() // new switch, add reactors // TODO: let the config be passed in? - s := initSwitch(i, NewSwitch(viper.New())) + s := initSwitch(i, NewSwitch(cfg)) s.SetNodeInfo(&NodeInfo{ PubKey: privKey.PubKey().Unwrap().(crypto.PubKeyEd25519), Moniker: Fmt("switch%d", i), @@ -572,23 +591,3 @@ func (sw *Switch) addPeerWithConnectionAndConfig(conn net.Conn, config *PeerConf return nil } - -func peerConfigFromGoConfig(config *viper.Viper) *PeerConfig { - return &PeerConfig{ - AuthEnc: config.GetBool(configKeyAuthEnc), - Fuzz: config.GetBool(configFuzzEnable), - HandshakeTimeout: time.Duration(config.GetInt(configKeyHandshakeTimeoutSeconds)) * time.Second, - DialTimeout: time.Duration(config.GetInt(configKeyDialTimeoutSeconds)) * time.Second, - MConfig: &MConnConfig{ - SendRate: int64(config.GetInt(configKeySendRate)), - RecvRate: int64(config.GetInt(configKeyRecvRate)), - }, - FuzzConfig: &FuzzConnConfig{ - Mode: config.GetInt(configFuzzMode), - MaxDelay: time.Duration(config.GetInt(configFuzzMaxDelayMilliseconds)) * time.Millisecond, - ProbDropRW: config.GetFloat64(configFuzzProbDropRW), - ProbDropConn: config.GetFloat64(configFuzzProbDropConn), - ProbSleep: config.GetFloat64(configFuzzProbSleep), - }, - } -} diff --git a/p2p/switch_test.go b/p2p/switch_test.go index 38529d754..6fb163117 100644 --- a/p2p/switch_test.go +++ b/p2p/switch_test.go @@ -8,8 +8,6 @@ import ( "testing" "time" - "github.com/spf13/viper" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" crypto "github.com/tendermint/go-crypto" @@ -18,12 +16,12 @@ import ( ) var ( - config *viper.Viper + config *Config ) func init() { - config = viper.New() - setConfigDefaults(config) + config = NewDefaultConfig("") + config.PexReactor = true } type PeerMessage struct { @@ -92,7 +90,7 @@ func (tr *TestReactor) getMsgs(chID byte) []PeerMessage { // XXX: note this uses net.Pipe and not a proper TCP conn func makeSwitchPair(t testing.TB, initSwitch func(int, *Switch) *Switch) (*Switch, *Switch) { // Create two switches that will be interconnected. - switches := MakeConnectedSwitches(2, initSwitch, Connect2Switches) + switches := MakeConnectedSwitches(config, 2, initSwitch, Connect2Switches) return switches[0], switches[1] } @@ -163,8 +161,8 @@ func TestSwitches(t *testing.T) { } func TestConnAddrFilter(t *testing.T) { - s1 := makeSwitch(1, "testing", "123.123.123", initSwitchFunc) - s2 := makeSwitch(1, "testing", "123.123.123", initSwitchFunc) + s1 := makeSwitch(config, 1, "testing", "123.123.123", initSwitchFunc) + s2 := makeSwitch(config, 1, "testing", "123.123.123", initSwitchFunc) c1, c2 := net.Pipe() @@ -197,8 +195,8 @@ func TestConnAddrFilter(t *testing.T) { } func TestConnPubKeyFilter(t *testing.T) { - s1 := makeSwitch(1, "testing", "123.123.123", initSwitchFunc) - s2 := makeSwitch(1, "testing", "123.123.123", initSwitchFunc) + s1 := makeSwitch(config, 1, "testing", "123.123.123", initSwitchFunc) + s2 := makeSwitch(config, 1, "testing", "123.123.123", initSwitchFunc) c1, c2 := net.Pipe() @@ -234,7 +232,7 @@ func TestConnPubKeyFilter(t *testing.T) { func TestSwitchStopsNonPersistentPeerOnError(t *testing.T) { assert, require := assert.New(t), require.New(t) - sw := makeSwitch(1, "testing", "123.123.123", initSwitchFunc) + sw := makeSwitch(config, 1, "testing", "123.123.123", initSwitchFunc) sw.Start() defer sw.Stop() @@ -260,7 +258,7 @@ func TestSwitchStopsNonPersistentPeerOnError(t *testing.T) { func TestSwitchReconnectsToPersistentPeer(t *testing.T) { assert, require := assert.New(t), require.New(t) - sw := makeSwitch(1, "testing", "123.123.123", initSwitchFunc) + sw := makeSwitch(config, 1, "testing", "123.123.123", initSwitchFunc) sw.Start() defer sw.Stop() From 57151d6043d3f9eb314727d1a30138cbe3afd652 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Mon, 1 May 2017 22:12:14 -0400 Subject: [PATCH 259/309] p2p: use cmn instead of . --- p2p/addrbook.go | 50 +++++++++++++++++------------------ p2p/listener.go | 20 +++++++------- p2p/peer_set_test.go | 8 +++--- p2p/secret_connection.go | 8 +++--- p2p/secret_connection_test.go | 14 +++++----- p2p/switch.go | 26 +++++++++--------- p2p/switch_test.go | 4 +-- p2p/upnp/probe.go | 24 ++++++++--------- 8 files changed, 77 insertions(+), 77 deletions(-) diff --git a/p2p/addrbook.go b/p2p/addrbook.go index e68cc7b3a..3210273b7 100644 --- a/p2p/addrbook.go +++ b/p2p/addrbook.go @@ -14,8 +14,8 @@ import ( "sync" "time" - . "github.com/tendermint/tmlibs/common" crypto "github.com/tendermint/go-crypto" + cmn "github.com/tendermint/tmlibs/common" ) const ( @@ -80,7 +80,7 @@ const ( // AddrBook - concurrency safe peer address manager. type AddrBook struct { - BaseService + cmn.BaseService mtx sync.Mutex filePath string @@ -107,7 +107,7 @@ func NewAddrBook(filePath string, routabilityStrict bool) *AddrBook { routabilityStrict: routabilityStrict, } am.init() - am.BaseService = *NewBaseService(log, "AddrBook", am) + am.BaseService = *cmn.NewBaseService(log, "AddrBook", am) return am } @@ -214,7 +214,7 @@ func (a *AddrBook) PickAddress(newBias int) *NetAddress { } randIndex-- } - PanicSanity("Should not happen") + cmn.PanicSanity("Should not happen") } else { // pick random New bucket. var bucket map[string]*knownAddress = nil @@ -229,7 +229,7 @@ func (a *AddrBook) PickAddress(newBias int) *NetAddress { } randIndex-- } - PanicSanity("Should not happen") + cmn.PanicSanity("Should not happen") } return nil } @@ -293,10 +293,10 @@ func (a *AddrBook) GetSelection() []*NetAddress { i++ } - numAddresses := MaxInt( - MinInt(minGetSelection, len(allAddr)), + numAddresses := cmn.MaxInt( + cmn.MinInt(minGetSelection, len(allAddr)), len(allAddr)*getSelectionPercent/100) - numAddresses = MinInt(maxGetSelection, numAddresses) + numAddresses = cmn.MinInt(maxGetSelection, numAddresses) // Fisher-Yates shuffle the array. We only need to do the first // `numAddresses' since we are throwing the rest. @@ -338,14 +338,14 @@ func (a *AddrBook) saveToFile(filePath string) { log.Error("Failed to save AddrBook to file", "err", err) return } - err = WriteFileAtomic(filePath, jsonBytes, 0644) + err = cmn.WriteFileAtomic(filePath, jsonBytes, 0644) if err != nil { log.Error("Failed to save AddrBook to file", "file", filePath, "error", err) } } // Returns false if file does not exist. -// Panics if file is corrupt. +// cmn.Panics if file is corrupt. func (a *AddrBook) loadFromFile(filePath string) bool { // If doesn't exist, do nothing. _, err := os.Stat(filePath) @@ -356,14 +356,14 @@ func (a *AddrBook) loadFromFile(filePath string) bool { // Load addrBookJSON{} r, err := os.Open(filePath) if err != nil { - PanicCrisis(Fmt("Error opening file %s: %v", filePath, err)) + cmn.PanicCrisis(cmn.Fmt("Error opening file %s: %v", filePath, err)) } defer r.Close() aJSON := &addrBookJSON{} dec := json.NewDecoder(r) err = dec.Decode(aJSON) if err != nil { - PanicCrisis(Fmt("Error reading file %s: %v", filePath, err)) + cmn.PanicCrisis(cmn.Fmt("Error reading file %s: %v", filePath, err)) } // Restore all the fields... @@ -417,7 +417,7 @@ func (a *AddrBook) getBucket(bucketType byte, bucketIdx int) map[string]*knownAd case bucketTypeOld: return a.addrOld[bucketIdx] default: - PanicSanity("Should not happen") + cmn.PanicSanity("Should not happen") return nil } } @@ -427,7 +427,7 @@ func (a *AddrBook) getBucket(bucketType byte, bucketIdx int) map[string]*knownAd func (a *AddrBook) addToNewBucket(ka *knownAddress, bucketIdx int) bool { // Sanity check if ka.isOld() { - log.Warn(Fmt("Cannot add address already in old bucket to a new bucket: %v", ka)) + log.Warn(cmn.Fmt("Cannot add address already in old bucket to a new bucket: %v", ka)) return false } @@ -461,11 +461,11 @@ func (a *AddrBook) addToNewBucket(ka *knownAddress, bucketIdx int) bool { func (a *AddrBook) addToOldBucket(ka *knownAddress, bucketIdx int) bool { // Sanity check if ka.isNew() { - log.Warn(Fmt("Cannot add new address to old bucket: %v", ka)) + log.Warn(cmn.Fmt("Cannot add new address to old bucket: %v", ka)) return false } if len(ka.Buckets) != 0 { - log.Warn(Fmt("Cannot add already old address to another old bucket: %v", ka)) + log.Warn(cmn.Fmt("Cannot add already old address to another old bucket: %v", ka)) return false } @@ -496,7 +496,7 @@ func (a *AddrBook) addToOldBucket(ka *knownAddress, bucketIdx int) bool { func (a *AddrBook) removeFromBucket(ka *knownAddress, bucketType byte, bucketIdx int) { if ka.BucketType != bucketType { - log.Warn(Fmt("Bucket type mismatch: %v", ka)) + log.Warn(cmn.Fmt("Bucket type mismatch: %v", ka)) return } bucket := a.getBucket(bucketType, bucketIdx) @@ -538,7 +538,7 @@ func (a *AddrBook) pickOldest(bucketType byte, bucketIdx int) *knownAddress { func (a *AddrBook) addAddress(addr, src *NetAddress) { if a.routabilityStrict && !addr.Routable() { - log.Warn(Fmt("Cannot add non-routable address %v", addr)) + log.Warn(cmn.Fmt("Cannot add non-routable address %v", addr)) return } if _, ok := a.ourAddrs[addr.String()]; ok { @@ -578,7 +578,7 @@ func (a *AddrBook) expireNew(bucketIdx int) { for addrStr, ka := range a.addrNew[bucketIdx] { // If an entry is bad, throw it away if ka.isBad() { - log.Notice(Fmt("expiring bad address %v", addrStr)) + log.Notice(cmn.Fmt("expiring bad address %v", addrStr)) a.removeFromBucket(ka, bucketTypeNew, bucketIdx) return } @@ -595,11 +595,11 @@ func (a *AddrBook) expireNew(bucketIdx int) { func (a *AddrBook) moveToOld(ka *knownAddress) { // Sanity check if ka.isOld() { - log.Warn(Fmt("Cannot promote address that is already old %v", ka)) + log.Warn(cmn.Fmt("Cannot promote address that is already old %v", ka)) return } if len(ka.Buckets) == 0 { - log.Warn(Fmt("Cannot promote address that isn't in any new buckets %v", ka)) + log.Warn(cmn.Fmt("Cannot promote address that isn't in any new buckets %v", ka)) return } @@ -624,13 +624,13 @@ func (a *AddrBook) moveToOld(ka *knownAddress) { if !added { added := a.addToNewBucket(oldest, freedBucket) if !added { - log.Warn(Fmt("Could not migrate oldest %v to freedBucket %v", oldest, freedBucket)) + log.Warn(cmn.Fmt("Could not migrate oldest %v to freedBucket %v", oldest, freedBucket)) } } // Finally, add to bucket again. added = a.addToOldBucket(ka, oldBucketIdx) if !added { - log.Warn(Fmt("Could not re-add ka %v to oldBucketIdx %v", ka, oldBucketIdx)) + log.Warn(cmn.Fmt("Could not re-add ka %v to oldBucketIdx %v", ka, oldBucketIdx)) } } } @@ -778,7 +778,7 @@ func (ka *knownAddress) markGood() { func (ka *knownAddress) addBucketRef(bucketIdx int) int { for _, bucket := range ka.Buckets { if bucket == bucketIdx { - log.Warn(Fmt("Bucket already exists in ka.Buckets: %v", ka)) + log.Warn(cmn.Fmt("Bucket already exists in ka.Buckets: %v", ka)) return -1 } } @@ -794,7 +794,7 @@ func (ka *knownAddress) removeBucketRef(bucketIdx int) int { } } if len(buckets) != len(ka.Buckets)-1 { - log.Warn(Fmt("bucketIdx not found in ka.Buckets: %v", ka)) + log.Warn(cmn.Fmt("bucketIdx not found in ka.Buckets: %v", ka)) return -1 } ka.Buckets = buckets diff --git a/p2p/listener.go b/p2p/listener.go index 2acf4d065..9dc9a7e48 100644 --- a/p2p/listener.go +++ b/p2p/listener.go @@ -6,8 +6,8 @@ import ( "strconv" "time" - . "github.com/tendermint/tmlibs/common" "github.com/tendermint/tendermint/p2p/upnp" + cmn "github.com/tendermint/tmlibs/common" ) type Listener interface { @@ -20,7 +20,7 @@ type Listener interface { // Implements Listener type DefaultListener struct { - BaseService + cmn.BaseService listener net.Listener intAddr *NetAddress @@ -37,11 +37,11 @@ const ( func splitHostPort(addr string) (host string, port int) { host, portStr, err := net.SplitHostPort(addr) if err != nil { - PanicSanity(err) + cmn.PanicSanity(err) } port, err = strconv.Atoi(portStr) if err != nil { - PanicSanity(err) + cmn.PanicSanity(err) } return host, port } @@ -63,7 +63,7 @@ func NewDefaultListener(protocol string, lAddr string, skipUPNP bool) Listener { } } if err != nil { - PanicCrisis(err) + cmn.PanicCrisis(err) } // Actual listener local IP & port listenerIP, listenerPort := splitHostPort(listener.Addr().String()) @@ -73,7 +73,7 @@ func NewDefaultListener(protocol string, lAddr string, skipUPNP bool) Listener { var intAddr *NetAddress intAddr, err = NewNetAddressString(lAddr) if err != nil { - PanicCrisis(err) + cmn.PanicCrisis(err) } // Determine external address... @@ -89,7 +89,7 @@ func NewDefaultListener(protocol string, lAddr string, skipUPNP bool) Listener { extAddr = getNaiveExternalAddress(listenerPort) } if extAddr == nil { - PanicCrisis("Could not determine external address!") + cmn.PanicCrisis("Could not determine external address!") } dl := &DefaultListener{ @@ -98,7 +98,7 @@ func NewDefaultListener(protocol string, lAddr string, skipUPNP bool) Listener { extAddr: extAddr, connections: make(chan net.Conn, numBufferedConnections), } - dl.BaseService = *NewBaseService(log, "DefaultListener", dl) + dl.BaseService = *cmn.NewBaseService(log, "DefaultListener", dl) dl.Start() // Started upon construction return dl } @@ -126,7 +126,7 @@ func (l *DefaultListener) listenRoutine() { // listener wasn't stopped, // yet we encountered an error. if err != nil { - PanicCrisis(err) + cmn.PanicCrisis(err) } l.connections <- conn @@ -199,7 +199,7 @@ func getUPNPExternalAddress(externalPort, internalPort int) *NetAddress { func getNaiveExternalAddress(port int) *NetAddress { addrs, err := net.InterfaceAddrs() if err != nil { - PanicCrisis(Fmt("Could not fetch interface addresses: %v", err)) + cmn.PanicCrisis(cmn.Fmt("Could not fetch interface addresses: %v", err)) } for _, a := range addrs { diff --git a/p2p/peer_set_test.go b/p2p/peer_set_test.go index a17f9d658..9214b2eb4 100644 --- a/p2p/peer_set_test.go +++ b/p2p/peer_set_test.go @@ -4,16 +4,16 @@ import ( "math/rand" "testing" - . "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tmlibs/common" ) // Returns an empty dummy peer func randPeer() *Peer { return &Peer{ - Key: RandStr(12), + Key: cmn.RandStr(12), NodeInfo: &NodeInfo{ - RemoteAddr: Fmt("%v.%v.%v.%v:46656", rand.Int()%256, rand.Int()%256, rand.Int()%256, rand.Int()%256), - ListenAddr: Fmt("%v.%v.%v.%v:46656", rand.Int()%256, rand.Int()%256, rand.Int()%256, rand.Int()%256), + RemoteAddr: cmn.Fmt("%v.%v.%v.%v:46656", rand.Int()%256, rand.Int()%256, rand.Int()%256, rand.Int()%256), + ListenAddr: cmn.Fmt("%v.%v.%v.%v:46656", rand.Int()%256, rand.Int()%256, rand.Int()%256, rand.Int()%256), }, } } diff --git a/p2p/secret_connection.go b/p2p/secret_connection.go index 446c4f185..24cae0f61 100644 --- a/p2p/secret_connection.go +++ b/p2p/secret_connection.go @@ -22,7 +22,7 @@ import ( "github.com/tendermint/go-crypto" "github.com/tendermint/go-wire" - . "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tmlibs/common" ) // 2 + 1024 == 1026 total frame size @@ -190,7 +190,7 @@ func genEphKeys() (ephPub, ephPriv *[32]byte) { var err error ephPub, ephPriv, err = box.GenerateKey(crand.Reader) if err != nil { - PanicCrisis("Could not generate ephemeral keypairs") + cmn.PanicCrisis("Could not generate ephemeral keypairs") } return } @@ -198,7 +198,7 @@ func genEphKeys() (ephPub, ephPriv *[32]byte) { func shareEphPubKey(conn io.ReadWriteCloser, locEphPub *[32]byte) (remEphPub *[32]byte, err error) { var err1, err2 error - Parallel( + cmn.Parallel( func() { _, err1 = conn.Write(locEphPub[:]) }, @@ -268,7 +268,7 @@ func shareAuthSignature(sc *SecretConnection, pubKey crypto.PubKeyEd25519, signa var recvMsg authSigMessage var err1, err2 error - Parallel( + cmn.Parallel( func() { msgBytes := wire.BinaryBytes(authSigMessage{pubKey.Wrap(), signature.Wrap()}) _, err1 = sc.Write(msgBytes) diff --git a/p2p/secret_connection_test.go b/p2p/secret_connection_test.go index 3dd962f88..d0d008529 100644 --- a/p2p/secret_connection_test.go +++ b/p2p/secret_connection_test.go @@ -6,7 +6,7 @@ import ( "testing" "github.com/tendermint/go-crypto" - . "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tmlibs/common" ) type dummyConn struct { @@ -37,7 +37,7 @@ func makeSecretConnPair(tb testing.TB) (fooSecConn, barSecConn *SecretConnection barPrvKey := crypto.GenPrivKeyEd25519() barPubKey := barPrvKey.PubKey().Unwrap().(crypto.PubKeyEd25519) - Parallel( + cmn.Parallel( func() { var err error fooSecConn, err = MakeSecretConnection(fooConn, fooPrvKey) @@ -81,8 +81,8 @@ func TestSecretConnectionReadWrite(t *testing.T) { // Pre-generate the things to write (for foo & bar) for i := 0; i < 100; i++ { - fooWrites = append(fooWrites, RandStr((RandInt()%(dataMaxSize*5))+1)) - barWrites = append(barWrites, RandStr((RandInt()%(dataMaxSize*5))+1)) + fooWrites = append(fooWrites, cmn.RandStr((cmn.RandInt()%(dataMaxSize*5))+1)) + barWrites = append(barWrites, cmn.RandStr((cmn.RandInt()%(dataMaxSize*5))+1)) } // A helper that will run with (fooConn, fooWrites, fooReads) and vice versa @@ -96,7 +96,7 @@ func TestSecretConnectionReadWrite(t *testing.T) { return } // In parallel, handle reads and writes - Parallel( + cmn.Parallel( func() { // Node writes for _, nodeWrite := range nodeWrites { @@ -131,7 +131,7 @@ func TestSecretConnectionReadWrite(t *testing.T) { } // Run foo & bar in parallel - Parallel( + cmn.Parallel( genNodeRunner(fooConn, fooWrites, &fooReads), genNodeRunner(barConn, barWrites, &barReads), ) @@ -174,7 +174,7 @@ func TestSecretConnectionReadWrite(t *testing.T) { func BenchmarkSecretConnection(b *testing.B) { b.StopTimer() fooSecConn, barSecConn := makeSecretConnPair(b) - fooWriteText := RandStr(dataMaxSize) + fooWriteText := cmn.RandStr(dataMaxSize) // Consume reads from bar's reader go func() { readBuffer := make([]byte, dataMaxSize) diff --git a/p2p/switch.go b/p2p/switch.go index e30060c43..cf5c63657 100644 --- a/p2p/switch.go +++ b/p2p/switch.go @@ -9,7 +9,7 @@ import ( crypto "github.com/tendermint/go-crypto" "github.com/tendermint/log15" - . "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tmlibs/common" ) const ( @@ -41,7 +41,7 @@ func NewDefaultConfig(rootDir string) *Config { } type Reactor interface { - Service // Start, Stop + cmn.Service // Start, Stop SetSwitch(*Switch) GetChannels() []*ChannelDescriptor @@ -53,13 +53,13 @@ type Reactor interface { //-------------------------------------- type BaseReactor struct { - BaseService // Provides Start, Stop, .Quit - Switch *Switch + cmn.BaseService // Provides Start, Stop, .Quit + Switch *Switch } func NewBaseReactor(log log15.Logger, name string, impl Reactor) *BaseReactor { return &BaseReactor{ - BaseService: *NewBaseService(log, name, impl), + BaseService: *cmn.NewBaseService(log, name, impl), Switch: nil, } } @@ -81,7 +81,7 @@ or more `Channels`. So while sending outgoing messages is typically performed o incoming messages are received on the reactor. */ type Switch struct { - BaseService + cmn.BaseService config *Config listeners []Listener @@ -89,7 +89,7 @@ type Switch struct { chDescs []*ChannelDescriptor reactorsByCh map[byte]Reactor peers *PeerSet - dialing *CMap + dialing *cmn.CMap nodeInfo *NodeInfo // our node info nodePrivKey crypto.PrivKeyEd25519 // our node privkey @@ -109,10 +109,10 @@ func NewSwitch(config *Config) *Switch { chDescs: make([]*ChannelDescriptor, 0), reactorsByCh: make(map[byte]Reactor), peers: NewPeerSet(), - dialing: NewCMap(), + dialing: cmn.NewCMap(), nodeInfo: nil, } - sw.BaseService = *NewBaseService(log, "P2P Switch", sw) + sw.BaseService = *cmn.NewBaseService(log, "P2P Switch", sw) return sw } @@ -124,7 +124,7 @@ func (sw *Switch) AddReactor(name string, reactor Reactor) Reactor { for _, chDesc := range reactorChannels { chID := chDesc.ID if sw.reactorsByCh[chID] != nil { - PanicSanity(fmt.Sprintf("Channel %X has multiple reactors %v & %v", chID, sw.reactorsByCh[chID], reactor)) + cmn.PanicSanity(fmt.Sprintf("Channel %X has multiple reactors %v & %v", chID, sw.reactorsByCh[chID], reactor)) } sw.chDescs = append(sw.chDescs, chDesc) sw.reactorsByCh[chID] = reactor @@ -552,11 +552,11 @@ func makeSwitch(cfg *Config, i int, network, version string, initSwitch func(int s := initSwitch(i, NewSwitch(cfg)) s.SetNodeInfo(&NodeInfo{ PubKey: privKey.PubKey().Unwrap().(crypto.PubKeyEd25519), - Moniker: Fmt("switch%d", i), + Moniker: cmn.Fmt("switch%d", i), Network: network, Version: version, - RemoteAddr: Fmt("%v:%v", network, rand.Intn(64512)+1023), - ListenAddr: Fmt("%v:%v", network, rand.Intn(64512)+1023), + RemoteAddr: cmn.Fmt("%v:%v", network, rand.Intn(64512)+1023), + ListenAddr: cmn.Fmt("%v:%v", network, rand.Intn(64512)+1023), }) s.SetNodePrivKey(privKey) return s diff --git a/p2p/switch_test.go b/p2p/switch_test.go index 6fb163117..d2f616922 100644 --- a/p2p/switch_test.go +++ b/p2p/switch_test.go @@ -12,7 +12,7 @@ import ( "github.com/stretchr/testify/require" crypto "github.com/tendermint/go-crypto" wire "github.com/tendermint/go-wire" - . "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tmlibs/common" ) var ( @@ -320,7 +320,7 @@ func BenchmarkSwitches(b *testing.B) { } } - log.Warn(Fmt("success: %v, failure: %v", numSuccess, numFailure)) + log.Warn(cmn.Fmt("success: %v, failure: %v", numSuccess, numFailure)) // Allow everything to flush before stopping switches & closing connections. b.StopTimer() diff --git a/p2p/upnp/probe.go b/p2p/upnp/probe.go index 5488de587..14dd496ac 100644 --- a/p2p/upnp/probe.go +++ b/p2p/upnp/probe.go @@ -6,7 +6,7 @@ import ( "net" "time" - . "github.com/tendermint/tmlibs/common" + cmn "github.com/tendermint/tmlibs/common" ) type UPNPCapabilities struct { @@ -19,19 +19,19 @@ func makeUPNPListener(intPort int, extPort int) (NAT, net.Listener, net.IP, erro if err != nil { return nil, nil, nil, errors.New(fmt.Sprintf("NAT upnp could not be discovered: %v", err)) } - log.Info(Fmt("ourIP: %v", nat.(*upnpNAT).ourIP)) + log.Info(cmn.Fmt("ourIP: %v", nat.(*upnpNAT).ourIP)) ext, err := nat.GetExternalAddress() if err != nil { return nat, nil, nil, errors.New(fmt.Sprintf("External address error: %v", err)) } - log.Info(Fmt("External address: %v", ext)) + log.Info(cmn.Fmt("External address: %v", ext)) port, err := nat.AddPortMapping("tcp", extPort, intPort, "Tendermint UPnP Probe", 0) if err != nil { return nat, nil, ext, errors.New(fmt.Sprintf("Port mapping error: %v", err)) } - log.Info(Fmt("Port mapping mapped: %v", port)) + log.Info(cmn.Fmt("Port mapping mapped: %v", port)) // also run the listener, open for all remote addresses. listener, err := net.Listen("tcp", fmt.Sprintf(":%v", intPort)) @@ -46,17 +46,17 @@ func testHairpin(listener net.Listener, extAddr string) (supportsHairpin bool) { go func() { inConn, err := listener.Accept() if err != nil { - log.Notice(Fmt("Listener.Accept() error: %v", err)) + log.Notice(cmn.Fmt("Listener.Accept() error: %v", err)) return } - log.Info(Fmt("Accepted incoming connection: %v -> %v", inConn.LocalAddr(), inConn.RemoteAddr())) + log.Info(cmn.Fmt("Accepted incoming connection: %v -> %v", inConn.LocalAddr(), inConn.RemoteAddr())) buf := make([]byte, 1024) n, err := inConn.Read(buf) if err != nil { - log.Notice(Fmt("Incoming connection read error: %v", err)) + log.Notice(cmn.Fmt("Incoming connection read error: %v", err)) return } - log.Info(Fmt("Incoming connection read %v bytes: %X", n, buf)) + log.Info(cmn.Fmt("Incoming connection read %v bytes: %X", n, buf)) if string(buf) == "test data" { supportsHairpin = true return @@ -66,16 +66,16 @@ func testHairpin(listener net.Listener, extAddr string) (supportsHairpin bool) { // Establish outgoing outConn, err := net.Dial("tcp", extAddr) if err != nil { - log.Notice(Fmt("Outgoing connection dial error: %v", err)) + log.Notice(cmn.Fmt("Outgoing connection dial error: %v", err)) return } n, err := outConn.Write([]byte("test data")) if err != nil { - log.Notice(Fmt("Outgoing connection write error: %v", err)) + log.Notice(cmn.Fmt("Outgoing connection write error: %v", err)) return } - log.Info(Fmt("Outgoing connection wrote %v bytes", n)) + log.Info(cmn.Fmt("Outgoing connection wrote %v bytes", n)) // Wait for data receipt time.Sleep(1 * time.Second) @@ -97,7 +97,7 @@ func Probe() (caps UPNPCapabilities, err error) { defer func() { err = nat.DeletePortMapping("tcp", intPort, extPort) if err != nil { - log.Warn(Fmt("Port mapping delete error: %v", err)) + log.Warn(cmn.Fmt("Port mapping delete error: %v", err)) } listener.Close() }() From 7db7bbe464f9fb8465bf18c8c29448ac401bf74f Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Mon, 1 May 2017 22:14:37 -0400 Subject: [PATCH 260/309] node: ConfigFromViper --- cmd/tendermint/commands/replay.go | 4 ++-- cmd/tendermint/commands/root.go | 6 +----- node/node.go | 24 ++++++++++++++---------- node/node_test.go | 3 ++- 4 files changed, 19 insertions(+), 18 deletions(-) diff --git a/cmd/tendermint/commands/replay.go b/cmd/tendermint/commands/replay.go index 611a96a63..9b3fbbae1 100644 --- a/cmd/tendermint/commands/replay.go +++ b/cmd/tendermint/commands/replay.go @@ -11,7 +11,7 @@ var replayCmd = &cobra.Command{ Short: "Replay messages from WAL", Run: func(cmd *cobra.Command, args []string) { config := getConfig() - consensus.RunReplayFile(config.Config, config.Consensus, false) + consensus.RunReplayFile(&config.Config, config.Consensus, false) }, } @@ -20,7 +20,7 @@ var replayConsoleCmd = &cobra.Command{ Short: "Replay messages from WAL in a console", Run: func(cmd *cobra.Command, args []string) { config := getConfig() - consensus.RunReplayFile(config.Config, config.Consensus, true) + consensus.RunReplayFile(&config.Config, config.Consensus, true) }, } diff --git a/cmd/tendermint/commands/root.go b/cmd/tendermint/commands/root.go index 515ef9dc6..24ff6281e 100644 --- a/cmd/tendermint/commands/root.go +++ b/cmd/tendermint/commands/root.go @@ -23,11 +23,7 @@ func init() { // unmarshal viper into the Tendermint config func getConfig() *node.Config { - config := new(node.Config) - if err := viperConfig.Unmarshal(config); err != nil { - panic(err) - } - return config + return node.ConfigFromViper(viperConfig) } //global flag diff --git a/node/node.go b/node/node.go index 742c9984c..e4f945ee3 100644 --- a/node/node.go +++ b/node/node.go @@ -37,23 +37,31 @@ import ( type Config struct { // Top level options use an anonymous struct - *cfg.Config `mapstructure:",squash"` + cfg.Config `mapstructure:",squash"` // Options for services - P2P *p2p.NetworkConfig `mapstructure:"p2p"` - Mempool *mempl.Config `mapstructure:"mempool"` - Consensus *consensus.Config `mapstructure:"consensus"` + P2P *p2p.Config `mapstructure:"p2p"` + Mempool *mempl.Config `mapstructure:"mempool"` + Consensus *consensus.Config `mapstructure:"consensus"` } func NewDefaultConfig(rootDir string) *Config { return &Config{ - Config: cfg.NewDefaultConfig(rootDir), + Config: *cfg.NewDefaultConfig(rootDir), P2P: p2p.NewDefaultConfig(rootDir), Mempool: mempl.NewDefaultConfig(rootDir), Consensus: consensus.NewDefaultConfig(rootDir), } } +func ConfigFromViper(viperConfig *viper.Viper) *Config { + tmConfig := new(Config) + if err := viperConfig.Unmarshal(tmConfig); err != nil { + panic(err) + } + return tmConfig +} + type Node struct { cmn.BaseService @@ -156,11 +164,7 @@ func NewNode(config *Config, privValidator *types.PrivValidator, clientCreator p } consensusReactor := consensus.NewConsensusReactor(consensusState, fastSync) - // Make p2p network switch - // TODO : p2pConfig := config.P2P - p2pConfig := viper.New() - - sw := p2p.NewSwitch(p2pConfig) + sw := p2p.NewSwitch(config.P2P) sw.AddReactor("MEMPOOL", mempoolReactor) sw.AddReactor("BLOCKCHAIN", bcReactor) sw.AddReactor("CONSENSUS", consensusReactor) diff --git a/node/node_test.go b/node/node_test.go index 2ab8e8dc6..ba9ac7234 100644 --- a/node/node_test.go +++ b/node/node_test.go @@ -8,7 +8,8 @@ import ( ) func TestNodeStartStop(t *testing.T) { - config := tendermint_test.ResetConfig("node_node_test") + viperConfig := tendermint_test.ResetConfig("node_node_test") + config := ConfigFromViper(viperConfig) // Create & start node n := NewNodeDefault(config) From 1ef7c1d25b49c44679926439ff92bd83833781d3 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Mon, 1 May 2017 22:39:17 -0400 Subject: [PATCH 261/309] cmd: fixes for new config --- cmd/tendermint/commands/replay.go | 2 - .../commands/reset_priv_validator.go | 2 - cmd/tendermint/commands/root.go | 13 +++---- cmd/tendermint/commands/run_node.go | 37 ++++++------------- cmd/tendermint/commands/show_validator.go | 1 - consensus/state.go | 1 + 6 files changed, 18 insertions(+), 38 deletions(-) diff --git a/cmd/tendermint/commands/replay.go b/cmd/tendermint/commands/replay.go index 9b3fbbae1..227931152 100644 --- a/cmd/tendermint/commands/replay.go +++ b/cmd/tendermint/commands/replay.go @@ -10,7 +10,6 @@ var replayCmd = &cobra.Command{ Use: "replay", Short: "Replay messages from WAL", Run: func(cmd *cobra.Command, args []string) { - config := getConfig() consensus.RunReplayFile(&config.Config, config.Consensus, false) }, } @@ -19,7 +18,6 @@ var replayConsoleCmd = &cobra.Command{ Use: "replay_console", Short: "Replay messages from WAL in a console", Run: func(cmd *cobra.Command, args []string) { - config := getConfig() consensus.RunReplayFile(&config.Config, config.Consensus, true) }, } diff --git a/cmd/tendermint/commands/reset_priv_validator.go b/cmd/tendermint/commands/reset_priv_validator.go index 8f03c11d5..c84ebcf8b 100644 --- a/cmd/tendermint/commands/reset_priv_validator.go +++ b/cmd/tendermint/commands/reset_priv_validator.go @@ -29,14 +29,12 @@ func init() { // XXX: this is totally unsafe. // it's only suitable for testnets. func resetAll(cmd *cobra.Command, args []string) { - config := getConfig() ResetAll(config.DBDir, config.PrivValidatorFile, log) } // XXX: this is totally unsafe. // it's only suitable for testnets. func resetPrivValidator(cmd *cobra.Command, args []string) { - config := getConfig() resetPrivValidatorLocal(config.PrivValidatorFile, log) } diff --git a/cmd/tendermint/commands/root.go b/cmd/tendermint/commands/root.go index 24ff6281e..9278bdd5a 100644 --- a/cmd/tendermint/commands/root.go +++ b/cmd/tendermint/commands/root.go @@ -4,6 +4,7 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" + cfg "github.com/tendermint/tendermint/config/tendermint" "github.com/tendermint/tendermint/node" "github.com/tendermint/tmlibs/logger" ) @@ -15,8 +16,7 @@ var ( ) func init() { - // Set config to be used as defaults by flags. - // This will be overwritten by whatever is unmarshalled from viper + viperConfig = cfg.GetConfig("") config = node.NewDefaultConfig("") } @@ -26,21 +26,18 @@ func getConfig() *node.Config { return node.ConfigFromViper(viperConfig) } -//global flag -var logLevel string - var RootCmd = &cobra.Command{ Use: "tendermint", Short: "Tendermint Core (BFT Consensus) in Go", PersistentPreRun: func(cmd *cobra.Command, args []string) { // set the log level - config := getConfig() + config = getConfig() logger.SetLogLevel(config.LogLevel) }, } func init() { //parse flag and set config - RootCmd.PersistentFlags().StringVar(&logLevel, "log_level", config.LogLevel, "Log level") - viperConfig.BindPFlag("log_level", RootCmd.Flags().Lookup("log_level")) + RootCmd.PersistentFlags().String("log_level", config.LogLevel, "Log level") + viperConfig.BindPFlag("log_level", RootCmd.PersistentFlags().Lookup("log_level")) } diff --git a/cmd/tendermint/commands/run_node.go b/cmd/tendermint/commands/run_node.go index c4d06efbf..cf8233ef2 100644 --- a/cmd/tendermint/commands/run_node.go +++ b/cmd/tendermint/commands/run_node.go @@ -19,66 +19,53 @@ var runNodeCmd = &cobra.Command{ RunE: runNode, } -//flags -var ( - moniker string - nodeLaddr string - seeds string - fastSync bool - skipUPNP bool - rpcLaddr string - grpcLaddr string - proxyApp string - abciTransport string - pex bool -) - func init() { // bind flags // node flags - runNodeCmd.Flags().StringVar(&moniker, "moniker", config.Moniker, + runNodeCmd.Flags().String("moniker", config.Moniker, "Node Name") viperConfig.BindPFlag("moniker", runNodeCmd.Flags().Lookup("moniker")) - runNodeCmd.Flags().BoolVar(&fastSync, "fast_sync", config.FastSync, + runNodeCmd.Flags().Bool("fast_sync", config.FastSync, "Fast blockchain syncing") viperConfig.BindPFlag("fast_sync", runNodeCmd.Flags().Lookup("fast_sync")) // abci flags - runNodeCmd.Flags().StringVar(&proxyApp, "proxy_app", config.ProxyApp, + runNodeCmd.Flags().String("proxy_app", config.ProxyApp, "Proxy app address, or 'nilapp' or 'dummy' for local testing.") viperConfig.BindPFlag("proxy_app", runNodeCmd.Flags().Lookup("proxy_app")) - runNodeCmd.Flags().StringVar(&abciTransport, "abci", config.ABCI, + runNodeCmd.Flags().String("abci", config.ABCI, "Specify abci transport (socket | grpc)") viperConfig.BindPFlag("abci", runNodeCmd.Flags().Lookup("abci")) // rpc flags - runNodeCmd.Flags().StringVar(&rpcLaddr, "rpc_laddr", config.RPCListenAddress, + runNodeCmd.Flags().String("rpc_laddr", config.RPCListenAddress, "RPC listen address. Port required") viperConfig.BindPFlag("rpc_laddr", runNodeCmd.Flags().Lookup("rpc_laddr")) - runNodeCmd.Flags().StringVar(&grpcLaddr, "grpc_laddr", config.GRPCListenAddress, + runNodeCmd.Flags().String("grpc_laddr", config.GRPCListenAddress, "GRPC listen address (BroadcastTx only). Port required") viperConfig.BindPFlag("grpc_laddr", runNodeCmd.Flags().Lookup("grpc_laddr")) // p2p flags - runNodeCmd.Flags().StringVar(&nodeLaddr, "p2p.laddr", config.P2P.ListenAddress, + runNodeCmd.Flags().String("p2p.laddr", config.P2P.ListenAddress, "Node listen address. (0.0.0.0:0 means any interface, any port)") viperConfig.BindPFlag("p2p.laddr", runNodeCmd.Flags().Lookup("p2p.laddr")) - runNodeCmd.Flags().StringVar(&seeds, "p2p.seeds", config.P2P.Seeds, + runNodeCmd.Flags().String("p2p.seeds", config.P2P.Seeds, "Comma delimited host:port seed nodes") viperConfig.BindPFlag("p2p.seeds", runNodeCmd.Flags().Lookup("p2p.seeds")) - runNodeCmd.Flags().BoolVar(&skipUPNP, "p2p.skip_upnp", config.P2P.SkipUPNP, + runNodeCmd.Flags().Bool("p2p.skip_upnp", config.P2P.SkipUPNP, "Skip UPNP configuration") viperConfig.BindPFlag("p2p.skip_upnp", runNodeCmd.Flags().Lookup("p2p.skip_upnp")) // feature flags - runNodeCmd.Flags().BoolVar(&pex, "p2p.pex", config.P2P.PexReactor, + runNodeCmd.Flags().Bool("p2p.pex", config.P2P.PexReactor, "Enable Peer-Exchange (dev feature)") + viperConfig.BindPFlag("p2p.pex", runNodeCmd.Flags().Lookup("p2p.pex")) RootCmd.AddCommand(runNodeCmd) } @@ -120,7 +107,7 @@ func runNode(cmd *cobra.Command, args []string) error { } // Create & start node - n := node.NewNodeDefault(getConfig()) + n := node.NewNodeDefault(config) if _, err := n.Start(); err != nil { return fmt.Errorf("Failed to start node: %v", err) } else { diff --git a/cmd/tendermint/commands/show_validator.go b/cmd/tendermint/commands/show_validator.go index 16dfe1ff4..b741ba8c0 100644 --- a/cmd/tendermint/commands/show_validator.go +++ b/cmd/tendermint/commands/show_validator.go @@ -20,7 +20,6 @@ func init() { } func showValidator(cmd *cobra.Command, args []string) { - config := getConfig() privValidator := types.LoadOrGenPrivValidator(config.PrivValidatorFile) pubKeyJSONBytes, _ := data.ToJSON(privValidator.PubKey) fmt.Println(string(pubKeyJSONBytes)) diff --git a/consensus/state.go b/consensus/state.go index a77e8a669..99c1112df 100644 --- a/consensus/state.go +++ b/consensus/state.go @@ -302,6 +302,7 @@ type ConsensusState struct { } func NewConsensusState(config *Config, state *sm.State, proxyAppConn proxy.AppConnConsensus, blockStore types.BlockStore, mempool types.Mempool) *ConsensusState { + config.chainID = state.ChainID // Set ChainID cs := &ConsensusState{ config: config, proxyAppConn: proxyAppConn, From 6afee8f117513be100e5879a35e6068a5a5f9826 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Mon, 1 May 2017 23:15:12 -0400 Subject: [PATCH 262/309] rpc: fix tests --- config/tendermint/config.go | 12 ++++++------ config/tendermint_test/config.go | 1 + consensus/state.go | 4 ++-- rpc/client/rpc_test.go | 8 +++----- rpc/test/client_test.go | 5 ++--- rpc/test/helpers.go | 25 +++++++++++++------------ 6 files changed, 27 insertions(+), 28 deletions(-) diff --git a/config/tendermint/config.go b/config/tendermint/config.go index 9f9a06849..e6757f5be 100644 --- a/config/tendermint/config.go +++ b/config/tendermint/config.go @@ -72,12 +72,12 @@ func GetConfig(rootDir string) *viper.Viper { config.SetDefault("grpc_laddr", "") config.SetDefault("tx_index", "kv") - config.SetDefault("network.listen_addr", "tcp://0.0.0.0:46656") - config.SetDefault("network.seeds", "") - config.SetDefault("network.skip_upnp", false) - config.SetDefault("network.addrbook_file", rootDir+"/addrbook.json") - config.SetDefault("network.addrbook_strict", true) // disable to allow connections locally - config.SetDefault("network.pex_reactor", false) // enable for peer exchange + config.SetDefault("p2p.laddr", "tcp://0.0.0.0:46656") + config.SetDefault("p2p.seeds", "") + config.SetDefault("p2p.skip_upnp", false) + config.SetDefault("p2p.addrbook_file", rootDir+"/addrbook.json") + config.SetDefault("p2p.addrbook_strict", true) // disable to allow connections locally + config.SetDefault("p2p.pex_reactor", false) // enable for peer exchange config.SetDefault("consensus.wal_file", rootDir+"/data/cs.wal/wal") config.SetDefault("consensus.wal_light", false) diff --git a/config/tendermint_test/config.go b/config/tendermint_test/config.go index 7c3ff72c0..6eb8f53d8 100644 --- a/config/tendermint_test/config.go +++ b/config/tendermint_test/config.go @@ -90,6 +90,7 @@ func ResetConfig(localPath string) *viper.Viper { config.SetDefault("filter_peers", false) config.SetDefault("tx_index", "kv") + config.SetDefault("p2p.laddr", "tcp://0.0.0.0:36656") config.SetDefault("p2p.skip_upnp", true) config.SetDefault("p2p.addrbook_file", rootDir+"/addrbook.json") config.SetDefault("p2p.addrbook_strict", true) // disable to allow connections locally diff --git a/consensus/state.go b/consensus/state.go index 99c1112df..5a9bff3f3 100644 --- a/consensus/state.go +++ b/consensus/state.go @@ -40,8 +40,8 @@ type Config struct { SkipTimeoutCommit bool `mapstructure:"skip_timeout_commit"` // BlockSize - MaxBlockSizeTxs int `mapstructure:"block_size_txs"` - MaxBlockSizeBytes int `mapstructure:"block_size_bytes"` + MaxBlockSizeTxs int `mapstructure:"max_block_size_txs"` + MaxBlockSizeBytes int `mapstructure:"max_block_size_bytes"` // TODO: This probably shouldn't be exposed but it makes it // easy to write tests for the wal/replay diff --git a/rpc/client/rpc_test.go b/rpc/client/rpc_test.go index 4c21a4afc..2586b4687 100644 --- a/rpc/client/rpc_test.go +++ b/rpc/client/rpc_test.go @@ -13,7 +13,7 @@ import ( ) func getHTTPClient() *client.HTTP { - rpcAddr := rpctest.GetConfig().GetString("rpc_laddr") + rpcAddr := rpctest.GetConfig().RPCListenAddress return client.NewHTTP(rpcAddr, "/websocket") } @@ -32,10 +32,10 @@ func GetClients() []client.Client { // Make sure status is correct (we connect properly) func TestStatus(t *testing.T) { for i, c := range GetClients() { - chainID := rpctest.GetConfig().GetString("chain_id") + moniker := rpctest.GetConfig().Moniker status, err := c.Status() require.Nil(t, err, "%d: %+v", i, err) - assert.Equal(t, chainID, status.NodeInfo.Network) + assert.Equal(t, moniker, status.NodeInfo.Moniker) } } @@ -77,12 +77,10 @@ func TestDumpConsensusState(t *testing.T) { func TestGenesisAndValidators(t *testing.T) { for i, c := range GetClients() { - chainID := rpctest.GetConfig().GetString("chain_id") // make sure this is the right genesis file gen, err := c.Genesis() require.Nil(t, err, "%d: %+v", i, err) - assert.Equal(t, chainID, gen.Genesis.ChainID) // get the genesis validator require.Equal(t, 1, len(gen.Genesis.Validators)) gval := gen.Genesis.Validators[0] diff --git a/rpc/test/client_test.go b/rpc/test/client_test.go index bd972f919..ecc2f36b9 100644 --- a/rpc/test/client_test.go +++ b/rpc/test/client_test.go @@ -39,12 +39,11 @@ func TestJSONStatus(t *testing.T) { } func testStatus(t *testing.T, client rpc.HTTPClient) { - chainID := GetConfig().GetString("chain_id") + moniker := GetConfig().Moniker result := new(ctypes.ResultStatus) _, err := client.Call("status", map[string]interface{}{}, result) require.Nil(t, err) - - assert.Equal(t, chainID, result.NodeInfo.Network) + assert.Equal(t, moniker, status.NodeInfo.Moniker) } //-------------------------------------------------------------------------------- diff --git a/rpc/test/helpers.go b/rpc/test/helpers.go index 11a228bb1..c5542fa7c 100644 --- a/rpc/test/helpers.go +++ b/rpc/test/helpers.go @@ -10,7 +10,6 @@ import ( "testing" "time" - "github.com/spf13/viper" "github.com/stretchr/testify/require" logger "github.com/tendermint/tmlibs/logger" @@ -24,7 +23,7 @@ import ( "github.com/tendermint/tendermint/types" ) -var config *viper.Viper +var config *nm.Config const tmLogLevel = "error" @@ -54,40 +53,42 @@ func makeAddrs() (string, string, string) { } // GetConfig returns a config for the test cases as a singleton -func GetConfig() *viper.Viper { +func GetConfig() *nm.Config { if config == nil { pathname := makePathname() - config = tendermint_test.ResetConfig(pathname) + viperConfig := tendermint_test.ResetConfig(pathname) // Shut up the logging logger.SetLogLevel(tmLogLevel) // and we use random ports to run in parallel tm, rpc, grpc := makeAddrs() - config.Set("node_laddr", tm) - config.Set("rpc_laddr", rpc) - config.Set("grpc_laddr", grpc) + viperConfig.Set("p2p.laddr", tm) + viperConfig.Set("rpc_laddr", rpc) + viperConfig.Set("grpc_laddr", grpc) + + config = nm.ConfigFromViper(viperConfig) } return config } // GetURIClient gets a uri client pointing to the test tendermint rpc func GetURIClient() *client.URIClient { - rpcAddr := GetConfig().GetString("rpc_laddr") + rpcAddr := GetConfig().RPCListenAddress return client.NewURIClient(rpcAddr) } // GetJSONClient gets a http/json client pointing to the test tendermint rpc func GetJSONClient() *client.JSONRPCClient { - rpcAddr := GetConfig().GetString("rpc_laddr") + rpcAddr := GetConfig().RPCListenAddress return client.NewJSONRPCClient(rpcAddr) } func GetGRPCClient() core_grpc.BroadcastAPIClient { - grpcAddr := config.GetString("grpc_laddr") + grpcAddr := config.GRPCListenAddress return core_grpc.StartGRPCClient(grpcAddr) } func GetWSClient() *client.WSClient { - rpcAddr := GetConfig().GetString("rpc_laddr") + rpcAddr := GetConfig().RPCListenAddress wsc := client.NewWSClient(rpcAddr, "/websocket") if _, err := wsc.Start(); err != nil { panic(err) @@ -107,7 +108,7 @@ func StartTendermint(app abci.Application) *nm.Node { func NewTendermint(app abci.Application) *nm.Node { // Create & start node config := GetConfig() - privValidatorFile := config.GetString("priv_validator_file") + privValidatorFile := config.PrivValidatorFile privValidator := types.LoadOrGenPrivValidator(privValidatorFile) papp := proxy.NewLocalClientCreator(app) node := nm.NewNode(config, privValidator, papp) From 92bafa7ecd8e4b9da9f51c175c16e2dd852abc07 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Tue, 2 May 2017 00:43:49 -0400 Subject: [PATCH 263/309] consensus: fix tests --- consensus/byzantine_test.go | 9 ++---- consensus/common_test.go | 50 ++++++++++++++++++++----------- consensus/height_vote_set_test.go | 9 +++--- consensus/mempool_test.go | 3 +- consensus/reactor_test.go | 8 ++--- consensus/replay_test.go | 40 +++++++++++-------------- consensus/state.go | 11 ++----- consensus/state_test.go | 29 +++++++++--------- p2p/switch.go | 11 +++---- 9 files changed, 84 insertions(+), 86 deletions(-) diff --git a/consensus/byzantine_test.go b/consensus/byzantine_test.go index b9edf4635..e33c13d47 100644 --- a/consensus/byzantine_test.go +++ b/consensus/byzantine_test.go @@ -5,9 +5,6 @@ import ( "testing" "time" - "github.com/spf13/viper" - - "github.com/tendermint/tendermint/config/tendermint_test" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/types" . "github.com/tendermint/tmlibs/common" @@ -15,7 +12,7 @@ import ( ) func init() { - config = tendermint_test.ResetConfig("consensus_byzantine_test") + config = ResetConfig("consensus_byzantine_test") } //---------------------------------------------- @@ -36,7 +33,7 @@ func TestByzantine(t *testing.T) { switches := make([]*p2p.Switch, N) for i := 0; i < N; i++ { - switches[i] = p2p.NewSwitch(viper.New()) + switches[i] = p2p.NewSwitch(config.P2P) } reactors := make([]p2p.Reactor, N) @@ -80,7 +77,7 @@ func TestByzantine(t *testing.T) { reactors[i] = conRI } - p2p.MakeConnectedSwitches(N, func(i int, s *p2p.Switch) *p2p.Switch { + p2p.MakeConnectedSwitches(config.P2P, N, func(i int, s *p2p.Switch) *p2p.Switch { // ignore new switch s, we already made ours switches[i].AddReactor("CONSENSUS", reactors[i]) return switches[i] diff --git a/consensus/common_test.go b/consensus/common_test.go index 7ebef78e9..ed7be9f36 100644 --- a/consensus/common_test.go +++ b/consensus/common_test.go @@ -11,11 +11,10 @@ import ( "testing" "time" - "github.com/spf13/viper" - abcicli "github.com/tendermint/abci/client" abci "github.com/tendermint/abci/types" bc "github.com/tendermint/tendermint/blockchain" + cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/config/tendermint_test" mempl "github.com/tendermint/tendermint/mempool" "github.com/tendermint/tendermint/p2p" @@ -29,7 +28,7 @@ import ( ) // genesis, chain_id, priv_val -var config *viper.Viper // NOTE: must be reset for each _test.go file +var config *NodeConfig // NOTE: must be reset for each _test.go file var ensureTimeout = time.Duration(2) func ensureDir(dir string, mode os.FileMode) { @@ -38,6 +37,23 @@ func ensureDir(dir string, mode os.FileMode) { } } +type NodeConfig struct { + cfg.Config `mapstructure:",squash"` + P2P *p2p.Config `mapstructure:"p2p"` + Mempool *mempl.Config `mapstructure:"mempool"` + Consensus *Config `mapstructure:"consensus"` +} + +// TODO: This is the same as NodeConfig. Should we move the configs to types (?) +func ResetConfig(name string) *NodeConfig { + viperConfig := tendermint_test.ResetConfig(name) + config := new(NodeConfig) + if err := viperConfig.Unmarshal(config); err != nil { + panic(err) + } + return config +} + //------------------------------------------------------------------------------- // validator stub (a dummy consensus peer we control) @@ -66,7 +82,7 @@ func (vs *validatorStub) signVote(voteType byte, hash []byte, header types.PartS Type: voteType, BlockID: types.BlockID{hash, header}, } - err := vs.PrivValidator.SignVote(config.GetString("chain_id"), vote) + err := vs.PrivValidator.SignVote(config.ChainID, vote) return vote, err } @@ -117,7 +133,7 @@ func decideProposal(cs1 *ConsensusState, vs *validatorStub, height, round int) ( // Make proposal polRound, polBlockID := cs1.Votes.POLInfo() proposal = types.NewProposal(height, round, blockParts.Header(), polRound, polBlockID) - if err := vs.SignProposal(config.GetString("chain_id"), proposal); err != nil { + if err := vs.SignProposal(config.ChainID, proposal); err != nil { panic(err) } return @@ -235,7 +251,7 @@ func newConsensusState(state *sm.State, pv *types.PrivValidator, app abci.Applic return newConsensusStateWithConfig(config, state, pv, app) } -func newConsensusStateWithConfig(thisConfig *viper.Viper, state *sm.State, pv *types.PrivValidator, app abci.Application) *ConsensusState { +func newConsensusStateWithConfig(thisConfig *NodeConfig, state *sm.State, pv *types.PrivValidator, app abci.Application) *ConsensusState { // Get BlockStore blockDB := dbm.NewMemDB() blockStore := bc.NewBlockStore(blockDB) @@ -246,10 +262,10 @@ func newConsensusStateWithConfig(thisConfig *viper.Viper, state *sm.State, pv *t proxyAppConnCon := abcicli.NewLocalClient(mtx, app) // Make Mempool - mempool := mempl.NewMempool(thisConfig, proxyAppConnMem) + mempool := mempl.NewMempool(thisConfig.Mempool, proxyAppConnMem) // Make ConsensusReactor - cs := NewConsensusState(thisConfig, state, proxyAppConnCon, blockStore, mempool) + cs := NewConsensusState(thisConfig.Consensus, state, proxyAppConnCon, blockStore, mempool) cs.SetPrivValidator(pv) evsw := types.NewEventSwitch() @@ -258,8 +274,8 @@ func newConsensusStateWithConfig(thisConfig *viper.Viper, state *sm.State, pv *t return cs } -func loadPrivValidator(conf *viper.Viper) *types.PrivValidator { - privValidatorFile := conf.GetString("priv_validator_file") +func loadPrivValidator(config *NodeConfig) *types.PrivValidator { + privValidatorFile := config.PrivValidatorFile ensureDir(path.Dir(privValidatorFile), 0700) privValidator := types.LoadOrGenPrivValidator(privValidatorFile) privValidator.Reset() @@ -268,7 +284,7 @@ func loadPrivValidator(conf *viper.Viper) *types.PrivValidator { func fixedConsensusState() *ConsensusState { stateDB := dbm.NewMemDB() - state := sm.MakeGenesisStateFromFile(stateDB, config.GetString("genesis_file")) + state := sm.MakeGenesisStateFromFile(stateDB, config.GenesisFile) privValidator := loadPrivValidator(config) cs := newConsensusState(state, privValidator, counter.NewCounterApplication(true)) return cs @@ -276,7 +292,7 @@ func fixedConsensusState() *ConsensusState { func fixedConsensusStateDummy() *ConsensusState { stateDB := dbm.NewMemDB() - state := sm.MakeGenesisStateFromFile(stateDB, config.GetString("genesis_file")) + state := sm.MakeGenesisStateFromFile(stateDB, config.GenesisFile) privValidator := loadPrivValidator(config) cs := newConsensusState(state, privValidator, dummy.NewDummyApplication()) return cs @@ -321,8 +337,8 @@ func randConsensusNet(nValidators int, testName string, tickerFunc func() Timeou db := dbm.NewMemDB() // each state needs its own db state := sm.MakeGenesisState(db, genDoc) state.Save() - thisConfig := tendermint_test.ResetConfig(Fmt("%s_%d", testName, i)) - ensureDir(path.Dir(thisConfig.GetString("cs_wal_file")), 0700) // dir for wal + thisConfig := ResetConfig(Fmt("%s_%d", testName, i)) + ensureDir(path.Dir(thisConfig.Consensus.WalFile), 0700) // dir for wal css[i] = newConsensusStateWithConfig(thisConfig, state, privVals[i], appFunc()) css[i].SetTimeoutTicker(tickerFunc()) } @@ -337,8 +353,8 @@ func randConsensusNetWithPeers(nValidators, nPeers int, testName string, tickerF db := dbm.NewMemDB() // each state needs its own db state := sm.MakeGenesisState(db, genDoc) state.Save() - thisConfig := tendermint_test.ResetConfig(Fmt("%s_%d", testName, i)) - ensureDir(path.Dir(thisConfig.GetString("cs_wal_file")), 0700) // dir for wal + thisConfig := ResetConfig(Fmt("%s_%d", testName, i)) + ensureDir(path.Dir(thisConfig.Consensus.WalFile), 0700) // dir for wal var privVal *types.PrivValidator if i < nValidators { privVal = privVals[i] @@ -381,7 +397,7 @@ func randGenesisDoc(numValidators int, randPower bool, minPower int64) (*types.G sort.Sort(types.PrivValidatorsByAddress(privValidators)) return &types.GenesisDoc{ GenesisTime: time.Now(), - ChainID: config.GetString("chain_id"), + ChainID: config.ChainID, Validators: validators, }, privValidators } diff --git a/consensus/height_vote_set_test.go b/consensus/height_vote_set_test.go index a86cba4f2..f1ef8b7ff 100644 --- a/consensus/height_vote_set_test.go +++ b/consensus/height_vote_set_test.go @@ -3,19 +3,18 @@ package consensus import ( "testing" - . "github.com/tendermint/tmlibs/common" - "github.com/tendermint/tendermint/config/tendermint_test" "github.com/tendermint/tendermint/types" + . "github.com/tendermint/tmlibs/common" ) func init() { - config = tendermint_test.ResetConfig("consensus_height_vote_set_test") + config = ResetConfig("consensus_height_vote_set_test") } func TestPeerCatchupRounds(t *testing.T) { valSet, privVals := types.RandValidatorSet(10, 1) - hvs := NewHeightVoteSet(config.GetString("chain_id"), 1, valSet) + hvs := NewHeightVoteSet(config.ChainID, 1, valSet) vote999_0 := makeVoteHR(t, 1, 999, privVals, 0) added, err := hvs.AddVote(vote999_0, "peer1") @@ -52,7 +51,7 @@ func makeVoteHR(t *testing.T, height, round int, privVals []*types.PrivValidator Type: types.VoteTypePrecommit, BlockID: types.BlockID{[]byte("fakehash"), types.PartSetHeader{}}, } - chainID := config.GetString("chain_id") + chainID := config.ChainID err := privVal.SignVote(chainID, vote) if err != nil { panic(Fmt("Error signing vote: %v", err)) diff --git a/consensus/mempool_test.go b/consensus/mempool_test.go index 15e6a1550..327ad733c 100644 --- a/consensus/mempool_test.go +++ b/consensus/mempool_test.go @@ -6,14 +6,13 @@ import ( "time" abci "github.com/tendermint/abci/types" - "github.com/tendermint/tendermint/config/tendermint_test" "github.com/tendermint/tendermint/types" . "github.com/tendermint/tmlibs/common" ) func init() { - config = tendermint_test.ResetConfig("consensus_mempool_test") + config = ResetConfig("consensus_mempool_test") } func TestTxConcurrentWithCommit(t *testing.T) { diff --git a/consensus/reactor_test.go b/consensus/reactor_test.go index fdf590151..f52194588 100644 --- a/consensus/reactor_test.go +++ b/consensus/reactor_test.go @@ -6,8 +6,6 @@ import ( "testing" "time" - "github.com/tendermint/tendermint/config/tendermint_test" - "github.com/tendermint/abci/example/dummy" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/types" @@ -15,7 +13,7 @@ import ( ) func init() { - config = tendermint_test.ResetConfig("consensus_reactor_test") + config = ResetConfig("consensus_reactor_test") } //---------------------------------------------- @@ -41,7 +39,7 @@ func startConsensusNet(t *testing.T, css []*ConsensusState, N int, subscribeEven } } // make connected switches and start all reactors - p2p.MakeConnectedSwitches(N, func(i int, s *p2p.Switch) *p2p.Switch { + p2p.MakeConnectedSwitches(config.P2P, N, func(i int, s *p2p.Switch) *p2p.Switch { s.AddReactor("CONSENSUS", reactors[i]) return s }, p2p.Connect2Switches) @@ -236,7 +234,7 @@ func TestReactorWithTimeoutCommit(t *testing.T) { css := randConsensusNet(N, "consensus_reactor_with_timeout_commit_test", newMockTickerFunc(false), newCounter) // override default SkipTimeoutCommit == true for tests for i := 0; i < N; i++ { - css[i].timeoutParams.SkipTimeoutCommit = false + css[i].config.SkipTimeoutCommit = false } reactors, eventChans := startConsensusNet(t, css, N-1, false) diff --git a/consensus/replay_test.go b/consensus/replay_test.go index 626de6bbf..9ab04359c 100644 --- a/consensus/replay_test.go +++ b/consensus/replay_test.go @@ -12,12 +12,9 @@ import ( "testing" "time" - "github.com/spf13/viper" - "github.com/tendermint/abci/example/dummy" "github.com/tendermint/go-crypto" "github.com/tendermint/go-wire" - "github.com/tendermint/tendermint/config/tendermint_test" "github.com/tendermint/tendermint/proxy" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" @@ -26,7 +23,7 @@ import ( ) func init() { - config = tendermint_test.ResetConfig("consensus_replay_test") + config = ResetConfig("consensus_replay_test") } // These tests ensure we can always recover from failure at any part of the consensus process. @@ -136,7 +133,7 @@ func waitForBlock(newBlockCh chan interface{}, thisCase *testCase, i int) { func runReplayTest(t *testing.T, cs *ConsensusState, walFile string, newBlockCh chan interface{}, thisCase *testCase, i int) { - cs.config.Set("cs_wal_file", walFile) + cs.config.WalFile = walFile started, err := cs.Start() if err != nil { t.Fatalf("Cannot start consensus: %v", err) @@ -309,7 +306,7 @@ func TestHandshakeReplayNone(t *testing.T) { // Make some blocks. Start a fresh app and apply nBlocks blocks. Then restart the app and sync it up with the remaining blocks func testHandshakeReplay(t *testing.T, nBlocks int, mode uint) { - config := tendermint_test.ResetConfig("proxy_test_") + config := ResetConfig("proxy_test_") // copy the many_blocks file walBody, err := cmn.ReadFile(path.Join(data_dir, "many_blocks.cswal")) @@ -317,10 +314,10 @@ func testHandshakeReplay(t *testing.T, nBlocks int, mode uint) { t.Fatal(err) } walFile := writeWAL(string(walBody)) - config.Set("cs_wal_file", walFile) + config.Consensus.WalFile = walFile - privVal := types.LoadPrivValidator(config.GetString("priv_validator_file")) - testPartSize = config.GetInt("block_part_size") + privVal := types.LoadPrivValidator(config.PrivValidatorFile) + testPartSize = config.Consensus.BlockPartSize wal, err := NewWAL(walFile, false) if err != nil { @@ -339,19 +336,19 @@ func testHandshakeReplay(t *testing.T, nBlocks int, mode uint) { latestAppHash := buildTMStateFromChain(config, state, chain, mode) // make a new client creator - dummyApp := dummy.NewPersistentDummyApplication(path.Join(config.GetString("db_dir"), "2")) + dummyApp := dummy.NewPersistentDummyApplication(path.Join(config.DBDir, "2")) clientCreator2 := proxy.NewLocalClientCreator(dummyApp) if nBlocks > 0 { // run nBlocks against a new client to build up the app state. // use a throwaway tendermint state - proxyApp := proxy.NewAppConns(config, clientCreator2, nil) + proxyApp := proxy.NewAppConns(clientCreator2, nil) state, _ := stateAndStore(config, privVal.PubKey) buildAppStateFromChain(proxyApp, state, chain, nBlocks, mode) } // now start the app using the handshake - it should sync - handshaker := NewHandshaker(config, state, store) - proxyApp := proxy.NewAppConns(config, clientCreator2, handshaker) + handshaker := NewHandshaker(state, store) + proxyApp := proxy.NewAppConns(clientCreator2, handshaker) if _, err := proxyApp.Start(); err != nil { t.Fatalf("Error starting proxy app connections: %v", err) } @@ -418,10 +415,10 @@ func buildAppStateFromChain(proxyApp proxy.AppConns, } -func buildTMStateFromChain(config *viper.Viper, state *sm.State, chain []*types.Block, mode uint) []byte { +func buildTMStateFromChain(config *NodeConfig, state *sm.State, chain []*types.Block, mode uint) []byte { // run the whole chain against this client to build up the tendermint state - clientCreator := proxy.NewLocalClientCreator(dummy.NewPersistentDummyApplication(path.Join(config.GetString("db_dir"), "1"))) - proxyApp := proxy.NewAppConns(config, clientCreator, nil) // sm.NewHandshaker(config, state, store, ReplayLastBlock)) + clientCreator := proxy.NewLocalClientCreator(dummy.NewPersistentDummyApplication(path.Join(config.DBDir, "1"))) + proxyApp := proxy.NewAppConns(clientCreator, nil) // sm.NewHandshaker(config, state, store, ReplayLastBlock)) if _, err := proxyApp.Start(); err != nil { panic(err) } @@ -615,10 +612,9 @@ func makeBlockchain(t *testing.T, chainID string, nBlocks int, privVal *types.Pr } // fresh state and mock store -func stateAndStore(config *viper.Viper, pubKey crypto.PubKey) (*sm.State, *mockBlockStore) { +func stateAndStore(config *NodeConfig, pubKey crypto.PubKey) (*sm.State, *mockBlockStore) { stateDB := dbm.NewMemDB() - - state := sm.MakeGenesisStateFromFile(stateDB, config.GetString("genesis_file")) + state := sm.MakeGenesisStateFromFile(stateDB, config.GenesisFile()) store := NewMockBlockStore(config) return state, store } @@ -627,13 +623,13 @@ func stateAndStore(config *viper.Viper, pubKey crypto.PubKey) (*sm.State, *mockB // mock block store type mockBlockStore struct { - config *viper.Viper + config *NodeConfig chain []*types.Block commits []*types.Commit } // TODO: NewBlockStore(db.NewMemDB) ... -func NewMockBlockStore(config *viper.Viper) *mockBlockStore { +func NewMockBlockStore(config *NodeConfig) *mockBlockStore { return &mockBlockStore{config, nil, nil} } @@ -642,7 +638,7 @@ func (bs *mockBlockStore) LoadBlock(height int) *types.Block { return bs.chain[h func (bs *mockBlockStore) LoadBlockMeta(height int) *types.BlockMeta { block := bs.chain[height-1] return &types.BlockMeta{ - BlockID: types.BlockID{block.Hash(), block.MakePartSet(bs.config.GetInt("block_part_size")).Header()}, + BlockID: types.BlockID{block.Hash(), block.MakePartSet(bs.config.Consensus.BlockPartSize).Header()}, Header: block.Header, } } diff --git a/consensus/state.go b/consensus/state.go index 5a9bff3f3..e7b6381c2 100644 --- a/consensus/state.go +++ b/consensus/state.go @@ -46,8 +46,6 @@ type Config struct { // TODO: This probably shouldn't be exposed but it makes it // easy to write tests for the wal/replay BlockPartSize int `mapstructure:"block_part_size"` - - chainID string } func NewDefaultConfig(rootDir string) *Config { @@ -81,10 +79,6 @@ func NewTestConfig(rootDir string) *Config { return config } -func (cfg *Config) SetChainID(chainID string) { - cfg.chainID = chainID -} - // Wait this long for a proposal func (cfg *Config) Propose(round int) time.Duration { return time.Duration(cfg.TimeoutPropose+cfg.TimeoutProposeDelta*round) * time.Millisecond @@ -302,7 +296,6 @@ type ConsensusState struct { } func NewConsensusState(config *Config, state *sm.State, proxyAppConn proxy.AppConnConsensus, blockStore types.BlockStore, mempool types.Mempool) *ConsensusState { - config.chainID = state.ChainID // Set ChainID cs := &ConsensusState{ config: config, proxyAppConn: proxyAppConn, @@ -558,7 +551,7 @@ func (cs *ConsensusState) reconstructLastCommit(state *sm.State) { return } seenCommit := cs.blockStore.LoadSeenCommit(state.LastBlockHeight) - lastPrecommits := types.NewVoteSet(cs.config.chainID, state.LastBlockHeight, seenCommit.Round(), types.VoteTypePrecommit, state.LastValidators) + lastPrecommits := types.NewVoteSet(cs.state.ChainID, state.LastBlockHeight, seenCommit.Round(), types.VoteTypePrecommit, state.LastValidators) for _, precommit := range seenCommit.Precommits { if precommit == nil { continue @@ -629,7 +622,7 @@ func (cs *ConsensusState) updateToState(state *sm.State) { cs.LockedRound = 0 cs.LockedBlock = nil cs.LockedBlockParts = nil - cs.Votes = NewHeightVoteSet(cs.config.chainID, height, validators) + cs.Votes = NewHeightVoteSet(state.ChainID, height, validators) cs.CommitRound = -1 cs.LastCommit = lastPrecommits cs.LastValidators = state.LastValidators diff --git a/consensus/state_test.go b/consensus/state_test.go index 2d5ed410b..990622738 100644 --- a/consensus/state_test.go +++ b/consensus/state_test.go @@ -6,17 +6,16 @@ import ( "testing" "time" - "github.com/tendermint/tendermint/config/tendermint_test" "github.com/tendermint/tendermint/types" . "github.com/tendermint/tmlibs/common" ) func init() { - config = tendermint_test.ResetConfig("consensus_state_test") + config = ResetConfig("consensus_state_test") } -func (tp *TimeoutParams) ensureProposeTimeout() time.Duration { - return time.Duration(tp.Propose0*2) * time.Millisecond +func (config *Config) ensureProposeTimeout() time.Duration { + return time.Duration(config.TimeoutPropose*2) * time.Millisecond } /* @@ -126,7 +125,7 @@ func TestEnterProposeNoPrivValidator(t *testing.T) { startTestRound(cs, height, round) // if we're not a validator, EnterPropose should timeout - ticker := time.NewTicker(cs.timeoutParams.ensureProposeTimeout()) + ticker := time.NewTicker(cs.config.ensureProposeTimeout()) select { case <-timeoutCh: case <-ticker.C: @@ -167,7 +166,7 @@ func TestEnterProposeYesPrivValidator(t *testing.T) { } // if we're a validator, enterPropose should not timeout - ticker := time.NewTicker(cs.timeoutParams.ensureProposeTimeout()) + ticker := time.NewTicker(cs.config.ensureProposeTimeout()) select { case <-timeoutCh: panic("Expected EnterPropose not to timeout") @@ -181,7 +180,7 @@ func TestBadProposal(t *testing.T) { height, round := cs1.Height, cs1.Round vs2 := vss[1] - partSize := config.GetInt("block_part_size") + partSize := config.Consensus.BlockPartSize proposalCh := subscribeToEvent(cs1.evsw, "tester", types.EventStringCompleteProposal(), 1) voteCh := subscribeToEvent(cs1.evsw, "tester", types.EventStringVote(), 1) @@ -201,7 +200,7 @@ func TestBadProposal(t *testing.T) { propBlock.AppHash = stateHash propBlockParts := propBlock.MakePartSet(partSize) proposal := types.NewProposal(vs2.Height, round, propBlockParts.Header(), -1, types.BlockID{}) - if err := vs2.SignProposal(config.GetString("chain_id"), proposal); err != nil { + if err := vs2.SignProposal(config.ChainID, proposal); err != nil { t.Fatal("failed to sign bad proposal", err) } @@ -328,7 +327,7 @@ func TestLockNoPOL(t *testing.T) { vs2 := vss[1] height := cs1.Height - partSize := config.GetInt("block_part_size") + partSize := config.Consensus.BlockPartSize timeoutProposeCh := subscribeToEvent(cs1.evsw, "tester", types.EventStringTimeoutPropose(), 1) timeoutWaitCh := subscribeToEvent(cs1.evsw, "tester", types.EventStringTimeoutWait(), 1) @@ -494,7 +493,7 @@ func TestLockPOLRelock(t *testing.T) { cs1, vss := randConsensusState(4) vs2, vs3, vs4 := vss[1], vss[2], vss[3] - partSize := config.GetInt("block_part_size") + partSize := config.Consensus.BlockPartSize timeoutProposeCh := subscribeToEvent(cs1.evsw, "tester", types.EventStringTimeoutPropose(), 1) timeoutWaitCh := subscribeToEvent(cs1.evsw, "tester", types.EventStringTimeoutWait(), 1) @@ -606,7 +605,7 @@ func TestLockPOLUnlock(t *testing.T) { cs1, vss := randConsensusState(4) vs2, vs3, vs4 := vss[1], vss[2], vss[3] - partSize := config.GetInt("block_part_size") + partSize := config.Consensus.BlockPartSize proposalCh := subscribeToEvent(cs1.evsw, "tester", types.EventStringCompleteProposal(), 1) timeoutProposeCh := subscribeToEvent(cs1.evsw, "tester", types.EventStringTimeoutPropose(), 1) @@ -701,7 +700,7 @@ func TestLockPOLSafety1(t *testing.T) { cs1, vss := randConsensusState(4) vs2, vs3, vs4 := vss[1], vss[2], vss[3] - partSize := config.GetInt("block_part_size") + partSize := config.Consensus.BlockPartSize proposalCh := subscribeToEvent(cs1.evsw, "tester", types.EventStringCompleteProposal(), 1) timeoutProposeCh := subscribeToEvent(cs1.evsw, "tester", types.EventStringTimeoutPropose(), 1) @@ -822,7 +821,7 @@ func TestLockPOLSafety2(t *testing.T) { cs1, vss := randConsensusState(4) vs2, vs3, vs4 := vss[1], vss[2], vss[3] - partSize := config.GetInt("block_part_size") + partSize := config.Consensus.BlockPartSize proposalCh := subscribeToEvent(cs1.evsw, "tester", types.EventStringCompleteProposal(), 1) timeoutProposeCh := subscribeToEvent(cs1.evsw, "tester", types.EventStringTimeoutPropose(), 1) @@ -878,7 +877,7 @@ func TestLockPOLSafety2(t *testing.T) { // in round 2 we see the polkad block from round 0 newProp := types.NewProposal(height, 2, propBlockParts0.Header(), 0, propBlockID1) - if err := vs3.SignProposal(config.GetString("chain_id"), newProp); err != nil { + if err := vs3.SignProposal(config.ChainID, newProp); err != nil { t.Fatal(err) } cs1.SetProposalAndBlock(newProp, propBlock0, propBlockParts0, "some peer") @@ -997,7 +996,7 @@ func TestHalt1(t *testing.T) { cs1, vss := randConsensusState(4) vs2, vs3, vs4 := vss[1], vss[2], vss[3] - partSize := config.GetInt("block_part_size") + partSize := config.Consensus.BlockPartSize proposalCh := subscribeToEvent(cs1.evsw, "tester", types.EventStringCompleteProposal(), 1) timeoutWaitCh := subscribeToEvent(cs1.evsw, "tester", types.EventStringTimeoutWait(), 1) diff --git a/p2p/switch.go b/p2p/switch.go index cf5c63657..49d817f20 100644 --- a/p2p/switch.go +++ b/p2p/switch.go @@ -27,7 +27,7 @@ type Config struct { PexReactor bool `mapstructure:"pex_reactor"` MaxNumPeers int `mapstructure:"max_num_peers"` - Peer *PeerConfig `mapstructure:"peer"` + peer *PeerConfig // Not exposed } func NewDefaultConfig(rootDir string) *Config { @@ -36,7 +36,7 @@ func NewDefaultConfig(rootDir string) *Config { AddrBookFile: rootDir + "/addrbook.json", AddrBookStrict: true, MaxNumPeers: 50, - Peer: DefaultPeerConfig(), + peer: DefaultPeerConfig(), } } @@ -103,6 +103,7 @@ var ( ) func NewSwitch(config *Config) *Switch { + config.peer = DefaultPeerConfig() sw := &Switch{ config: config, reactors: make(map[string]Reactor), @@ -228,7 +229,7 @@ func (sw *Switch) AddPeer(peer *Peer) error { return err } - if err := peer.HandshakeTimeout(sw.nodeInfo, time.Duration(sw.config.Peer.HandshakeTimeout*time.Second)); err != nil { + if err := peer.HandshakeTimeout(sw.nodeInfo, time.Duration(sw.config.peer.HandshakeTimeout*time.Second)); err != nil { return err } @@ -337,7 +338,7 @@ func (sw *Switch) DialPeerWithAddress(addr *NetAddress, persistent bool) (*Peer, sw.dialing.Set(addr.IP.String(), addr) defer sw.dialing.Delete(addr.IP.String()) - peer, err := newOutboundPeerWithConfig(addr, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey, sw.config.Peer) + peer, err := newOutboundPeerWithConfig(addr, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey, sw.config.peer) if err != nil { log.Info("Failed dialing peer", "address", addr, "error", err) return nil, err @@ -456,7 +457,7 @@ func (sw *Switch) listenerRoutine(l Listener) { } // New inbound connection! - err := sw.addPeerWithConnectionAndConfig(inConn, sw.config.Peer) + err := sw.addPeerWithConnectionAndConfig(inConn, sw.config.peer) if err != nil { log.Notice("Ignoring inbound connection: error while adding peer", "address", inConn.RemoteAddr().String(), "error", err) continue From f217f2b2c559035e93bce3feee9be6b9a1b55c63 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Tue, 2 May 2017 03:51:36 -0400 Subject: [PATCH 264/309] cleanup run_node flags --- cmd/tendermint/commands/root.go | 4 +- cmd/tendermint/commands/run_node.go | 59 ++++++++++------------------- 2 files changed, 22 insertions(+), 41 deletions(-) diff --git a/cmd/tendermint/commands/root.go b/cmd/tendermint/commands/root.go index 9278bdd5a..1f69a2158 100644 --- a/cmd/tendermint/commands/root.go +++ b/cmd/tendermint/commands/root.go @@ -17,8 +17,6 @@ var ( func init() { viperConfig = cfg.GetConfig("") - config = node.NewDefaultConfig("") - } // unmarshal viper into the Tendermint config @@ -38,6 +36,6 @@ var RootCmd = &cobra.Command{ func init() { //parse flag and set config - RootCmd.PersistentFlags().String("log_level", config.LogLevel, "Log level") + RootCmd.PersistentFlags().String("log_level", viperConfig.GetString("log_level"), "Log level") viperConfig.BindPFlag("log_level", RootCmd.PersistentFlags().Lookup("log_level")) } diff --git a/cmd/tendermint/commands/run_node.go b/cmd/tendermint/commands/run_node.go index cf8233ef2..58cdd3cf2 100644 --- a/cmd/tendermint/commands/run_node.go +++ b/cmd/tendermint/commands/run_node.go @@ -7,7 +7,6 @@ import ( "github.com/spf13/cobra" - //cfg "github.com/tendermint/tendermint/config/tendermint" "github.com/tendermint/tendermint/node" "github.com/tendermint/tendermint/types" cmn "github.com/tendermint/tmlibs/common" @@ -19,53 +18,38 @@ var runNodeCmd = &cobra.Command{ RunE: runNode, } +func registerRunNodeFlagString(flagName, desc string) { + runNodeCmd.Flags().String(flagName, viperConfig.GetString(flagName), desc) + viperConfig.BindPFlag(flagName, runNodeCmd.Flags().Lookup(flagName)) +} + +func registerRunNodeFlagBool(flagName, desc string) { + runNodeCmd.Flags().Bool(flagName, viperConfig.GetBool(flagName), desc) + viperConfig.BindPFlag(flagName, runNodeCmd.Flags().Lookup(flagName)) +} + func init() { // bind flags // node flags - runNodeCmd.Flags().String("moniker", config.Moniker, - "Node Name") - viperConfig.BindPFlag("moniker", runNodeCmd.Flags().Lookup("moniker")) - - runNodeCmd.Flags().Bool("fast_sync", config.FastSync, - "Fast blockchain syncing") - viperConfig.BindPFlag("fast_sync", runNodeCmd.Flags().Lookup("fast_sync")) + registerRunNodeFlagString("moniker", "Node Name") + registerRunNodeFlagBool("fast_sync", "Fast blockchain syncing") // abci flags - runNodeCmd.Flags().String("proxy_app", config.ProxyApp, - "Proxy app address, or 'nilapp' or 'dummy' for local testing.") - viperConfig.BindPFlag("proxy_app", runNodeCmd.Flags().Lookup("proxy_app")) - - runNodeCmd.Flags().String("abci", config.ABCI, - "Specify abci transport (socket | grpc)") - viperConfig.BindPFlag("abci", runNodeCmd.Flags().Lookup("abci")) + registerRunNodeFlagString("proxy_app", "Proxy app address, or 'nilapp' or 'dummy' for local testing.") + registerRunNodeFlagString("abci", "Specify abci transport (socket | grpc)") // rpc flags - runNodeCmd.Flags().String("rpc_laddr", config.RPCListenAddress, - "RPC listen address. Port required") - viperConfig.BindPFlag("rpc_laddr", runNodeCmd.Flags().Lookup("rpc_laddr")) - - runNodeCmd.Flags().String("grpc_laddr", config.GRPCListenAddress, - "GRPC listen address (BroadcastTx only). Port required") - viperConfig.BindPFlag("grpc_laddr", runNodeCmd.Flags().Lookup("grpc_laddr")) + registerRunNodeFlagString("rpc_laddr", "RPC listen address. Port required") + registerRunNodeFlagString("grpc_laddr", "GRPC listen address (BroadcastTx only). Port required") // p2p flags - runNodeCmd.Flags().String("p2p.laddr", config.P2P.ListenAddress, - "Node listen address. (0.0.0.0:0 means any interface, any port)") - viperConfig.BindPFlag("p2p.laddr", runNodeCmd.Flags().Lookup("p2p.laddr")) - - runNodeCmd.Flags().String("p2p.seeds", config.P2P.Seeds, - "Comma delimited host:port seed nodes") - viperConfig.BindPFlag("p2p.seeds", runNodeCmd.Flags().Lookup("p2p.seeds")) - - runNodeCmd.Flags().Bool("p2p.skip_upnp", config.P2P.SkipUPNP, - "Skip UPNP configuration") - viperConfig.BindPFlag("p2p.skip_upnp", runNodeCmd.Flags().Lookup("p2p.skip_upnp")) + registerRunNodeFlagString("p2p.laddr", "Node listen address. (0.0.0.0:0 means any interface, any port)") + registerRunNodeFlagString("p2p.seeds", "Comma delimited host:port seed nodes") + registerRunNodeFlagBool("p2p.skip_upnp", "Skip UPNP configuration") // feature flags - runNodeCmd.Flags().Bool("p2p.pex", config.P2P.PexReactor, - "Enable Peer-Exchange (dev feature)") - viperConfig.BindPFlag("p2p.pex", runNodeCmd.Flags().Lookup("p2p.pex")) + registerRunNodeFlagBool("p2p.pex", "Enable Peer-Exchange (dev feature)") RootCmd.AddCommand(runNodeCmd) } @@ -101,8 +85,7 @@ func runNode(cmd *cobra.Command, args []string) error { if genDoc.ChainID == "" { return fmt.Errorf("Genesis doc %v must include non-empty chain_id", genDocFile) } - - // config.SetChainID("chain_id", genDoc.ChainID) TODO + config.ChainID = genDoc.ChainID } } From 604bf03f3a539f5f27434642bf116c6fa7a3ee0f Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Thu, 4 May 2017 20:07:08 +0200 Subject: [PATCH 265/309] Pulled out all config structs (except p2p.PeerConfig) into config package --- config/config.go | 153 +++++++++++++++++++++++++++- config/tendermint/config.go | 122 ---------------------- config/tendermint_test/config.go | 170 ------------------------------- config/toml.go | 129 +++++++++++++++++++++++ consensus/replay_file.go | 4 +- consensus/state.go | 86 +--------------- glide.lock | 9 +- glide.yaml | 1 + mempool/mempool.go | 5 +- mempool/reactor.go | 21 +--- node/node.go | 36 +------ p2p/switch.go | 41 ++------ 12 files changed, 310 insertions(+), 467 deletions(-) delete mode 100644 config/tendermint/config.go delete mode 100644 config/tendermint_test/config.go create mode 100644 config/toml.go diff --git a/config/config.go b/config/config.go index 5f4f28a83..531ef9a50 100644 --- a/config/config.go +++ b/config/config.go @@ -1,7 +1,41 @@ package config -// Config struct for a Tendermint node +import ( + "time" + + "github.com/tendermint/tendermint/types" +) + type Config struct { + // Top level options use an anonymous struct + *BaseConfig `mapstructure:",squash"` + + // Options for services + P2P *P2PConfig `mapstructure:"p2p"` + Mempool *MempoolConfig `mapstructure:"mempool"` + Consensus *ConsensusConfig `mapstructure:"consensus"` +} + +func DefaultConfig(rootDir string) *Config { + return &Config{ + BaseConfig: DefaultBaseConfig(rootDir), + P2P: DefaultP2PConfig(rootDir), + Mempool: DefaultMempoolConfig(rootDir), + Consensus: DefaultConsensusConfig(rootDir), + } +} + +func TestConfig(rootDir string) *Config { + return &Config{ + BaseConfig: DefaultBaseConfig(rootDir), + P2P: DefaultP2PConfig(rootDir), + Mempool: DefaultMempoolConfig(rootDir), + Consensus: TestConsensusConfig(rootDir), + } +} + +// BaseConfig struct for a Tendermint node +type BaseConfig struct { // The ID of the chain to join (should be signed with every transaction and vote) ChainID string `mapstructure:"chain_id"` @@ -53,8 +87,8 @@ type Config struct { GRPCListenAddress string `mapstructure:"grpc_laddr"` } -func NewDefaultConfig(rootDir string) *Config { - return &Config{ +func DefaultBaseConfig(rootDir string) *BaseConfig { + return &BaseConfig{ GenesisFile: rootDir + "/genesis.json", PrivValidatorFile: rootDir + "/priv_validator.json", Moniker: "anonymous", @@ -71,3 +105,116 @@ func NewDefaultConfig(rootDir string) *Config { GRPCListenAddress: "", } } + +type P2PConfig struct { + ListenAddress string `mapstructure:"laddr"` + Seeds string `mapstructure:"seeds"` + SkipUPNP bool `mapstructure:"skip_upnp"` + AddrBookFile string `mapstructure:"addr_book_file"` + AddrBookStrict bool `mapstructure:"addr_book_strict"` + PexReactor bool `mapstructure:"pex_reactor"` + MaxNumPeers int `mapstructure:"max_num_peers"` +} + +func DefaultP2PConfig(rootDir string) *P2PConfig { + return &P2PConfig{ + ListenAddress: "tcp://0.0.0.0:46656", + AddrBookFile: rootDir + "/addrbook.json", + AddrBookStrict: true, + MaxNumPeers: 50, + } +} + +type MempoolConfig struct { + Recheck bool `mapstructure:"recheck"` // true + RecheckEmpty bool `mapstructure:"recheck_empty"` // true + Broadcast bool `mapstructure:"broadcast"` // true + WalDir string `mapstructure:"wal_dir"` // +} + +func DefaultMempoolConfig(rootDir string) *MempoolConfig { + return &MempoolConfig{ + Recheck: true, + RecheckEmpty: true, + Broadcast: true, + WalDir: rootDir + "/data/mempool.wal", + } +} + +// ConsensusConfig holds timeouts and details about the WAL, the block structure, +// and timeouts in the consensus protocol. +type ConsensusConfig struct { + WalFile string `mapstructure:"wal_file"` + WalLight bool `mapstructure:"wal_light"` + + // All timeouts are in ms + TimeoutPropose int `mapstructure:"timeout_propose"` + TimeoutProposeDelta int `mapstructure:"timeout_propose_delta"` + TimeoutPrevote int `mapstructure:"timeout_prevote"` + TimeoutPrevoteDelta int `mapstructure:"timeout_prevote_delta"` + TimeoutPrecommit int `mapstructure:"timeout_precommit"` + TimeoutPrecommitDelta int `mapstructure:"timeout_precommit_delta"` + TimeoutCommit int `mapstructure:"timeout_commit"` + + // Make progress as soon as we have all the precommits (as if TimeoutCommit = 0) + SkipTimeoutCommit bool `mapstructure:"skip_timeout_commit"` + + // BlockSize + MaxBlockSizeTxs int `mapstructure:"max_block_size_txs"` + MaxBlockSizeBytes int `mapstructure:"max_block_size_bytes"` + + // TODO: This probably shouldn't be exposed but it makes it + // easy to write tests for the wal/replay + BlockPartSize int `mapstructure:"block_part_size"` +} + +// Wait this long for a proposal +func (cfg *ConsensusConfig) Propose(round int) time.Duration { + return time.Duration(cfg.TimeoutPropose+cfg.TimeoutProposeDelta*round) * time.Millisecond +} + +// After receiving any +2/3 prevote, wait this long for stragglers +func (cfg *ConsensusConfig) Prevote(round int) time.Duration { + return time.Duration(cfg.TimeoutPrevote+cfg.TimeoutPrevoteDelta*round) * time.Millisecond +} + +// After receiving any +2/3 precommits, wait this long for stragglers +func (cfg *ConsensusConfig) Precommit(round int) time.Duration { + return time.Duration(cfg.TimeoutPrecommit+cfg.TimeoutPrecommitDelta*round) * time.Millisecond +} + +// After receiving +2/3 precommits for a single block (a commit), wait this long for stragglers in the next height's RoundStepNewHeight +func (cfg *ConsensusConfig) Commit(t time.Time) time.Time { + return t.Add(time.Duration(cfg.TimeoutCommit) * time.Millisecond) +} + +func DefaultConsensusConfig(rootDir string) *ConsensusConfig { + return &ConsensusConfig{ + WalFile: rootDir + "/data/cs.wal/wal", + WalLight: false, + TimeoutPropose: 3000, + TimeoutProposeDelta: 500, + TimeoutPrevote: 1000, + TimeoutPrevoteDelta: 500, + TimeoutPrecommit: 1000, + TimeoutPrecommitDelta: 500, + TimeoutCommit: 1000, + SkipTimeoutCommit: false, + MaxBlockSizeTxs: 10000, + MaxBlockSizeBytes: 1, // TODO + BlockPartSize: types.DefaultBlockPartSize, + } +} + +func TestConsensusConfig(rootDir string) *ConsensusConfig { + config := DefaultConsensusConfig(rootDir) + config.TimeoutPropose = 2000 + config.TimeoutProposeDelta = 1 + config.TimeoutPrevote = 10 + config.TimeoutPrevoteDelta = 1 + config.TimeoutPrecommit = 10 + config.TimeoutPrecommitDelta = 1 + config.TimeoutCommit = 10 + config.SkipTimeoutCommit = true + return config +} diff --git a/config/tendermint/config.go b/config/tendermint/config.go deleted file mode 100644 index e6757f5be..000000000 --- a/config/tendermint/config.go +++ /dev/null @@ -1,122 +0,0 @@ -package tendermint - -import ( - "os" - "path" - "strings" - - "github.com/spf13/viper" - cmn "github.com/tendermint/tmlibs/common" -) - -func getTMRoot(rootDir string) string { - if rootDir == "" { - rootDir = os.Getenv("TMHOME") - } - if rootDir == "" { - // deprecated, use TMHOME (TODO: remove in TM 0.11.0) - rootDir = os.Getenv("TMROOT") - } - if rootDir == "" { - rootDir = os.Getenv("HOME") + "/.tendermint" - } - return rootDir -} - -func initTMRoot(rootDir string) { - rootDir = getTMRoot(rootDir) - cmn.EnsureDir(rootDir, 0700) - cmn.EnsureDir(rootDir+"/data", 0700) - - configFilePath := path.Join(rootDir, "config.toml") - - // Write default config file if missing. - if !cmn.FileExists(configFilePath) { - // Ask user for moniker - // moniker := cfg.Prompt("Type hostname: ", "anonymous") - cmn.MustWriteFile(configFilePath, []byte(defaultConfig("anonymous")), 0644) - } -} - -func GetConfig(rootDir string) *viper.Viper { - rootDir = getTMRoot(rootDir) - initTMRoot(rootDir) - - config := viper.New() - config.SetConfigName("config") - config.SetConfigType("toml") - config.AddConfigPath(rootDir) - err := config.ReadInConfig() - if err != nil { - cmn.Exit(cmn.Fmt("Could not read config from directory %v: %v", rootDir, err)) - } - //config.WatchConfig() - - // Set defaults or panic - if config.IsSet("chain.chain_id") { - cmn.Exit("Cannot set 'chain_id' via config.toml") - } - //mapConfig.SetRequired("chain_id") // blows up if you try to use it before setting. - config.SetDefault("moniker", "anonymous") - config.SetDefault("log_level", "info") - config.SetDefault("prof_laddr", "") - config.SetDefault("genesis_file", rootDir+"/genesis.json") - config.SetDefault("proxy_app", "tcp://127.0.0.1:46658") - config.SetDefault("abci", "socket") - config.SetDefault("filter_peers", false) - config.SetDefault("fast_sync", true) - config.SetDefault("priv_validator_file", rootDir+"/priv_validator.json") - config.SetDefault("db_backend", "leveldb") - config.SetDefault("db_dir", rootDir+"/data") - config.SetDefault("rpc_laddr", "tcp://0.0.0.0:46657") - config.SetDefault("grpc_laddr", "") - config.SetDefault("tx_index", "kv") - - config.SetDefault("p2p.laddr", "tcp://0.0.0.0:46656") - config.SetDefault("p2p.seeds", "") - config.SetDefault("p2p.skip_upnp", false) - config.SetDefault("p2p.addrbook_file", rootDir+"/addrbook.json") - config.SetDefault("p2p.addrbook_strict", true) // disable to allow connections locally - config.SetDefault("p2p.pex_reactor", false) // enable for peer exchange - - config.SetDefault("consensus.wal_file", rootDir+"/data/cs.wal/wal") - config.SetDefault("consensus.wal_light", false) - config.SetDefault("consensus.max_block_size_txs", 10000) // max number of txs - config.SetDefault("consensus.block_part_size", 65536) // part size 64K - // all timeouts are in ms - config.SetDefault("consensus.timeout_handshake", 10000) - config.SetDefault("consensus.timeout_propose", 3000) - config.SetDefault("consensus.timeout_propose_delta", 500) - config.SetDefault("consensus.timeout_prevote", 1000) - config.SetDefault("consensus.timeout_prevote_delta", 500) - config.SetDefault("consensus.timeout_precommit", 1000) - config.SetDefault("consensus.timeout_precommit_delta", 500) - config.SetDefault("consensus.timeout_commit", 1000) - // make progress asap (no `timeout_commit`) on full precommit votes - config.SetDefault("consensus.skip_timeout_commit", false) - - config.SetDefault("mempool.recheck", true) - config.SetDefault("mempool.recheck_empty", true) - config.SetDefault("mempool.broadcast", true) - config.SetDefault("mempool.wal_dir", rootDir+"/data/mempool.wal") - - return config -} - -var defaultConfigTmpl = `# This is a TOML config file. -# For more information, see https://github.com/toml-lang/toml - -proxy_app = "tcp://127.0.0.1:46658" -moniker = "__MONIKER__" -node_laddr = "tcp://0.0.0.0:46656" -seeds = "" -fast_sync = true -db_backend = "leveldb" -log_level = "notice" -rpc_laddr = "tcp://0.0.0.0:46657" -` - -func defaultConfig(moniker string) (defaultConfig string) { - defaultConfig = strings.Replace(defaultConfigTmpl, "__MONIKER__", moniker, -1) - return -} diff --git a/config/tendermint_test/config.go b/config/tendermint_test/config.go deleted file mode 100644 index 6eb8f53d8..000000000 --- a/config/tendermint_test/config.go +++ /dev/null @@ -1,170 +0,0 @@ -// Import this in all *_test.go files to initialize ~/.tendermint_test. - -package tendermint_test - -import ( - "fmt" - "os" - "path" - "strings" - - "github.com/spf13/viper" - - . "github.com/tendermint/tmlibs/common" - "github.com/tendermint/tmlibs/logger" -) - -func init() { - // Creates ~/.tendermint_test - EnsureDir(os.Getenv("HOME")+"/.tendermint_test", 0700) -} - -func initTMRoot(rootDir string) { - // Remove ~/.tendermint_test_bak - if FileExists(rootDir + "_bak") { - err := os.RemoveAll(rootDir + "_bak") - if err != nil { - PanicSanity(err.Error()) - } - } - // Move ~/.tendermint_test to ~/.tendermint_test_bak - if FileExists(rootDir) { - err := os.Rename(rootDir, rootDir+"_bak") - if err != nil { - PanicSanity(err.Error()) - } - } - // Create new dir - EnsureDir(rootDir, 0700) - EnsureDir(rootDir+"/data", 0700) - - configFilePath := path.Join(rootDir, "config.toml") - genesisFilePath := path.Join(rootDir, "genesis.json") - privFilePath := path.Join(rootDir, "priv_validator.json") - - // Write default config file if missing. - if !FileExists(configFilePath) { - // Ask user for moniker - MustWriteFile(configFilePath, []byte(defaultConfig("anonymous")), 0644) - } - if !FileExists(genesisFilePath) { - MustWriteFile(genesisFilePath, []byte(defaultGenesis), 0644) - } - // we always overwrite the priv val - MustWriteFile(privFilePath, []byte(defaultPrivValidator), 0644) -} - -func ResetConfig(localPath string) *viper.Viper { - rootDir := os.Getenv("HOME") + "/.tendermint_test/" + localPath - initTMRoot(rootDir) - - config := viper.New() - config.SetConfigName("config") - config.SetConfigType("toml") - config.AddConfigPath(rootDir) - err := config.ReadInConfig() - if err != nil { - Exit(Fmt("Could not read config: %v", err)) - } - //config.WatchConfig() - - // Set defaults or panic - if config.IsSet("chain_id") { - Exit(fmt.Sprintf("Cannot set 'chain_id' via config.toml:\n %v\n %v\n ", config.Get("chain_id"), rootDir)) - } - - config.SetDefault("chain_id", "tendermint_test") - config.SetDefault("genesis_file", rootDir+"/genesis.json") - config.SetDefault("proxy_app", "dummy") - config.SetDefault("abci", "socket") - config.SetDefault("moniker", "anonymous") - config.SetDefault("node_laddr", "tcp://0.0.0.0:36656") - config.SetDefault("fast_sync", false) - config.SetDefault("priv_validator_file", rootDir+"/priv_validator.json") - config.SetDefault("db_backend", "memdb") - config.SetDefault("db_dir", rootDir+"/data") - config.SetDefault("log_level", "info") - config.SetDefault("rpc_laddr", "tcp://0.0.0.0:36657") - config.SetDefault("grpc_laddr", "tcp://0.0.0.0:36658") - config.SetDefault("prof_laddr", "") - config.SetDefault("filter_peers", false) - config.SetDefault("tx_index", "kv") - - config.SetDefault("p2p.laddr", "tcp://0.0.0.0:36656") - config.SetDefault("p2p.skip_upnp", true) - config.SetDefault("p2p.addrbook_file", rootDir+"/addrbook.json") - config.SetDefault("p2p.addrbook_strict", true) // disable to allow connections locally - config.SetDefault("p2p.pex_reactor", false) // enable for peer exchange - - config.SetDefault("consensus.wal_file", rootDir+"/data/cs.wal/wal") - config.SetDefault("consensus.wal_light", false) - config.SetDefault("consensus.max_block_size_txs", 10000) - config.SetDefault("consensus.block_part_size", 65536) // part size 64K - config.SetDefault("consensus.timeout_handshake", 10000) - config.SetDefault("consensus.timeout_propose", 2000) - config.SetDefault("consensus.timeout_propose_delta", 1) - config.SetDefault("consensus.timeout_prevote", 10) - config.SetDefault("consensus.timeout_prevote_delta", 1) - config.SetDefault("consensus.timeout_precommit", 10) - config.SetDefault("consensus.timeout_precommit_delta", 1) - config.SetDefault("consensus.timeout_commit", 10) - config.SetDefault("consensus.skip_timeout_commit", true) - - config.SetDefault("mempool.recheck", true) - config.SetDefault("mempool.recheck_empty", true) - config.SetDefault("mempool.broadcast", true) - config.SetDefault("mempool.wal_dir", "") - - logger.SetLogLevel(config.GetString("log_level")) - - return config -} - -var defaultConfigTmpl = `# This is a TOML config file. -# For more information, see https://github.com/toml-lang/toml - -proxy_app = "dummy" -moniker = "__MONIKER__" -node_laddr = "tcp://0.0.0.0:36656" -seeds = "" -fast_sync = false -db_backend = "memdb" -log_level = "info" -rpc_laddr = "tcp://0.0.0.0:36657" -` - -func defaultConfig(moniker string) (defaultConfig string) { - defaultConfig = strings.Replace(defaultConfigTmpl, "__MONIKER__", moniker, -1) - return -} - -var defaultGenesis = `{ - "genesis_time": "0001-01-01T00:00:00.000Z", - "chain_id": "tendermint_test", - "validators": [ - { - "pub_key": { - "type": "ed25519", - "data":"3B3069C422E19688B45CBFAE7BB009FC0FA1B1EA86593519318B7214853803C8" - }, - "amount": 10, - "name": "" - } - ], - "app_hash": "" -}` - -var defaultPrivValidator = `{ - "address": "D028C9981F7A87F3093672BF0D5B0E2A1B3ED456", - "pub_key": { - "type": "ed25519", - "data": "3B3069C422E19688B45CBFAE7BB009FC0FA1B1EA86593519318B7214853803C8" - }, - "priv_key": { - "type": "ed25519", - "data": "27F82582AEFAE7AB151CFB01C48BB6C1A0DA78F9BDDA979A9F70A84D074EB07D3B3069C422E19688B45CBFAE7BB009FC0FA1B1EA86593519318B7214853803C8" - }, - "last_height": 0, - "last_round": 0, - "last_step": 0 -}` diff --git a/config/toml.go b/config/toml.go new file mode 100644 index 000000000..a9e6ba302 --- /dev/null +++ b/config/toml.go @@ -0,0 +1,129 @@ +package config + +import ( + "os" + "path" + "strings" + + cmn "github.com/tendermint/tmlibs/common" +) + +/****** these are for production settings ***********/ + +func initRoot(rootDir string) { + cmn.EnsureDir(rootDir, 0700) + cmn.EnsureDir(rootDir+"/data", 0700) + + configFilePath := path.Join(rootDir, "config.toml") + + // Write default config file if missing. + if !cmn.FileExists(configFilePath) { + // Ask user for moniker + // moniker := cfg.Prompt("Type hostname: ", "anonymous") + cmn.MustWriteFile(configFilePath, []byte(defaultConfig("anonymous")), 0644) + } +} + +var defaultConfigTmpl = `# This is a TOML config file. +# For more information, see https://github.com/toml-lang/toml + +proxy_app = "tcp://127.0.0.1:46658" +moniker = "__MONIKER__" +node_laddr = "tcp://0.0.0.0:46656" +seeds = "" +fast_sync = true +db_backend = "leveldb" +log_level = "notice" +rpc_laddr = "tcp://0.0.0.0:46657" +` + +func defaultConfig(moniker string) (defaultConfig string) { + defaultConfig = strings.Replace(defaultConfigTmpl, "__MONIKER__", moniker, -1) + return +} + +/****** these are for test settings ***********/ + +func initTestRoot(rootDir string) { + // Remove ~/.tendermint_test_bak + if cmn.FileExists(rootDir + "_bak") { + err := os.RemoveAll(rootDir + "_bak") + if err != nil { + cmn.PanicSanity(err.Error()) + } + } + // Move ~/.tendermint_test to ~/.tendermint_test_bak + if cmn.FileExists(rootDir) { + err := os.Rename(rootDir, rootDir+"_bak") + if err != nil { + cmn.PanicSanity(err.Error()) + } + } + // Create new dir + cmn.EnsureDir(rootDir, 0700) + cmn.EnsureDir(rootDir+"/data", 0700) + + configFilePath := path.Join(rootDir, "config.toml") + genesisFilePath := path.Join(rootDir, "genesis.json") + privFilePath := path.Join(rootDir, "priv_validator.json") + + // Write default config file if missing. + if !cmn.FileExists(configFilePath) { + // Ask user for moniker + cmn.MustWriteFile(configFilePath, []byte(testConfig("anonymous")), 0644) + } + if !cmn.FileExists(genesisFilePath) { + cmn.MustWriteFile(genesisFilePath, []byte(testGenesis), 0644) + } + // we always overwrite the priv val + cmn.MustWriteFile(privFilePath, []byte(testPrivValidator), 0644) +} + +var testConfigTmpl = `# This is a TOML config file. +# For more information, see https://github.com/toml-lang/toml + +proxy_app = "dummy" +moniker = "__MONIKER__" +node_laddr = "tcp://0.0.0.0:36656" +seeds = "" +fast_sync = false +db_backend = "memdb" +log_level = "info" +rpc_laddr = "tcp://0.0.0.0:36657" +` + +func testConfig(moniker string) (testConfig string) { + testConfig = strings.Replace(testConfigTmpl, "__MONIKER__", moniker, -1) + return +} + +var testGenesis = `{ + "genesis_time": "0001-01-01T00:00:00.000Z", + "chain_id": "tendermint_test", + "validators": [ + { + "pub_key": { + "type": "ed25519", + "data":"3B3069C422E19688B45CBFAE7BB009FC0FA1B1EA86593519318B7214853803C8" + }, + "amount": 10, + "name": "" + } + ], + "app_hash": "" +}` + +var testPrivValidator = `{ + "address": "D028C9981F7A87F3093672BF0D5B0E2A1B3ED456", + "pub_key": { + "type": "ed25519", + "data": "3B3069C422E19688B45CBFAE7BB009FC0FA1B1EA86593519318B7214853803C8" + }, + "priv_key": { + "type": "ed25519", + "data": "27F82582AEFAE7AB151CFB01C48BB6C1A0DA78F9BDDA979A9F70A84D074EB07D3B3069C422E19688B45CBFAE7BB009FC0FA1B1EA86593519318B7214853803C8" + }, + "last_height": 0, + "last_round": 0, + "last_step": 0 +}` diff --git a/consensus/replay_file.go b/consensus/replay_file.go index 4e0f40b65..2db228c91 100644 --- a/consensus/replay_file.go +++ b/consensus/replay_file.go @@ -20,7 +20,7 @@ import ( //-------------------------------------------------------- // replay messages interactively or all at once -func RunReplayFile(config *cfg.Config, csConfig *Config, console bool) { +func RunReplayFile(config *cfg.Config, csConfig *cfg.ConsensusConfig, console bool) { consensusState := newConsensusStateForReplay(config, csConfig) if err := consensusState.ReplayFile(csConfig.WalFile, console); err != nil { @@ -235,7 +235,7 @@ func (pb *playback) replayConsoleLoop() int { //-------------------------------------------------------------------------------- // convenience for replay mode -func newConsensusStateForReplay(config *cfg.Config, csConfig *Config) *ConsensusState { +func newConsensusStateForReplay(config *cfg.Config, csConfig *cfg.ConsensusConfig) *ConsensusState { // Get BlockStore blockStoreDB := dbm.NewDB("blockstore", config.DBBackend, config.DBDir) blockStore := bc.NewBlockStore(blockStoreDB) diff --git a/consensus/state.go b/consensus/state.go index e7b6381c2..a565dfdce 100644 --- a/consensus/state.go +++ b/consensus/state.go @@ -9,9 +9,9 @@ import ( "sync" "time" - "github.com/ebuchman/fail-test" - + fail "github.com/ebuchman/fail-test" "github.com/tendermint/go-wire" + cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/proxy" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" @@ -21,84 +21,6 @@ import ( //----------------------------------------------------------------------------- // Config -// Config holds timeouts and details about the WAL, the block structure, -// and timeouts in the consensus protocol. -type Config struct { - WalFile string `mapstructure:"wal_file"` - WalLight bool `mapstructure:"wal_light"` - - // All timeouts are in ms - TimeoutPropose int `mapstructure:"timeout_propose"` - TimeoutProposeDelta int `mapstructure:"timeout_propose_delta"` - TimeoutPrevote int `mapstructure:"timeout_prevote"` - TimeoutPrevoteDelta int `mapstructure:"timeout_prevote_delta"` - TimeoutPrecommit int `mapstructure:"timeout_precommit"` - TimeoutPrecommitDelta int `mapstructure:"timeout_precommit_delta"` - TimeoutCommit int `mapstructure:"timeout_commit"` - - // Make progress as soon as we have all the precommits (as if TimeoutCommit = 0) - SkipTimeoutCommit bool `mapstructure:"skip_timeout_commit"` - - // BlockSize - MaxBlockSizeTxs int `mapstructure:"max_block_size_txs"` - MaxBlockSizeBytes int `mapstructure:"max_block_size_bytes"` - - // TODO: This probably shouldn't be exposed but it makes it - // easy to write tests for the wal/replay - BlockPartSize int `mapstructure:"block_part_size"` -} - -func NewDefaultConfig(rootDir string) *Config { - return &Config{ - WalFile: rootDir + "/data/cs.wal/wal", - WalLight: false, - TimeoutPropose: 3000, - TimeoutProposeDelta: 500, - TimeoutPrevote: 1000, - TimeoutPrevoteDelta: 500, - TimeoutPrecommit: 1000, - TimeoutPrecommitDelta: 500, - TimeoutCommit: 1000, - SkipTimeoutCommit: false, - MaxBlockSizeTxs: 10000, - MaxBlockSizeBytes: 1, // TODO - BlockPartSize: types.DefaultBlockPartSize, - } -} - -func NewTestConfig(rootDir string) *Config { - config := NewDefaultConfig(rootDir) - config.TimeoutPropose = 2000 - config.TimeoutProposeDelta = 1 - config.TimeoutPrevote = 10 - config.TimeoutPrevoteDelta = 1 - config.TimeoutPrecommit = 10 - config.TimeoutPrecommitDelta = 1 - config.TimeoutCommit = 10 - config.SkipTimeoutCommit = true - return config -} - -// Wait this long for a proposal -func (cfg *Config) Propose(round int) time.Duration { - return time.Duration(cfg.TimeoutPropose+cfg.TimeoutProposeDelta*round) * time.Millisecond -} - -// After receiving any +2/3 prevote, wait this long for stragglers -func (cfg *Config) Prevote(round int) time.Duration { - return time.Duration(cfg.TimeoutPrevote+cfg.TimeoutPrevoteDelta*round) * time.Millisecond -} - -// After receiving any +2/3 precommits, wait this long for stragglers -func (cfg *Config) Precommit(round int) time.Duration { - return time.Duration(cfg.TimeoutPrecommit+cfg.TimeoutPrecommitDelta*round) * time.Millisecond -} - -// After receiving +2/3 precommits for a single block (a commit), wait this long for stragglers in the next height's RoundStepNewHeight -func (cfg *Config) Commit(t time.Time) time.Time { - return t.Add(time.Duration(cfg.TimeoutCommit) * time.Millisecond) -} - //----------------------------------------------------------------------------- // Errors @@ -255,7 +177,7 @@ type ConsensusState struct { cmn.BaseService // config details - config *Config + config *cfg.ConsensusConfig privValidator PrivValidator // for signing votes // services for creating and executing blocks @@ -295,7 +217,7 @@ type ConsensusState struct { done chan struct{} } -func NewConsensusState(config *Config, state *sm.State, proxyAppConn proxy.AppConnConsensus, blockStore types.BlockStore, mempool types.Mempool) *ConsensusState { +func NewConsensusState(config *cfg.ConsensusConfig, state *sm.State, proxyAppConn proxy.AppConnConsensus, blockStore types.BlockStore, mempool types.Mempool) *ConsensusState { cs := &ConsensusState{ config: config, proxyAppConn: proxyAppConn, diff --git a/glide.lock b/glide.lock index b78270bd7..0f1426f3d 100644 --- a/glide.lock +++ b/glide.lock @@ -1,5 +1,5 @@ -hash: 6f8962f6ca0e25b8e43bc6e496bd46c9ff3a79dcf789578efeeaee2fffc39c6e -updated: 2017-04-27T19:56:37.342860938-04:00 +hash: 1bdb98b332fc88df3659092ce571b74851f54465c11d91e273a10098dd4d8011 +updated: 2017-05-04T19:50:25.718540841+02:00 imports: - name: github.com/btcsuite/btcd version: 4b348c1d33373d672edd83fc576892d0e46686d2 @@ -56,7 +56,7 @@ imports: - name: github.com/pelletier/go-toml version: 13d49d4606eb801b8f01ae542b4afc4c6ee3d84a - name: github.com/pkg/errors - version: 645ef00459ed84a119197bfb8d8205042c6df63d + version: bfd5150e4e41705ded2129ec33379de1cb90b513 - name: github.com/pmezard/go-difflib version: d8ed2627bdf02c080bf22230dbb337003b7aba2d subpackages: @@ -119,7 +119,7 @@ imports: subpackages: - term - name: github.com/tendermint/merkleeyes - version: ea4dd9c7b773435de26bf59fddf90afd43a07d67 + version: 0fab643ccac1a3f93b90e0e2682a5d1b9d17f8c4 subpackages: - app - client @@ -129,6 +129,7 @@ imports: version: df250b69416a35a943a6e2a92118667e9ef031d4 subpackages: - autofile + - cli - clist - common - db diff --git a/glide.yaml b/glide.yaml index f06a16b3b..238b4ec0c 100644 --- a/glide.yaml +++ b/glide.yaml @@ -31,6 +31,7 @@ import: version: develop subpackages: - autofile + - cli - clist - common - db diff --git a/mempool/mempool.go b/mempool/mempool.go index daf9f6524..6b168897c 100644 --- a/mempool/mempool.go +++ b/mempool/mempool.go @@ -12,6 +12,7 @@ import ( "github.com/tendermint/tmlibs/clist" cmn "github.com/tendermint/tmlibs/common" + cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/proxy" "github.com/tendermint/tendermint/types" ) @@ -47,7 +48,7 @@ TODO: Better handle abci client errors. (make it automatically handle connection const cacheSize = 100000 type Mempool struct { - config *Config + config *cfg.MempoolConfig proxyMtx sync.Mutex proxyAppConn proxy.AppConnMempool @@ -66,7 +67,7 @@ type Mempool struct { wal *auto.AutoFile } -func NewMempool(config *Config, proxyAppConn proxy.AppConnMempool) *Mempool { +func NewMempool(config *cfg.MempoolConfig, proxyAppConn proxy.AppConnMempool) *Mempool { mempool := &Mempool{ config: config, proxyAppConn: proxyAppConn, diff --git a/mempool/reactor.go b/mempool/reactor.go index a0e7d518c..169228982 100644 --- a/mempool/reactor.go +++ b/mempool/reactor.go @@ -10,6 +10,7 @@ import ( "github.com/tendermint/go-wire" "github.com/tendermint/tmlibs/clist" + cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/types" ) @@ -21,31 +22,15 @@ const ( peerCatchupSleepIntervalMS = 100 // If peer is behind, sleep this amount ) -type Config struct { - Recheck bool `mapstructure:"recheck"` // true - RecheckEmpty bool `mapstructure:"recheck_empty"` // true - Broadcast bool `mapstructure:"broadcast"` // true - WalDir string `mapstructure:"wal_dir"` // -} - -func NewDefaultConfig(rootDir string) *Config { - return &Config{ - Recheck: true, - RecheckEmpty: true, - Broadcast: true, - WalDir: rootDir + "/data/mempool.wal", - } -} - // MempoolReactor handles mempool tx broadcasting amongst peers. type MempoolReactor struct { p2p.BaseReactor - config *Config + config *cfg.MempoolConfig Mempool *Mempool evsw types.EventSwitch } -func NewMempoolReactor(config *Config, mempool *Mempool) *MempoolReactor { +func NewMempoolReactor(config *cfg.MempoolConfig, mempool *Mempool) *MempoolReactor { memR := &MempoolReactor{ config: config, Mempool: mempool, diff --git a/node/node.go b/node/node.go index e4f945ee3..b206c2ad9 100644 --- a/node/node.go +++ b/node/node.go @@ -7,14 +7,11 @@ import ( "net/http" "strings" - "github.com/spf13/viper" - abci "github.com/tendermint/abci/types" crypto "github.com/tendermint/go-crypto" wire "github.com/tendermint/go-wire" bc "github.com/tendermint/tendermint/blockchain" cfg "github.com/tendermint/tendermint/config" - // tmcfg "github.com/tendermint/tendermint/config/tendermint" "github.com/tendermint/tendermint/consensus" mempl "github.com/tendermint/tendermint/mempool" p2p "github.com/tendermint/tendermint/p2p" @@ -35,38 +32,11 @@ import ( _ "net/http/pprof" ) -type Config struct { - // Top level options use an anonymous struct - cfg.Config `mapstructure:",squash"` - - // Options for services - P2P *p2p.Config `mapstructure:"p2p"` - Mempool *mempl.Config `mapstructure:"mempool"` - Consensus *consensus.Config `mapstructure:"consensus"` -} - -func NewDefaultConfig(rootDir string) *Config { - return &Config{ - Config: *cfg.NewDefaultConfig(rootDir), - P2P: p2p.NewDefaultConfig(rootDir), - Mempool: mempl.NewDefaultConfig(rootDir), - Consensus: consensus.NewDefaultConfig(rootDir), - } -} - -func ConfigFromViper(viperConfig *viper.Viper) *Config { - tmConfig := new(Config) - if err := viperConfig.Unmarshal(tmConfig); err != nil { - panic(err) - } - return tmConfig -} - type Node struct { cmn.BaseService // config - config *Config + config *cfg.Config genesisDoc *types.GenesisDoc // initial validator set privValidator *types.PrivValidator // local node's validator key @@ -87,14 +57,14 @@ type Node struct { txIndexer txindex.TxIndexer } -func NewNodeDefault(config *Config) *Node { +func NewNodeDefault(config *cfg.Config) *Node { // Get PrivValidator privValidator := types.LoadOrGenPrivValidator(config.PrivValidatorFile) return NewNode(config, privValidator, proxy.DefaultClientCreator(config.ProxyApp, config.ABCI, config.DBDir)) } -func NewNode(config *Config, privValidator *types.PrivValidator, clientCreator proxy.ClientCreator) *Node { +func NewNode(config *cfg.Config, privValidator *types.PrivValidator, clientCreator proxy.ClientCreator) *Node { // Get BlockStore blockStoreDB := dbm.NewDB("blockstore", config.DBBackend, config.DBDir) diff --git a/p2p/switch.go b/p2p/switch.go index 49d817f20..9fe001eff 100644 --- a/p2p/switch.go +++ b/p2p/switch.go @@ -9,6 +9,7 @@ import ( crypto "github.com/tendermint/go-crypto" "github.com/tendermint/log15" + cfg "github.com/tendermint/tendermint/config" cmn "github.com/tendermint/tmlibs/common" ) @@ -17,29 +18,6 @@ const ( reconnectInterval = 3 * time.Second ) -// for node.Config -type Config struct { - ListenAddress string `mapstructure:"laddr"` - Seeds string `mapstructure:"seeds"` - SkipUPNP bool `mapstructure:"skip_upnp"` - AddrBookFile string `mapstructure:"addr_book_file"` - AddrBookStrict bool `mapstructure:"addr_book_strict"` - PexReactor bool `mapstructure:"pex_reactor"` - MaxNumPeers int `mapstructure:"max_num_peers"` - - peer *PeerConfig // Not exposed -} - -func NewDefaultConfig(rootDir string) *Config { - return &Config{ - ListenAddress: "tcp://0.0.0.0:46656", - AddrBookFile: rootDir + "/addrbook.json", - AddrBookStrict: true, - MaxNumPeers: 50, - peer: DefaultPeerConfig(), - } -} - type Reactor interface { cmn.Service // Start, Stop @@ -83,7 +61,8 @@ incoming messages are received on the reactor. type Switch struct { cmn.BaseService - config *Config + config *cfg.P2PConfig + peerConfig *PeerConfig listeners []Listener reactors map[string]Reactor chDescs []*ChannelDescriptor @@ -102,10 +81,10 @@ var ( ErrSwitchMaxPeersPerIPRange = errors.New("IP range has too many peers") ) -func NewSwitch(config *Config) *Switch { - config.peer = DefaultPeerConfig() +func NewSwitch(config *cfg.P2PConfig) *Switch { sw := &Switch{ config: config, + peerConfig: DefaultPeerConfig(), reactors: make(map[string]Reactor), chDescs: make([]*ChannelDescriptor, 0), reactorsByCh: make(map[byte]Reactor), @@ -229,7 +208,7 @@ func (sw *Switch) AddPeer(peer *Peer) error { return err } - if err := peer.HandshakeTimeout(sw.nodeInfo, time.Duration(sw.config.peer.HandshakeTimeout*time.Second)); err != nil { + if err := peer.HandshakeTimeout(sw.nodeInfo, time.Duration(sw.peerConfig.HandshakeTimeout*time.Second)); err != nil { return err } @@ -338,7 +317,7 @@ func (sw *Switch) DialPeerWithAddress(addr *NetAddress, persistent bool) (*Peer, sw.dialing.Set(addr.IP.String(), addr) defer sw.dialing.Delete(addr.IP.String()) - peer, err := newOutboundPeerWithConfig(addr, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey, sw.config.peer) + peer, err := newOutboundPeerWithConfig(addr, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey, sw.peerConfig) if err != nil { log.Info("Failed dialing peer", "address", addr, "error", err) return nil, err @@ -457,7 +436,7 @@ func (sw *Switch) listenerRoutine(l Listener) { } // New inbound connection! - err := sw.addPeerWithConnectionAndConfig(inConn, sw.config.peer) + err := sw.addPeerWithConnectionAndConfig(inConn, sw.peerConfig) if err != nil { log.Notice("Ignoring inbound connection: error while adding peer", "address", inConn.RemoteAddr().String(), "error", err) continue @@ -489,7 +468,7 @@ type SwitchEventDonePeer struct { // If connect==Connect2Switches, the switches will be fully connected. // initSwitch defines how the ith switch should be initialized (ie. with what reactors). // NOTE: panics if any switch fails to start. -func MakeConnectedSwitches(cfg *Config, n int, initSwitch func(int, *Switch) *Switch, connect func([]*Switch, int, int)) []*Switch { +func MakeConnectedSwitches(cfg *cfg.P2PConfig, n int, initSwitch func(int, *Switch) *Switch, connect func([]*Switch, int, int)) []*Switch { switches := make([]*Switch, n) for i := 0; i < n; i++ { switches[i] = makeSwitch(cfg, i, "testing", "123.123.123", initSwitch) @@ -546,7 +525,7 @@ func StartSwitches(switches []*Switch) error { return nil } -func makeSwitch(cfg *Config, i int, network, version string, initSwitch func(int, *Switch) *Switch) *Switch { +func makeSwitch(cfg *cfg.P2PConfig, i int, network, version string, initSwitch func(int, *Switch) *Switch) *Switch { privKey := crypto.GenPrivKeyEd25519() // new switch, add reactors // TODO: let the config be passed in? From 92dee7ea3ce3a15d562cf55cc440efcab29fcdc3 Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Thu, 4 May 2017 21:37:12 +0200 Subject: [PATCH 266/309] Commands compile (mostly) with new config reading --- cmd/tendermint/commands/replay.go | 4 ++-- cmd/tendermint/commands/root.go | 28 ++++++++------------------- cmd/tendermint/commands/run_node.go | 30 ++++++++++------------------- cmd/tendermint/main.go | 8 +++----- consensus/replay_file.go | 4 ++-- 5 files changed, 25 insertions(+), 49 deletions(-) diff --git a/cmd/tendermint/commands/replay.go b/cmd/tendermint/commands/replay.go index 227931152..0c88b2443 100644 --- a/cmd/tendermint/commands/replay.go +++ b/cmd/tendermint/commands/replay.go @@ -10,7 +10,7 @@ var replayCmd = &cobra.Command{ Use: "replay", Short: "Replay messages from WAL", Run: func(cmd *cobra.Command, args []string) { - consensus.RunReplayFile(&config.Config, config.Consensus, false) + consensus.RunReplayFile(config.BaseConfig, config.Consensus, false) }, } @@ -18,7 +18,7 @@ var replayConsoleCmd = &cobra.Command{ Use: "replay_console", Short: "Replay messages from WAL in a console", Run: func(cmd *cobra.Command, args []string) { - consensus.RunReplayFile(&config.Config, config.Consensus, true) + consensus.RunReplayFile(config.BaseConfig, config.Consensus, true) }, } diff --git a/cmd/tendermint/commands/root.go b/cmd/tendermint/commands/root.go index 1f69a2158..63ee0db5c 100644 --- a/cmd/tendermint/commands/root.go +++ b/cmd/tendermint/commands/root.go @@ -4,38 +4,26 @@ import ( "github.com/spf13/cobra" "github.com/spf13/viper" - cfg "github.com/tendermint/tendermint/config/tendermint" - "github.com/tendermint/tendermint/node" + cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tmlibs/logger" ) var ( - viperConfig *viper.Viper - config *node.Config - log = logger.New("module", "main") + config *cfg.Config + log = logger.New("module", "main") ) func init() { - viperConfig = cfg.GetConfig("") -} - -// unmarshal viper into the Tendermint config -func getConfig() *node.Config { - return node.ConfigFromViper(viperConfig) + config = cfg.DefaultConfig("REMOVE-ROOT") + RootCmd.PersistentFlags().String("log_level", config.LogLevel, "Log level") } var RootCmd = &cobra.Command{ Use: "tendermint", Short: "Tendermint Core (BFT Consensus) in Go", - PersistentPreRun: func(cmd *cobra.Command, args []string) { - // set the log level - config = getConfig() + PersistentPreRunE: func(cmd *cobra.Command, args []string) error { + err := viper.Unmarshal(config) logger.SetLogLevel(config.LogLevel) + return err }, } - -func init() { - //parse flag and set config - RootCmd.PersistentFlags().String("log_level", viperConfig.GetString("log_level"), "Log level") - viperConfig.BindPFlag("log_level", RootCmd.PersistentFlags().Lookup("log_level")) -} diff --git a/cmd/tendermint/commands/run_node.go b/cmd/tendermint/commands/run_node.go index 58cdd3cf2..d8c268c26 100644 --- a/cmd/tendermint/commands/run_node.go +++ b/cmd/tendermint/commands/run_node.go @@ -18,38 +18,28 @@ var runNodeCmd = &cobra.Command{ RunE: runNode, } -func registerRunNodeFlagString(flagName, desc string) { - runNodeCmd.Flags().String(flagName, viperConfig.GetString(flagName), desc) - viperConfig.BindPFlag(flagName, runNodeCmd.Flags().Lookup(flagName)) -} - -func registerRunNodeFlagBool(flagName, desc string) { - runNodeCmd.Flags().Bool(flagName, viperConfig.GetBool(flagName), desc) - viperConfig.BindPFlag(flagName, runNodeCmd.Flags().Lookup(flagName)) -} - func init() { // bind flags + runNodeCmd.Flags().String("moniker", config.Moniker, "Node Name") // node flags - registerRunNodeFlagString("moniker", "Node Name") - registerRunNodeFlagBool("fast_sync", "Fast blockchain syncing") + runNodeCmd.Flags().Bool("fast_sync", config.FastSync, "Fast blockchain syncing") // abci flags - registerRunNodeFlagString("proxy_app", "Proxy app address, or 'nilapp' or 'dummy' for local testing.") - registerRunNodeFlagString("abci", "Specify abci transport (socket | grpc)") + runNodeCmd.Flags().String("proxy_app", config.ProxyApp, "Proxy app address, or 'nilapp' or 'dummy' for local testing.") + runNodeCmd.Flags().String("abci", config.ABCI, "Specify abci transport (socket | grpc)") // rpc flags - registerRunNodeFlagString("rpc_laddr", "RPC listen address. Port required") - registerRunNodeFlagString("grpc_laddr", "GRPC listen address (BroadcastTx only). Port required") + runNodeCmd.Flags().String("rpc_laddr", config.RPCListenAddress, "RPC listen address. Port required") + runNodeCmd.Flags().String("grpc_laddr", config.GRPCListenAddress, "GRPC listen address (BroadcastTx only). Port required") // p2p flags - registerRunNodeFlagString("p2p.laddr", "Node listen address. (0.0.0.0:0 means any interface, any port)") - registerRunNodeFlagString("p2p.seeds", "Comma delimited host:port seed nodes") - registerRunNodeFlagBool("p2p.skip_upnp", "Skip UPNP configuration") + runNodeCmd.Flags().String("p2p.laddr", config.P2P.ListenAddress, "Node listen address. (0.0.0.0:0 means any interface, any port)") + runNodeCmd.Flags().String("p2p.seeds", config.P2P.Seeds, "Comma delimited host:port seed nodes") + runNodeCmd.Flags().Bool("p2p.skip_upnp", config.P2P.SkipUPNP, "Skip UPNP configuration") // feature flags - registerRunNodeFlagBool("p2p.pex", "Enable Peer-Exchange (dev feature)") + runNodeCmd.Flags().Bool("p2p.pex", config.P2P.PexReactor, "Enable Peer-Exchange (dev feature)") RootCmd.AddCommand(runNodeCmd) } diff --git a/cmd/tendermint/main.go b/cmd/tendermint/main.go index cddae985b..5493e4f2f 100644 --- a/cmd/tendermint/main.go +++ b/cmd/tendermint/main.go @@ -1,15 +1,13 @@ package main import ( - "fmt" "os" "github.com/tendermint/tendermint/cmd/tendermint/commands" + "github.com/tendermint/tmlibs/cli" ) func main() { - if err := commands.RootCmd.Execute(); err != nil { - fmt.Println(err) - os.Exit(1) - } + cmd := cli.PrepareBaseCmd(commands.RootCmd, "TM", os.ExpandEnv("$HOME/.tendermint")) + cmd.Execute() } diff --git a/consensus/replay_file.go b/consensus/replay_file.go index 2db228c91..e7d904bff 100644 --- a/consensus/replay_file.go +++ b/consensus/replay_file.go @@ -20,7 +20,7 @@ import ( //-------------------------------------------------------- // replay messages interactively or all at once -func RunReplayFile(config *cfg.Config, csConfig *cfg.ConsensusConfig, console bool) { +func RunReplayFile(config *cfg.BaseConfig, csConfig *cfg.ConsensusConfig, console bool) { consensusState := newConsensusStateForReplay(config, csConfig) if err := consensusState.ReplayFile(csConfig.WalFile, console); err != nil { @@ -235,7 +235,7 @@ func (pb *playback) replayConsoleLoop() int { //-------------------------------------------------------------------------------- // convenience for replay mode -func newConsensusStateForReplay(config *cfg.Config, csConfig *cfg.ConsensusConfig) *ConsensusState { +func newConsensusStateForReplay(config *cfg.BaseConfig, csConfig *cfg.ConsensusConfig) *ConsensusState { // Get BlockStore blockStoreDB := dbm.NewDB("blockstore", config.DBBackend, config.DBDir) blockStore := bc.NewBlockStore(blockStoreDB) From 6b059e0063168dc37cd56641c992c78ab46f3523 Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Thu, 4 May 2017 21:57:58 +0200 Subject: [PATCH 267/309] Accept relative paths in all configs, TODO: must SetRoot --- cmd/tendermint/commands/init.go | 4 +- .../commands/reset_priv_validator.go | 4 +- cmd/tendermint/commands/root.go | 2 +- cmd/tendermint/commands/run_node.go | 2 +- cmd/tendermint/commands/show_validator.go | 2 +- config/config.go | 103 +++++++++++++----- consensus/replay_file.go | 10 +- consensus/state.go | 2 +- mempool/mempool.go | 2 +- node/node.go | 14 +-- 10 files changed, 96 insertions(+), 49 deletions(-) diff --git a/cmd/tendermint/commands/init.go b/cmd/tendermint/commands/init.go index bb8aa45dc..5c3fbb52a 100644 --- a/cmd/tendermint/commands/init.go +++ b/cmd/tendermint/commands/init.go @@ -20,13 +20,13 @@ func init() { } func initFiles(cmd *cobra.Command, args []string) { - privValFile := config.PrivValidatorFile + privValFile := config.PrivValidatorFile() if _, err := os.Stat(privValFile); os.IsNotExist(err) { privValidator := types.GenPrivValidator() privValidator.SetFile(privValFile) privValidator.Save() - genFile := config.GenesisFile + genFile := config.GenesisFile() if _, err := os.Stat(genFile); os.IsNotExist(err) { genDoc := types.GenesisDoc{ diff --git a/cmd/tendermint/commands/reset_priv_validator.go b/cmd/tendermint/commands/reset_priv_validator.go index c84ebcf8b..c10f9c56a 100644 --- a/cmd/tendermint/commands/reset_priv_validator.go +++ b/cmd/tendermint/commands/reset_priv_validator.go @@ -29,13 +29,13 @@ func init() { // XXX: this is totally unsafe. // it's only suitable for testnets. func resetAll(cmd *cobra.Command, args []string) { - ResetAll(config.DBDir, config.PrivValidatorFile, log) + ResetAll(config.DBDir(), config.PrivValidatorFile(), log) } // XXX: this is totally unsafe. // it's only suitable for testnets. func resetPrivValidator(cmd *cobra.Command, args []string) { - resetPrivValidatorLocal(config.PrivValidatorFile, log) + resetPrivValidatorLocal(config.PrivValidatorFile(), log) } // Exported so other CLI tools can use it diff --git a/cmd/tendermint/commands/root.go b/cmd/tendermint/commands/root.go index 63ee0db5c..28527b7f1 100644 --- a/cmd/tendermint/commands/root.go +++ b/cmd/tendermint/commands/root.go @@ -14,7 +14,7 @@ var ( ) func init() { - config = cfg.DefaultConfig("REMOVE-ROOT") + config = cfg.DefaultConfig() RootCmd.PersistentFlags().String("log_level", config.LogLevel, "Log level") } diff --git a/cmd/tendermint/commands/run_node.go b/cmd/tendermint/commands/run_node.go index d8c268c26..a2c363dc9 100644 --- a/cmd/tendermint/commands/run_node.go +++ b/cmd/tendermint/commands/run_node.go @@ -56,7 +56,7 @@ func runNode(cmd *cobra.Command, args []string) error { // This is for Mintnet compatibility. // TODO: If Mintnet gets deprecated or genesis_file is // always available, remove. - genDocFile := config.GenesisFile + genDocFile := config.GenesisFile() if !cmn.FileExists(genDocFile) { log.Notice(cmn.Fmt("Waiting for genesis file %v...", genDocFile)) for { diff --git a/cmd/tendermint/commands/show_validator.go b/cmd/tendermint/commands/show_validator.go index b741ba8c0..6f2e2a07e 100644 --- a/cmd/tendermint/commands/show_validator.go +++ b/cmd/tendermint/commands/show_validator.go @@ -20,7 +20,7 @@ func init() { } func showValidator(cmd *cobra.Command, args []string) { - privValidator := types.LoadOrGenPrivValidator(config.PrivValidatorFile) + privValidator := types.LoadOrGenPrivValidator(config.PrivValidatorFile()) pubKeyJSONBytes, _ := data.ToJSON(privValidator.PubKey) fmt.Println(string(pubKeyJSONBytes)) } diff --git a/config/config.go b/config/config.go index 531ef9a50..7490f8037 100644 --- a/config/config.go +++ b/config/config.go @@ -1,6 +1,7 @@ package config import ( + "path/filepath" "time" "github.com/tendermint/tendermint/types" @@ -16,34 +17,45 @@ type Config struct { Consensus *ConsensusConfig `mapstructure:"consensus"` } -func DefaultConfig(rootDir string) *Config { +func DefaultConfig() *Config { return &Config{ - BaseConfig: DefaultBaseConfig(rootDir), - P2P: DefaultP2PConfig(rootDir), - Mempool: DefaultMempoolConfig(rootDir), - Consensus: DefaultConsensusConfig(rootDir), + BaseConfig: DefaultBaseConfig(), + P2P: DefaultP2PConfig(), + Mempool: DefaultMempoolConfig(), + Consensus: DefaultConsensusConfig(), } } -func TestConfig(rootDir string) *Config { +func TestConfig() *Config { return &Config{ - BaseConfig: DefaultBaseConfig(rootDir), - P2P: DefaultP2PConfig(rootDir), - Mempool: DefaultMempoolConfig(rootDir), - Consensus: TestConsensusConfig(rootDir), + BaseConfig: DefaultBaseConfig(), + P2P: DefaultP2PConfig(), + Mempool: DefaultMempoolConfig(), + Consensus: TestConsensusConfig(), } } +// TODO: set this from root or home.... or default.... +func SetRoot(cfg *Config, root string) { + cfg.BaseConfig.RootDir = root + cfg.P2P.RootDir = root + cfg.Mempool.RootDir = root + cfg.Consensus.RootDir = root +} + // BaseConfig struct for a Tendermint node type BaseConfig struct { + // TODO: set this from root or home.... or default.... + RootDir string `mapstructure:"home"` + // The ID of the chain to join (should be signed with every transaction and vote) ChainID string `mapstructure:"chain_id"` // A JSON file containing the initial validator set and other meta data - GenesisFile string `mapstructure:"genesis_file"` + Genesis string `mapstructure:"genesis_file"` // A JSON file containing the private key to use as a validator in the consensus protocol - PrivValidatorFile string `mapstructure:"priv_validator_file"` + PrivValidator string `mapstructure:"priv_validator_file"` // A custom human readable name for this node Moniker string `mapstructure:"moniker"` @@ -77,7 +89,7 @@ type BaseConfig struct { DBBackend string `mapstructure:"db_backend"` // Database directory - DBDir string `mapstructure:"db_dir"` + DBPath string `mapstructure:"db_dir"` // TCP or UNIX socket address for the RPC server to listen on RPCListenAddress string `mapstructure:"rpc_laddr"` @@ -87,10 +99,10 @@ type BaseConfig struct { GRPCListenAddress string `mapstructure:"grpc_laddr"` } -func DefaultBaseConfig(rootDir string) *BaseConfig { +func DefaultBaseConfig() *BaseConfig { return &BaseConfig{ - GenesisFile: rootDir + "/genesis.json", - PrivValidatorFile: rootDir + "/priv_validator.json", + Genesis: "genesis.json", + PrivValidator: "priv_validator.json", Moniker: "anonymous", ProxyApp: "tcp://127.0.0.1:46658", ABCI: "socket", @@ -100,51 +112,74 @@ func DefaultBaseConfig(rootDir string) *BaseConfig { FilterPeers: false, TxIndex: "kv", DBBackend: "leveldb", - DBDir: rootDir + "/data", + DBPath: "data", RPCListenAddress: "tcp://0.0.0.0:46657", GRPCListenAddress: "", } } +func (b *BaseConfig) GenesisFile() string { + return rootify(b.Genesis, b.RootDir) +} + +func (b *BaseConfig) PrivValidatorFile() string { + return rootify(b.PrivValidator, b.RootDir) +} + +func (b *BaseConfig) DBDir() string { + return rootify(b.DBPath, b.RootDir) +} + type P2PConfig struct { + RootDir string `mapstructure:"home"` ListenAddress string `mapstructure:"laddr"` Seeds string `mapstructure:"seeds"` SkipUPNP bool `mapstructure:"skip_upnp"` - AddrBookFile string `mapstructure:"addr_book_file"` + AddrBook string `mapstructure:"addr_book_file"` AddrBookStrict bool `mapstructure:"addr_book_strict"` PexReactor bool `mapstructure:"pex_reactor"` MaxNumPeers int `mapstructure:"max_num_peers"` } -func DefaultP2PConfig(rootDir string) *P2PConfig { +func DefaultP2PConfig() *P2PConfig { return &P2PConfig{ ListenAddress: "tcp://0.0.0.0:46656", - AddrBookFile: rootDir + "/addrbook.json", + AddrBook: "addrbook.json", AddrBookStrict: true, MaxNumPeers: 50, } } +func (p *P2PConfig) AddrBookFile() string { + return rootify(p.AddrBook, p.RootDir) +} + type MempoolConfig struct { + RootDir string `mapstructure:"home"` Recheck bool `mapstructure:"recheck"` // true RecheckEmpty bool `mapstructure:"recheck_empty"` // true Broadcast bool `mapstructure:"broadcast"` // true - WalDir string `mapstructure:"wal_dir"` // + WalPath string `mapstructure:"wal_dir"` // } -func DefaultMempoolConfig(rootDir string) *MempoolConfig { +func DefaultMempoolConfig() *MempoolConfig { return &MempoolConfig{ Recheck: true, RecheckEmpty: true, Broadcast: true, - WalDir: rootDir + "/data/mempool.wal", + WalPath: "data/mempool.wal", } } +func (m *MempoolConfig) WalDir() string { + return rootify(m.WalPath, m.RootDir) +} + // ConsensusConfig holds timeouts and details about the WAL, the block structure, // and timeouts in the consensus protocol. type ConsensusConfig struct { - WalFile string `mapstructure:"wal_file"` + RootDir string `mapstructure:"home"` + WalPath string `mapstructure:"wal_file"` WalLight bool `mapstructure:"wal_light"` // All timeouts are in ms @@ -188,9 +223,9 @@ func (cfg *ConsensusConfig) Commit(t time.Time) time.Time { return t.Add(time.Duration(cfg.TimeoutCommit) * time.Millisecond) } -func DefaultConsensusConfig(rootDir string) *ConsensusConfig { +func DefaultConsensusConfig() *ConsensusConfig { return &ConsensusConfig{ - WalFile: rootDir + "/data/cs.wal/wal", + WalPath: "data/cs.wal/wal", WalLight: false, TimeoutPropose: 3000, TimeoutProposeDelta: 500, @@ -206,8 +241,8 @@ func DefaultConsensusConfig(rootDir string) *ConsensusConfig { } } -func TestConsensusConfig(rootDir string) *ConsensusConfig { - config := DefaultConsensusConfig(rootDir) +func TestConsensusConfig() *ConsensusConfig { + config := DefaultConsensusConfig() config.TimeoutPropose = 2000 config.TimeoutProposeDelta = 1 config.TimeoutPrevote = 10 @@ -218,3 +253,15 @@ func TestConsensusConfig(rootDir string) *ConsensusConfig { config.SkipTimeoutCommit = true return config } + +func (c *ConsensusConfig) WalFile() string { + return rootify(c.WalPath, c.RootDir) +} + +// helper function to make config creation independent of root dir +func rootify(path, root string) string { + if filepath.IsAbs(path) { + return path + } + return filepath.Join(root, path) +} diff --git a/consensus/replay_file.go b/consensus/replay_file.go index e7d904bff..3735f8942 100644 --- a/consensus/replay_file.go +++ b/consensus/replay_file.go @@ -23,7 +23,7 @@ import ( func RunReplayFile(config *cfg.BaseConfig, csConfig *cfg.ConsensusConfig, console bool) { consensusState := newConsensusStateForReplay(config, csConfig) - if err := consensusState.ReplayFile(csConfig.WalFile, console); err != nil { + if err := consensusState.ReplayFile(csConfig.WalFile(), console); err != nil { cmn.Exit(cmn.Fmt("Error during consensus replay: %v", err)) } } @@ -237,15 +237,15 @@ func (pb *playback) replayConsoleLoop() int { // convenience for replay mode func newConsensusStateForReplay(config *cfg.BaseConfig, csConfig *cfg.ConsensusConfig) *ConsensusState { // Get BlockStore - blockStoreDB := dbm.NewDB("blockstore", config.DBBackend, config.DBDir) + blockStoreDB := dbm.NewDB("blockstore", config.DBBackend, config.DBDir()) blockStore := bc.NewBlockStore(blockStoreDB) // Get State - stateDB := dbm.NewDB("state", config.DBBackend, config.DBDir) - state := sm.MakeGenesisStateFromFile(stateDB, config.GenesisFile) + stateDB := dbm.NewDB("state", config.DBBackend, config.DBDir()) + state := sm.MakeGenesisStateFromFile(stateDB, config.GenesisFile()) // Create proxyAppConn connection (consensus, mempool, query) - clientCreator := proxy.DefaultClientCreator(config.ProxyApp, config.ABCI, config.DBDir) + clientCreator := proxy.DefaultClientCreator(config.ProxyApp, config.ABCI, config.DBDir()) proxyApp := proxy.NewAppConns(clientCreator, NewHandshaker(state, blockStore)) _, err := proxyApp.Start() if err != nil { diff --git a/consensus/state.go b/consensus/state.go index a565dfdce..579f22ce5 100644 --- a/consensus/state.go +++ b/consensus/state.go @@ -302,7 +302,7 @@ func (cs *ConsensusState) LoadCommit(height int) *types.Commit { func (cs *ConsensusState) OnStart() error { - walFile := cs.config.WalFile + walFile := cs.config.WalFile() if err := cs.OpenWAL(walFile); err != nil { log.Error("Error loading ConsensusState wal", "error", err.Error()) return err diff --git a/mempool/mempool.go b/mempool/mempool.go index 6b168897c..44a20e6f5 100644 --- a/mempool/mempool.go +++ b/mempool/mempool.go @@ -86,7 +86,7 @@ func NewMempool(config *cfg.MempoolConfig, proxyAppConn proxy.AppConnMempool) *M } func (mem *Mempool) initWAL() { - walDir := mem.config.WalDir + walDir := mem.config.WalDir() if walDir != "" { err := cmn.EnsureDir(walDir, 0700) if err != nil { diff --git a/node/node.go b/node/node.go index b206c2ad9..6896bc4f1 100644 --- a/node/node.go +++ b/node/node.go @@ -59,20 +59,20 @@ type Node struct { func NewNodeDefault(config *cfg.Config) *Node { // Get PrivValidator - privValidator := types.LoadOrGenPrivValidator(config.PrivValidatorFile) + privValidator := types.LoadOrGenPrivValidator(config.PrivValidatorFile()) return NewNode(config, privValidator, - proxy.DefaultClientCreator(config.ProxyApp, config.ABCI, config.DBDir)) + proxy.DefaultClientCreator(config.ProxyApp, config.ABCI, config.DBDir())) } func NewNode(config *cfg.Config, privValidator *types.PrivValidator, clientCreator proxy.ClientCreator) *Node { // Get BlockStore - blockStoreDB := dbm.NewDB("blockstore", config.DBBackend, config.DBDir) + blockStoreDB := dbm.NewDB("blockstore", config.DBBackend, config.DBDir()) blockStore := bc.NewBlockStore(blockStoreDB) // Get State - stateDB := dbm.NewDB("state", config.DBBackend, config.DBDir) - state := sm.GetState(stateDB, config.GenesisFile) + stateDB := dbm.NewDB("state", config.DBBackend, config.DBDir()) + state := sm.GetState(stateDB, config.GenesisFile()) // add the chainid and number of validators to the global config // TODO: Set ChainID. eg: @@ -93,7 +93,7 @@ func NewNode(config *cfg.Config, privValidator *types.PrivValidator, clientCreat var txIndexer txindex.TxIndexer switch config.TxIndex { case "kv": - store := dbm.NewDB("tx_index", config.DBBackend, config.DBDir) + store := dbm.NewDB("tx_index", config.DBBackend, config.DBDir()) txIndexer = kv.NewTxIndex(store) default: txIndexer = &null.TxIndex{} @@ -142,7 +142,7 @@ func NewNode(config *cfg.Config, privValidator *types.PrivValidator, clientCreat // Optionally, start the pex reactor var addrBook *p2p.AddrBook if config.P2P.PexReactor { - addrBook = p2p.NewAddrBook(config.P2P.AddrBookFile, config.P2P.AddrBookStrict) + addrBook = p2p.NewAddrBook(config.P2P.AddrBookFile(), config.P2P.AddrBookStrict) pexReactor := p2p.NewPEXReactor(addrBook) sw.AddReactor("PEX", pexReactor) } From 9109b20852ec7c414e8c8d44ea4a661c428072b3 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Thu, 4 May 2017 21:59:53 -0400 Subject: [PATCH 268/309] SetRoot --- cmd/tendermint/commands/init.go | 4 ++-- cmd/tendermint/commands/root.go | 2 ++ config/config.go | 29 +++++++++++++++-------------- config/toml.go | 2 +- consensus/replay_file.go | 4 ++-- 5 files changed, 22 insertions(+), 19 deletions(-) diff --git a/cmd/tendermint/commands/init.go b/cmd/tendermint/commands/init.go index 5c3fbb52a..ba3b711b3 100644 --- a/cmd/tendermint/commands/init.go +++ b/cmd/tendermint/commands/init.go @@ -40,8 +40,8 @@ func initFiles(cmd *cobra.Command, args []string) { genDoc.SaveAs(genFile) } - log.Notice("Initialized tendermint", "genesis", config.GenesisFile, "priv_validator", config.PrivValidatorFile) + log.Notice("Initialized tendermint", "genesis", config.GenesisFile(), "priv_validator", config.PrivValidatorFile()) } else { - log.Notice("Already initialized", "priv_validator", config.PrivValidatorFile) + log.Notice("Already initialized", "priv_validator", config.PrivValidatorFile()) } } diff --git a/cmd/tendermint/commands/root.go b/cmd/tendermint/commands/root.go index 28527b7f1..5771a9b29 100644 --- a/cmd/tendermint/commands/root.go +++ b/cmd/tendermint/commands/root.go @@ -23,6 +23,8 @@ var RootCmd = &cobra.Command{ Short: "Tendermint Core (BFT Consensus) in Go", PersistentPreRunE: func(cmd *cobra.Command, args []string) error { err := viper.Unmarshal(config) + cfg.SetRoot(config, config.RootDir) + cfg.EnsureRoot(config.RootDir) logger.SetLogLevel(config.LogLevel) return err }, diff --git a/config/config.go b/config/config.go index 7490f8037..178f19dbc 100644 --- a/config/config.go +++ b/config/config.go @@ -9,7 +9,7 @@ import ( type Config struct { // Top level options use an anonymous struct - *BaseConfig `mapstructure:",squash"` + BaseConfig `mapstructure:",squash"` // Options for services P2P *P2PConfig `mapstructure:"p2p"` @@ -35,7 +35,7 @@ func TestConfig() *Config { } } -// TODO: set this from root or home.... or default.... +// Set the RootDir for all Config structs func SetRoot(cfg *Config, root string) { cfg.BaseConfig.RootDir = root cfg.P2P.RootDir = root @@ -45,7 +45,8 @@ func SetRoot(cfg *Config, root string) { // BaseConfig struct for a Tendermint node type BaseConfig struct { - // TODO: set this from root or home.... or default.... + // The root directory for all data. + // This should be set in viper so it can unmarshal into this struct RootDir string `mapstructure:"home"` // The ID of the chain to join (should be signed with every transaction and vote) @@ -99,8 +100,8 @@ type BaseConfig struct { GRPCListenAddress string `mapstructure:"grpc_laddr"` } -func DefaultBaseConfig() *BaseConfig { - return &BaseConfig{ +func DefaultBaseConfig() BaseConfig { + return BaseConfig{ Genesis: "genesis.json", PrivValidator: "priv_validator.json", Moniker: "anonymous", @@ -118,15 +119,15 @@ func DefaultBaseConfig() *BaseConfig { } } -func (b *BaseConfig) GenesisFile() string { +func (b BaseConfig) GenesisFile() string { return rootify(b.Genesis, b.RootDir) } -func (b *BaseConfig) PrivValidatorFile() string { +func (b BaseConfig) PrivValidatorFile() string { return rootify(b.PrivValidator, b.RootDir) } -func (b *BaseConfig) DBDir() string { +func (b BaseConfig) DBDir() string { return rootify(b.DBPath, b.RootDir) } @@ -156,10 +157,10 @@ func (p *P2PConfig) AddrBookFile() string { type MempoolConfig struct { RootDir string `mapstructure:"home"` - Recheck bool `mapstructure:"recheck"` // true - RecheckEmpty bool `mapstructure:"recheck_empty"` // true - Broadcast bool `mapstructure:"broadcast"` // true - WalPath string `mapstructure:"wal_dir"` // + Recheck bool `mapstructure:"recheck"` + RecheckEmpty bool `mapstructure:"recheck_empty"` + Broadcast bool `mapstructure:"broadcast"` + WalPath string `mapstructure:"wal_dir"` } func DefaultMempoolConfig() *MempoolConfig { @@ -236,8 +237,8 @@ func DefaultConsensusConfig() *ConsensusConfig { TimeoutCommit: 1000, SkipTimeoutCommit: false, MaxBlockSizeTxs: 10000, - MaxBlockSizeBytes: 1, // TODO - BlockPartSize: types.DefaultBlockPartSize, + MaxBlockSizeBytes: 1, // TODO + BlockPartSize: types.DefaultBlockPartSize, // TODO: we shouldnt be importing types } } diff --git a/config/toml.go b/config/toml.go index a9e6ba302..aff6bd1aa 100644 --- a/config/toml.go +++ b/config/toml.go @@ -10,7 +10,7 @@ import ( /****** these are for production settings ***********/ -func initRoot(rootDir string) { +func EnsureRoot(rootDir string) { cmn.EnsureDir(rootDir, 0700) cmn.EnsureDir(rootDir+"/data", 0700) diff --git a/consensus/replay_file.go b/consensus/replay_file.go index 3735f8942..a0af8b853 100644 --- a/consensus/replay_file.go +++ b/consensus/replay_file.go @@ -20,7 +20,7 @@ import ( //-------------------------------------------------------- // replay messages interactively or all at once -func RunReplayFile(config *cfg.BaseConfig, csConfig *cfg.ConsensusConfig, console bool) { +func RunReplayFile(config cfg.BaseConfig, csConfig *cfg.ConsensusConfig, console bool) { consensusState := newConsensusStateForReplay(config, csConfig) if err := consensusState.ReplayFile(csConfig.WalFile(), console); err != nil { @@ -235,7 +235,7 @@ func (pb *playback) replayConsoleLoop() int { //-------------------------------------------------------------------------------- // convenience for replay mode -func newConsensusStateForReplay(config *cfg.BaseConfig, csConfig *cfg.ConsensusConfig) *ConsensusState { +func newConsensusStateForReplay(config cfg.BaseConfig, csConfig *cfg.ConsensusConfig) *ConsensusState { // Get BlockStore blockStoreDB := dbm.NewDB("blockstore", config.DBBackend, config.DBDir()) blockStore := bc.NewBlockStore(blockStoreDB) From 46151720f842a17fdc368a60abd8b0dcc884304a Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Thu, 4 May 2017 22:33:08 -0400 Subject: [PATCH 269/309] fix tests --- cmd/tendermint/commands/root.go | 2 +- config/config.go | 33 +++++++++++++++++++++++++++++--- config/toml.go | 10 +++++++++- consensus/common_test.go | 34 ++++++++++----------------------- consensus/replay_test.go | 24 ++++++++++++----------- consensus/state_test.go | 8 ++++---- mempool/mempool_test.go | 18 ++--------------- node/node_test.go | 5 ++--- p2p/switch_test.go | 6 ++++-- rpc/test/helpers.go | 22 ++++++++++----------- state/state_test.go | 31 ++++++++++-------------------- 11 files changed, 96 insertions(+), 97 deletions(-) diff --git a/cmd/tendermint/commands/root.go b/cmd/tendermint/commands/root.go index 5771a9b29..fd369d934 100644 --- a/cmd/tendermint/commands/root.go +++ b/cmd/tendermint/commands/root.go @@ -23,7 +23,7 @@ var RootCmd = &cobra.Command{ Short: "Tendermint Core (BFT Consensus) in Go", PersistentPreRunE: func(cmd *cobra.Command, args []string) error { err := viper.Unmarshal(config) - cfg.SetRoot(config, config.RootDir) + config.SetRoot(config.RootDir) cfg.EnsureRoot(config.RootDir) logger.SetLogLevel(config.LogLevel) return err diff --git a/config/config.go b/config/config.go index 178f19dbc..2c78524b5 100644 --- a/config/config.go +++ b/config/config.go @@ -28,19 +28,20 @@ func DefaultConfig() *Config { func TestConfig() *Config { return &Config{ - BaseConfig: DefaultBaseConfig(), - P2P: DefaultP2PConfig(), + BaseConfig: TestBaseConfig(), + P2P: TestP2PConfig(), Mempool: DefaultMempoolConfig(), Consensus: TestConsensusConfig(), } } // Set the RootDir for all Config structs -func SetRoot(cfg *Config, root string) { +func (cfg *Config) SetRoot(root string) *Config { cfg.BaseConfig.RootDir = root cfg.P2P.RootDir = root cfg.Mempool.RootDir = root cfg.Consensus.RootDir = root + return cfg } // BaseConfig struct for a Tendermint node @@ -119,6 +120,17 @@ func DefaultBaseConfig() BaseConfig { } } +func TestBaseConfig() BaseConfig { + conf := DefaultBaseConfig() + conf.ChainID = "tendermint_test" + conf.ProxyApp = "dummy" + conf.FastSync = false + conf.DBBackend = "memdb" + conf.RPCListenAddress = "tcp://0.0.0.0:36657" + conf.GRPCListenAddress = "tcp://0.0.0.0:36658" + return conf +} + func (b BaseConfig) GenesisFile() string { return rootify(b.Genesis, b.RootDir) } @@ -151,6 +163,13 @@ func DefaultP2PConfig() *P2PConfig { } } +func TestP2PConfig() *P2PConfig { + conf := DefaultP2PConfig() + conf.ListenAddress = "tcp://0.0.0.0:36656" + conf.SkipUPNP = true + return conf +} + func (p *P2PConfig) AddrBookFile() string { return rootify(p.AddrBook, p.RootDir) } @@ -182,6 +201,7 @@ type ConsensusConfig struct { RootDir string `mapstructure:"home"` WalPath string `mapstructure:"wal_file"` WalLight bool `mapstructure:"wal_light"` + walFile string // overrides WalPath if set // All timeouts are in ms TimeoutPropose int `mapstructure:"timeout_propose"` @@ -256,9 +276,16 @@ func TestConsensusConfig() *ConsensusConfig { } func (c *ConsensusConfig) WalFile() string { + if c.walFile != "" { + return c.walFile + } return rootify(c.WalPath, c.RootDir) } +func (c *ConsensusConfig) SetWalFile(walFile string) { + c.walFile = walFile +} + // helper function to make config creation independent of root dir func rootify(path, root string) string { if filepath.IsAbs(path) { diff --git a/config/toml.go b/config/toml.go index aff6bd1aa..d07b3281f 100644 --- a/config/toml.go +++ b/config/toml.go @@ -3,9 +3,11 @@ package config import ( "os" "path" + "path/filepath" "strings" cmn "github.com/tendermint/tmlibs/common" + "github.com/tendermint/tmlibs/logger" ) /****** these are for production settings ***********/ @@ -44,7 +46,9 @@ func defaultConfig(moniker string) (defaultConfig string) { /****** these are for test settings ***********/ -func initTestRoot(rootDir string) { +func ResetTestRoot(testName string) *Config { + rootDir := os.ExpandEnv("$HOME/.tendermint_test") + rootDir = filepath.Join(rootDir, testName) // Remove ~/.tendermint_test_bak if cmn.FileExists(rootDir + "_bak") { err := os.RemoveAll(rootDir + "_bak") @@ -77,6 +81,10 @@ func initTestRoot(rootDir string) { } // we always overwrite the priv val cmn.MustWriteFile(privFilePath, []byte(testPrivValidator), 0644) + + config := TestConfig().SetRoot(rootDir) + logger.SetLogLevel(config.LogLevel) + return config } var testConfigTmpl = `# This is a TOML config file. diff --git a/consensus/common_test.go b/consensus/common_test.go index ed7be9f36..463b748f8 100644 --- a/consensus/common_test.go +++ b/consensus/common_test.go @@ -15,7 +15,6 @@ import ( abci "github.com/tendermint/abci/types" bc "github.com/tendermint/tendermint/blockchain" cfg "github.com/tendermint/tendermint/config" - "github.com/tendermint/tendermint/config/tendermint_test" mempl "github.com/tendermint/tendermint/mempool" "github.com/tendermint/tendermint/p2p" sm "github.com/tendermint/tendermint/state" @@ -28,7 +27,7 @@ import ( ) // genesis, chain_id, priv_val -var config *NodeConfig // NOTE: must be reset for each _test.go file +var config *cfg.Config // NOTE: must be reset for each _test.go file var ensureTimeout = time.Duration(2) func ensureDir(dir string, mode os.FileMode) { @@ -37,21 +36,8 @@ func ensureDir(dir string, mode os.FileMode) { } } -type NodeConfig struct { - cfg.Config `mapstructure:",squash"` - P2P *p2p.Config `mapstructure:"p2p"` - Mempool *mempl.Config `mapstructure:"mempool"` - Consensus *Config `mapstructure:"consensus"` -} - -// TODO: This is the same as NodeConfig. Should we move the configs to types (?) -func ResetConfig(name string) *NodeConfig { - viperConfig := tendermint_test.ResetConfig(name) - config := new(NodeConfig) - if err := viperConfig.Unmarshal(config); err != nil { - panic(err) - } - return config +func ResetConfig(name string) *cfg.Config { + return cfg.ResetTestRoot(name) } //------------------------------------------------------------------------------- @@ -251,7 +237,7 @@ func newConsensusState(state *sm.State, pv *types.PrivValidator, app abci.Applic return newConsensusStateWithConfig(config, state, pv, app) } -func newConsensusStateWithConfig(thisConfig *NodeConfig, state *sm.State, pv *types.PrivValidator, app abci.Application) *ConsensusState { +func newConsensusStateWithConfig(thisConfig *cfg.Config, state *sm.State, pv *types.PrivValidator, app abci.Application) *ConsensusState { // Get BlockStore blockDB := dbm.NewMemDB() blockStore := bc.NewBlockStore(blockDB) @@ -274,8 +260,8 @@ func newConsensusStateWithConfig(thisConfig *NodeConfig, state *sm.State, pv *ty return cs } -func loadPrivValidator(config *NodeConfig) *types.PrivValidator { - privValidatorFile := config.PrivValidatorFile +func loadPrivValidator(config *cfg.Config) *types.PrivValidator { + privValidatorFile := config.PrivValidatorFile() ensureDir(path.Dir(privValidatorFile), 0700) privValidator := types.LoadOrGenPrivValidator(privValidatorFile) privValidator.Reset() @@ -284,7 +270,7 @@ func loadPrivValidator(config *NodeConfig) *types.PrivValidator { func fixedConsensusState() *ConsensusState { stateDB := dbm.NewMemDB() - state := sm.MakeGenesisStateFromFile(stateDB, config.GenesisFile) + state := sm.MakeGenesisStateFromFile(stateDB, config.GenesisFile()) privValidator := loadPrivValidator(config) cs := newConsensusState(state, privValidator, counter.NewCounterApplication(true)) return cs @@ -292,7 +278,7 @@ func fixedConsensusState() *ConsensusState { func fixedConsensusStateDummy() *ConsensusState { stateDB := dbm.NewMemDB() - state := sm.MakeGenesisStateFromFile(stateDB, config.GenesisFile) + state := sm.MakeGenesisStateFromFile(stateDB, config.GenesisFile()) privValidator := loadPrivValidator(config) cs := newConsensusState(state, privValidator, dummy.NewDummyApplication()) return cs @@ -338,7 +324,7 @@ func randConsensusNet(nValidators int, testName string, tickerFunc func() Timeou state := sm.MakeGenesisState(db, genDoc) state.Save() thisConfig := ResetConfig(Fmt("%s_%d", testName, i)) - ensureDir(path.Dir(thisConfig.Consensus.WalFile), 0700) // dir for wal + ensureDir(path.Dir(thisConfig.Consensus.WalFile()), 0700) // dir for wal css[i] = newConsensusStateWithConfig(thisConfig, state, privVals[i], appFunc()) css[i].SetTimeoutTicker(tickerFunc()) } @@ -354,7 +340,7 @@ func randConsensusNetWithPeers(nValidators, nPeers int, testName string, tickerF state := sm.MakeGenesisState(db, genDoc) state.Save() thisConfig := ResetConfig(Fmt("%s_%d", testName, i)) - ensureDir(path.Dir(thisConfig.Consensus.WalFile), 0700) // dir for wal + ensureDir(path.Dir(thisConfig.Consensus.WalFile()), 0700) // dir for wal var privVal *types.PrivValidator if i < nValidators { privVal = privVals[i] diff --git a/consensus/replay_test.go b/consensus/replay_test.go index 9ab04359c..778e5c458 100644 --- a/consensus/replay_test.go +++ b/consensus/replay_test.go @@ -15,11 +15,13 @@ import ( "github.com/tendermint/abci/example/dummy" "github.com/tendermint/go-crypto" "github.com/tendermint/go-wire" + cmn "github.com/tendermint/tmlibs/common" + dbm "github.com/tendermint/tmlibs/db" + + cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/proxy" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" - cmn "github.com/tendermint/tmlibs/common" - dbm "github.com/tendermint/tmlibs/db" ) func init() { @@ -133,7 +135,7 @@ func waitForBlock(newBlockCh chan interface{}, thisCase *testCase, i int) { func runReplayTest(t *testing.T, cs *ConsensusState, walFile string, newBlockCh chan interface{}, thisCase *testCase, i int) { - cs.config.WalFile = walFile + cs.config.SetWalFile(walFile) started, err := cs.Start() if err != nil { t.Fatalf("Cannot start consensus: %v", err) @@ -314,9 +316,9 @@ func testHandshakeReplay(t *testing.T, nBlocks int, mode uint) { t.Fatal(err) } walFile := writeWAL(string(walBody)) - config.Consensus.WalFile = walFile + config.Consensus.SetWalFile(walFile) - privVal := types.LoadPrivValidator(config.PrivValidatorFile) + privVal := types.LoadPrivValidator(config.PrivValidatorFile()) testPartSize = config.Consensus.BlockPartSize wal, err := NewWAL(walFile, false) @@ -336,7 +338,7 @@ func testHandshakeReplay(t *testing.T, nBlocks int, mode uint) { latestAppHash := buildTMStateFromChain(config, state, chain, mode) // make a new client creator - dummyApp := dummy.NewPersistentDummyApplication(path.Join(config.DBDir, "2")) + dummyApp := dummy.NewPersistentDummyApplication(path.Join(config.DBDir(), "2")) clientCreator2 := proxy.NewLocalClientCreator(dummyApp) if nBlocks > 0 { // run nBlocks against a new client to build up the app state. @@ -415,9 +417,9 @@ func buildAppStateFromChain(proxyApp proxy.AppConns, } -func buildTMStateFromChain(config *NodeConfig, state *sm.State, chain []*types.Block, mode uint) []byte { +func buildTMStateFromChain(config *cfg.Config, state *sm.State, chain []*types.Block, mode uint) []byte { // run the whole chain against this client to build up the tendermint state - clientCreator := proxy.NewLocalClientCreator(dummy.NewPersistentDummyApplication(path.Join(config.DBDir, "1"))) + clientCreator := proxy.NewLocalClientCreator(dummy.NewPersistentDummyApplication(path.Join(config.DBDir(), "1"))) proxyApp := proxy.NewAppConns(clientCreator, nil) // sm.NewHandshaker(config, state, store, ReplayLastBlock)) if _, err := proxyApp.Start(); err != nil { panic(err) @@ -612,7 +614,7 @@ func makeBlockchain(t *testing.T, chainID string, nBlocks int, privVal *types.Pr } // fresh state and mock store -func stateAndStore(config *NodeConfig, pubKey crypto.PubKey) (*sm.State, *mockBlockStore) { +func stateAndStore(config *cfg.Config, pubKey crypto.PubKey) (*sm.State, *mockBlockStore) { stateDB := dbm.NewMemDB() state := sm.MakeGenesisStateFromFile(stateDB, config.GenesisFile()) store := NewMockBlockStore(config) @@ -623,13 +625,13 @@ func stateAndStore(config *NodeConfig, pubKey crypto.PubKey) (*sm.State, *mockBl // mock block store type mockBlockStore struct { - config *NodeConfig + config *cfg.Config chain []*types.Block commits []*types.Commit } // TODO: NewBlockStore(db.NewMemDB) ... -func NewMockBlockStore(config *NodeConfig) *mockBlockStore { +func NewMockBlockStore(config *cfg.Config) *mockBlockStore { return &mockBlockStore{config, nil, nil} } diff --git a/consensus/state_test.go b/consensus/state_test.go index 990622738..f4eed5732 100644 --- a/consensus/state_test.go +++ b/consensus/state_test.go @@ -14,8 +14,8 @@ func init() { config = ResetConfig("consensus_state_test") } -func (config *Config) ensureProposeTimeout() time.Duration { - return time.Duration(config.TimeoutPropose*2) * time.Millisecond +func ensureProposeTimeout(timeoutPropose int) time.Duration { + return time.Duration(timeoutPropose*2) * time.Millisecond } /* @@ -125,7 +125,7 @@ func TestEnterProposeNoPrivValidator(t *testing.T) { startTestRound(cs, height, round) // if we're not a validator, EnterPropose should timeout - ticker := time.NewTicker(cs.config.ensureProposeTimeout()) + ticker := time.NewTicker(ensureProposeTimeout(cs.config.TimeoutPropose)) select { case <-timeoutCh: case <-ticker.C: @@ -166,7 +166,7 @@ func TestEnterProposeYesPrivValidator(t *testing.T) { } // if we're a validator, enterPropose should not timeout - ticker := time.NewTicker(cs.config.ensureProposeTimeout()) + ticker := time.NewTicker(ensureProposeTimeout(cs.config.TimeoutPropose)) select { case <-timeoutCh: panic("Expected EnterPropose not to timeout") diff --git a/mempool/mempool_test.go b/mempool/mempool_test.go index a1bd188d4..dd15493d0 100644 --- a/mempool/mempool_test.go +++ b/mempool/mempool_test.go @@ -6,33 +6,19 @@ import ( "github.com/tendermint/abci/example/counter" cfg "github.com/tendermint/tendermint/config" - "github.com/tendermint/tendermint/config/tendermint_test" "github.com/tendermint/tendermint/proxy" "github.com/tendermint/tendermint/types" ) -func ResetConfig(name string) *Config { - viperConfig := tendermint_test.ResetConfig(name) - config := new(struct { - cfg.Config `mapstructure:",squash"` - Mempool *Config `mapstructure:"mempool"` - }) - if err := viperConfig.Unmarshal(config); err != nil { - panic(err) - } - return config.Mempool - -} - func TestSerialReap(t *testing.T) { - config := ResetConfig("mempool_test") + config := cfg.ResetTestRoot("mempool_test") app := counter.NewCounterApplication(true) app.SetOption("serial", "on") cc := proxy.NewLocalClientCreator(app) appConnMem, _ := cc.NewABCIClient() appConnCon, _ := cc.NewABCIClient() - mempool := NewMempool(config, appConnMem) + mempool := NewMempool(config.Mempool, appConnMem) deliverTxsRange := func(start, end int) { // Deliver some txs. diff --git a/node/node_test.go b/node/node_test.go index ba9ac7234..e00a67ecb 100644 --- a/node/node_test.go +++ b/node/node_test.go @@ -4,12 +4,11 @@ import ( "testing" "time" - "github.com/tendermint/tendermint/config/tendermint_test" + cfg "github.com/tendermint/tendermint/config" ) func TestNodeStartStop(t *testing.T) { - viperConfig := tendermint_test.ResetConfig("node_node_test") - config := ConfigFromViper(viperConfig) + config := cfg.ResetTestRoot("node_node_test") // Create & start node n := NewNodeDefault(config) diff --git a/p2p/switch_test.go b/p2p/switch_test.go index d2f616922..da5f43aa3 100644 --- a/p2p/switch_test.go +++ b/p2p/switch_test.go @@ -13,14 +13,16 @@ import ( crypto "github.com/tendermint/go-crypto" wire "github.com/tendermint/go-wire" cmn "github.com/tendermint/tmlibs/common" + + cfg "github.com/tendermint/tendermint/config" ) var ( - config *Config + config *cfg.P2PConfig ) func init() { - config = NewDefaultConfig("") + config = cfg.DefaultP2PConfig() config.PexReactor = true } diff --git a/rpc/test/helpers.go b/rpc/test/helpers.go index c5542fa7c..034816cd1 100644 --- a/rpc/test/helpers.go +++ b/rpc/test/helpers.go @@ -14,7 +14,7 @@ import ( logger "github.com/tendermint/tmlibs/logger" abci "github.com/tendermint/abci/types" - "github.com/tendermint/tendermint/config/tendermint_test" + cfg "github.com/tendermint/tendermint/config" nm "github.com/tendermint/tendermint/node" "github.com/tendermint/tendermint/proxy" ctypes "github.com/tendermint/tendermint/rpc/core/types" @@ -23,7 +23,7 @@ import ( "github.com/tendermint/tendermint/types" ) -var config *nm.Config +var config *cfg.Config const tmLogLevel = "error" @@ -53,19 +53,19 @@ func makeAddrs() (string, string, string) { } // GetConfig returns a config for the test cases as a singleton -func GetConfig() *nm.Config { +func GetConfig() *cfg.Config { if config == nil { pathname := makePathname() - viperConfig := tendermint_test.ResetConfig(pathname) - // Shut up the logging - logger.SetLogLevel(tmLogLevel) + config = cfg.ResetTestRoot(pathname) + // and we use random ports to run in parallel tm, rpc, grpc := makeAddrs() - viperConfig.Set("p2p.laddr", tm) - viperConfig.Set("rpc_laddr", rpc) - viperConfig.Set("grpc_laddr", grpc) + config.P2P.ListenAddress = tm + config.RPCListenAddress = rpc + config.GRPCListenAddress = grpc - config = nm.ConfigFromViper(viperConfig) + // Shut up the logging + logger.SetLogLevel(tmLogLevel) } return config } @@ -108,7 +108,7 @@ func StartTendermint(app abci.Application) *nm.Node { func NewTendermint(app abci.Application) *nm.Node { // Create & start node config := GetConfig() - privValidatorFile := config.PrivValidatorFile + privValidatorFile := config.PrivValidatorFile() privValidator := types.LoadOrGenPrivValidator(privValidatorFile) papp := proxy.NewLocalClientCreator(app) node := nm.NewNode(config, privValidator, papp) diff --git a/state/state_test.go b/state/state_test.go index 97df5cab4..10bf07938 100644 --- a/state/state_test.go +++ b/state/state_test.go @@ -8,26 +8,15 @@ import ( abci "github.com/tendermint/abci/types" "github.com/tendermint/go-crypto" cfg "github.com/tendermint/tendermint/config" - "github.com/tendermint/tendermint/config/tendermint_test" dbm "github.com/tendermint/tmlibs/db" ) -func ResetConfig(name string) *cfg.Config { - viperConfig := tendermint_test.ResetConfig(name) - config := new(struct { - cfg.Config `mapstructure:",squash"` - }) - if err := viperConfig.Unmarshal(config); err != nil { - panic(err) - } - return &config.Config -} - func TestStateCopyEquals(t *testing.T) { - config := ResetConfig("state_") + config := cfg.ResetTestRoot("state_") + // Get State db - stateDB := dbm.NewDB("state", config.DBBackend, config.DBDir) - state := GetState(stateDB, config.GenesisFile) + stateDB := dbm.NewDB("state", config.DBBackend, config.DBDir()) + state := GetState(stateDB, config.GenesisFile()) stateCopy := state.Copy() @@ -43,10 +32,10 @@ func TestStateCopyEquals(t *testing.T) { } func TestStateSaveLoad(t *testing.T) { - config := ResetConfig("state_") + config := cfg.ResetTestRoot("state_") // Get State db - stateDB := dbm.NewDB("state", config.DBBackend, config.DBDir) - state := GetState(stateDB, config.GenesisFile) + stateDB := dbm.NewDB("state", config.DBBackend, config.DBDir()) + state := GetState(stateDB, config.GenesisFile()) state.LastBlockHeight += 1 state.Save() @@ -60,9 +49,9 @@ func TestStateSaveLoad(t *testing.T) { func TestABCIResponsesSaveLoad(t *testing.T) { assert := assert.New(t) - config := ResetConfig("state_") - stateDB := dbm.NewDB("state", config.DBBackend, config.DBDir) - state := GetState(stateDB, config.GenesisFile) + config := cfg.ResetTestRoot("state_") + stateDB := dbm.NewDB("state", config.DBBackend, config.DBDir()) + state := GetState(stateDB, config.GenesisFile()) state.LastBlockHeight += 1 From 75989342b07c4b4a0c3df163889bd53dc67c16ae Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Thu, 4 May 2017 23:03:42 -0400 Subject: [PATCH 270/309] fixes from rebase --- rpc/core/routes.go | 6 ------ rpc/lib/server/handlers.go | 2 +- rpc/test/client_test.go | 7 ++++--- 3 files changed, 5 insertions(+), 10 deletions(-) diff --git a/rpc/core/routes.go b/rpc/core/routes.go index 5e045d49d..734d1ee77 100644 --- a/rpc/core/routes.go +++ b/rpc/core/routes.go @@ -2,12 +2,6 @@ package core import ( rpc "github.com/tendermint/tendermint/rpc/lib/server" - - data "github.com/tendermint/go-wire/data" - ctypes "github.com/tendermint/tendermint/rpc/core/types" - rpc "github.com/tendermint/tendermint/rpc/lib/server" - "github.com/tendermint/tendermint/rpc/lib/types" - "github.com/tendermint/tendermint/types" ) // TODO: better system than "unsafe" prefix diff --git a/rpc/lib/server/handlers.go b/rpc/lib/server/handlers.go index f780fba44..5e6252d43 100644 --- a/rpc/lib/server/handlers.go +++ b/rpc/lib/server/handlers.go @@ -145,7 +145,7 @@ func mapParamsToArgs(rpcFunc *RPCFunc, params map[string]*json.RawMessage, argsO for i, argName := range rpcFunc.argNames { argType := rpcFunc.args[i+argsOffset] - if p, ok := params[argName]; ok && len(*p) > 0 { + if p, ok := params[argName]; ok && p != nil && len(*p) > 0 { val := reflect.New(argType) err := json.Unmarshal(*p, val.Interface()) if err != nil { diff --git a/rpc/test/client_test.go b/rpc/test/client_test.go index ecc2f36b9..b7df67841 100644 --- a/rpc/test/client_test.go +++ b/rpc/test/client_test.go @@ -43,7 +43,7 @@ func testStatus(t *testing.T, client rpc.HTTPClient) { result := new(ctypes.ResultStatus) _, err := client.Call("status", map[string]interface{}{}, result) require.Nil(t, err) - assert.Equal(t, moniker, status.NodeInfo.Moniker) + assert.Equal(t, moniker, result.NodeInfo.Moniker) } //-------------------------------------------------------------------------------- @@ -158,8 +158,9 @@ func TestURITx(t *testing.T) { testTx(t, GetURIClient(), true) core.SetTxIndexer(&null.TxIndex{}) - testTx(t, GetJSONClient(), false) - core.SetTxIndexer(node.ConsensusState().GetState().TxIndexer) + defer core.SetTxIndexer(node.ConsensusState().GetState().TxIndexer) + + testTx(t, GetURIClient(), false) } func TestJSONTx(t *testing.T) { From 8c3823545d0f86ca48dc323246a4ad710655b045 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 5 May 2017 00:39:57 -0400 Subject: [PATCH 271/309] update glide --- glide.lock | 50 ++++++++++++++++++++++++++------------------------ glide.yaml | 2 +- 2 files changed, 27 insertions(+), 25 deletions(-) diff --git a/glide.lock b/glide.lock index 0f1426f3d..7cb29b749 100644 --- a/glide.lock +++ b/glide.lock @@ -1,12 +1,12 @@ -hash: 1bdb98b332fc88df3659092ce571b74851f54465c11d91e273a10098dd4d8011 -updated: 2017-05-04T19:50:25.718540841+02:00 +hash: c715f30f5021a73c8d35229ad5bb7473bd5b18a24707b3211f264658c44ef63f +updated: 2017-05-05T00:50:11.28834974-04:00 imports: - name: github.com/btcsuite/btcd version: 4b348c1d33373d672edd83fc576892d0e46686d2 subpackages: - btcec - name: github.com/davecgh/go-spew - version: 6d212800a42e8ab5c146b8ace3490ee17e5225f9 + version: 04cdfd42973bb9c8589fd6a731800cf222fde1a9 subpackages: - spew - name: github.com/ebuchman/fail-test @@ -14,22 +14,22 @@ imports: - name: github.com/fsnotify/fsnotify version: 4da3e2cfbabc9f751898f250b49f2439785783a1 - name: github.com/go-stack/stack - version: 100eb0c0a9c5b306ca2fb4f165df21d80ada4b82 + version: 7a2f19628aabfe68f0766b59e74d6315f8347d22 - name: github.com/gogo/protobuf - version: 100ba4e885062801d56799d78530b73b178a78f3 + version: 30433562cfbf487fe1df7cd26c7bab168d2f14d0 subpackages: - proto - name: github.com/golang/protobuf - version: 2bba0603135d7d7f5cb73b2125beeda19c09f4ef + version: 18c9bb3261723cd5401db4d0c9fbc5c3b6c70fe8 subpackages: - proto - ptypes/any - name: github.com/golang/snappy version: 553a641470496b2327abcac10b36396bd98e45c9 - name: github.com/gorilla/websocket - version: 3ab3a8b8831546bd18fd182c20687ca853b2bb13 + version: a91eba7f97777409bc2c443f5534d41dd20c5720 - name: github.com/hashicorp/hcl - version: 630949a3c5fa3c613328e1b8256052cbc2327c9b + version: a4b07c25de5ff55ad3b8936cea69a79a3d95a855 subpackages: - hcl/ast - hcl/parser @@ -50,13 +50,13 @@ imports: - name: github.com/mattn/go-isatty version: fc9e8d8ef48496124e79ae0df75490096eccf6fe - name: github.com/mitchellh/mapstructure - version: 53818660ed4955e899c0bcafa97299a388bd7c8e + version: cc8532a8e9a55ea36402aa21efdf403a60d34096 - name: github.com/pelletier/go-buffruneio version: c37440a7cf42ac63b919c752ca73a85067e05992 - name: github.com/pelletier/go-toml - version: 13d49d4606eb801b8f01ae542b4afc4c6ee3d84a + version: 97253b98df84f9eef872866d079e74b8265150f1 - name: github.com/pkg/errors - version: bfd5150e4e41705ded2129ec33379de1cb90b513 + version: c605e284fe17294bda444b34710735b29d1a9d90 - name: github.com/pmezard/go-difflib version: d8ed2627bdf02c080bf22230dbb337003b7aba2d subpackages: @@ -68,15 +68,15 @@ imports: - name: github.com/spf13/cast version: acbeb36b902d72a7a4c18e8f3241075e7ab763e4 - name: github.com/spf13/cobra - version: 10f6b9d7e1631a54ad07c5c0fb71c28a1abfd3c2 + version: 8f0203be891287870100e4af46262cdf4a4261d1 - name: github.com/spf13/jwalterweatherman version: fa7ca7e836cf3a8bb4ebf799f472c12d7e903d66 - name: github.com/spf13/pflag - version: 2300d0f8576fe575f71aaa5b9bbe4e1b0dc2eb51 + version: c990990ab4981d84da820b7b00c85139ca150b5f - name: github.com/spf13/viper - version: 5d46e70da8c0b6f812e0b170b7a985753b5c63cb + version: 0967fc9aceab2ce9da34061253ac10fb99bba5b2 - name: github.com/stretchr/testify - version: 69483b4bd14f5845b5a1e55bca19e954e827f1d0 + version: 4d4bfba8f1d1027c4fdbe371823030df51419987 subpackages: - assert - require @@ -109,24 +109,25 @@ imports: - edwards25519 - extra25519 - name: github.com/tendermint/go-crypto - version: 197a2b270fd94ee03824b158e738fce62862d0b8 + version: 524ba917a3a1636f21ab2c0bf76b6526903ab879 - name: github.com/tendermint/go-wire version: b53add0b622662731985485f3a19be7f684660b8 subpackages: - data + - data/base58 - name: github.com/tendermint/log15 - version: ae0f3d6450da9eac7074b439c8e1c3cabf0d5ce6 + version: f91285dece9f4875421b481da3e613d83d44f29b subpackages: - term - name: github.com/tendermint/merkleeyes - version: 0fab643ccac1a3f93b90e0e2682a5d1b9d17f8c4 + version: d0aa363fd4e015e509038c3a0ec493bc62ee0b8a subpackages: - app - client - iavl - testutil - name: github.com/tendermint/tmlibs - version: df250b69416a35a943a6e2a92118667e9ef031d4 + version: 3585a542a0e07d0e9d396b2f809c2826c8536437 subpackages: - autofile - cli @@ -139,7 +140,7 @@ imports: - merkle - test - name: golang.org/x/crypto - version: 96846453c37f0876340a66a47f3f75b1f3a6cd2d + version: 5a033cc77e57eca05bdb50522851d29e03569cbe subpackages: - curve25519 - nacl/box @@ -150,7 +151,7 @@ imports: - ripemd160 - salsa20/salsa - name: golang.org/x/net - version: c8c74377599bd978aee1cf3b9b63a8634051cec2 + version: feeb485667d1fdabe727840fe00adc22431bc86e subpackages: - context - http2 @@ -160,11 +161,11 @@ imports: - lex/httplex - trace - name: golang.org/x/sys - version: ea9bcade75cb975a0b9738936568ab388b845617 + version: 9ccfe848b9db8435a24c424abbc07a921adf1df5 subpackages: - unix - name: golang.org/x/text - version: 19e3104b43db45fca0303f489a9536087b184802 + version: 470f45bf29f4147d6fbd7dfd0a02a848e49f5bf4 subpackages: - secure/bidirule - transform @@ -175,10 +176,11 @@ imports: subpackages: - googleapis/rpc/status - name: google.golang.org/grpc - version: 6914ab1e338c92da4218a23d27fcd03d0ad78d46 + version: 844f573616520565fdc6fb4db242321b5456fd6d subpackages: - codes - credentials + - grpclb/grpc_lb_v1 - grpclog - internal - keepalive diff --git a/glide.yaml b/glide.yaml index 238b4ec0c..c777d5832 100644 --- a/glide.yaml +++ b/glide.yaml @@ -28,7 +28,7 @@ import: - data - package: github.com/tendermint/log15 - package: github.com/tendermint/tmlibs - version: develop + version: cli subpackages: - autofile - cli From fb9d3842e4f460115bbdb261e5bb1c9b8c675cb8 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 5 May 2017 01:28:43 -0400 Subject: [PATCH 272/309] test: p2p.seeds and p2p.pex --- test/p2p/README.md | 2 +- test/p2p/data/core/init.sh | 2 +- test/p2p/fast_sync/test_peer.sh | 2 +- test/p2p/local_testnet_start.sh | 4 ++-- test/p2p/pex/test_addrbook.sh | 4 ++-- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/test/p2p/README.md b/test/p2p/README.md index 5836fc61e..e2a577cfa 100644 --- a/test/p2p/README.md +++ b/test/p2p/README.md @@ -38,7 +38,7 @@ for i in $(seq 1 4); do --name local_testnet_$i \ --entrypoint tendermint \ -e TMHOME=/go/src/github.com/tendermint/tendermint/test/p2p/data/mach$i/core \ - tendermint_tester node --seeds 172.57.0.101:46656,172.57.0.102:46656,172.57.0.103:46656,172.57.0.104:46656 --proxy_app=dummy + tendermint_tester node --p2p.seeds 172.57.0.101:46656,172.57.0.102:46656,172.57.0.103:46656,172.57.0.104:46656 --proxy_app=dummy done ``` diff --git a/test/p2p/data/core/init.sh b/test/p2p/data/core/init.sh index 470ed37e3..4a1575aab 100755 --- a/test/p2p/data/core/init.sh +++ b/test/p2p/data/core/init.sh @@ -17,4 +17,4 @@ git fetch origin $BRANCH git checkout $BRANCH make install -tendermint node --seeds="$TMSEEDS" --moniker="$TMNAME" --proxy_app="$PROXYAPP" \ No newline at end of file +tendermint node --p2p.seeds="$TMSEEDS" --moniker="$TMNAME" --proxy_app="$PROXYAPP" diff --git a/test/p2p/fast_sync/test_peer.sh b/test/p2p/fast_sync/test_peer.sh index 615ae9e06..8cfab1c13 100644 --- a/test/p2p/fast_sync/test_peer.sh +++ b/test/p2p/fast_sync/test_peer.sh @@ -27,7 +27,7 @@ SEEDS="$(test/p2p/ip.sh 1):46656" for j in `seq 2 $N`; do SEEDS="$SEEDS,$(test/p2p/ip.sh $j):46656" done -bash test/p2p/peer.sh $DOCKER_IMAGE $NETWORK_NAME $ID $PROXY_APP "--seeds $SEEDS --pex" +bash test/p2p/peer.sh $DOCKER_IMAGE $NETWORK_NAME $ID $PROXY_APP "--p2p.seeds $SEEDS --p2p.pex" # wait for peer to sync and check the app hash bash test/p2p/client.sh $DOCKER_IMAGE $NETWORK_NAME fs_$ID "test/p2p/fast_sync/check_peer.sh $ID" diff --git a/test/p2p/local_testnet_start.sh b/test/p2p/local_testnet_start.sh index b7cfb959e..301098fc2 100644 --- a/test/p2p/local_testnet_start.sh +++ b/test/p2p/local_testnet_start.sh @@ -10,7 +10,7 @@ set +u SEEDS=$5 if [[ "$SEEDS" != "" ]]; then echo "Seeds: $SEEDS" - SEEDS="--seeds $SEEDS" + SEEDS="--p2p.seeds $SEEDS" fi set -u @@ -20,5 +20,5 @@ cd "$GOPATH/src/github.com/tendermint/tendermint" docker network create --driver bridge --subnet 172.57.0.0/16 "$NETWORK_NAME" for i in $(seq 1 "$N"); do - bash test/p2p/peer.sh "$DOCKER_IMAGE" "$NETWORK_NAME" "$i" "$APP_PROXY" "$SEEDS --pex" + bash test/p2p/peer.sh "$DOCKER_IMAGE" "$NETWORK_NAME" "$i" "$APP_PROXY" "$SEEDS --p2p.pex" done diff --git a/test/p2p/pex/test_addrbook.sh b/test/p2p/pex/test_addrbook.sh index d63096c8d..f724d3dd4 100644 --- a/test/p2p/pex/test_addrbook.sh +++ b/test/p2p/pex/test_addrbook.sh @@ -23,7 +23,7 @@ docker rm -vf "local_testnet_$ID" set -e # NOTE that we do not provide seeds -bash test/p2p/peer.sh "$DOCKER_IMAGE" "$NETWORK_NAME" "$ID" "$PROXY_APP" "--pex" +bash test/p2p/peer.sh "$DOCKER_IMAGE" "$NETWORK_NAME" "$ID" "$PROXY_APP" "--p2p.pex" docker cp "/tmp/addrbook.json" "local_testnet_$ID:/go/src/github.com/tendermint/tendermint/test/p2p/data/mach1/core/addrbook.json" echo "with the following addrbook:" cat /tmp/addrbook.json @@ -47,7 +47,7 @@ docker rm -vf "local_testnet_$ID" set -e # NOTE that we do not provide seeds -bash test/p2p/peer.sh "$DOCKER_IMAGE" "$NETWORK_NAME" "$ID" "$PROXY_APP" "--pex" +bash test/p2p/peer.sh "$DOCKER_IMAGE" "$NETWORK_NAME" "$ID" "$PROXY_APP" "--p2p.pex" # if the client runs forever, it means other peers have removed us from their books (which should not happen) bash test/p2p/client.sh "$DOCKER_IMAGE" "$NETWORK_NAME" "$CLIENT_NAME" "test/p2p/pex/check_peer.sh $ID $N" From 8a0466d81d36b4272655080780dcc05e46350230 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 5 May 2017 02:04:24 -0400 Subject: [PATCH 273/309] config: pex_reactor -> pex --- config/config.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config/config.go b/config/config.go index 2c78524b5..1da45abab 100644 --- a/config/config.go +++ b/config/config.go @@ -150,7 +150,7 @@ type P2PConfig struct { SkipUPNP bool `mapstructure:"skip_upnp"` AddrBook string `mapstructure:"addr_book_file"` AddrBookStrict bool `mapstructure:"addr_book_strict"` - PexReactor bool `mapstructure:"pex_reactor"` + PexReactor bool `mapstructure:"pex"` MaxNumPeers int `mapstructure:"max_num_peers"` } From dd1f5a22682fab2e2630e1945ac4b1b12d6945e2 Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Fri, 5 May 2017 15:30:39 +0200 Subject: [PATCH 274/309] Test config parsing in root command --- cmd/tendermint/commands/root_test.go | 99 ++++++++++++++++++++++++++++ glide.lock | 2 +- 2 files changed, 100 insertions(+), 1 deletion(-) create mode 100644 cmd/tendermint/commands/root_test.go diff --git a/cmd/tendermint/commands/root_test.go b/cmd/tendermint/commands/root_test.go new file mode 100644 index 000000000..f776a0248 --- /dev/null +++ b/cmd/tendermint/commands/root_test.go @@ -0,0 +1,99 @@ +package commands + +import ( + "os" + "strconv" + + "github.com/spf13/cobra" + "github.com/spf13/viper" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + cfg "github.com/tendermint/tendermint/config" + "github.com/tendermint/tmlibs/cli" + + "testing" +) + +var ( + defaultRoot = os.ExpandEnv("$HOME/.some/test/dir") +) + +const ( + rootName = "root" +) + +// isolate provides a clean setup and returns a copy of RootCmd you can +// modify in the test cases +func isolate(cmds ...*cobra.Command) cli.Executable { + viper.Reset() + config = cfg.DefaultConfig() + r := &cobra.Command{ + Use: rootName, + PersistentPreRunE: RootCmd.PersistentPreRunE, + } + r.AddCommand(cmds...) + wr := cli.PrepareBaseCmd(r, "TM", defaultRoot) + return wr +} + +func TestRootConfig(t *testing.T) { + assert, require := assert.New(t), require.New(t) + + // we pre-create a config file we can refer to in the rest of + // the test cases. + cvals := map[string]string{ + "moniker": "monkey", + "fast_sync": "false", + } + // proper types of the above settings + cfast := false + conf, err := cli.WriteDemoConfig(cvals) + require.Nil(err) + + defaults := cfg.DefaultConfig() + dmax := defaults.P2P.MaxNumPeers + + cases := []struct { + args []string + env map[string]string + root string + moniker string + fastSync bool + maxPeer int + }{ + {nil, nil, defaultRoot, defaults.Moniker, defaults.FastSync, dmax}, + // try multiple ways of setting root (two flags, cli vs. env) + {[]string{"--home", conf}, nil, conf, cvals["moniker"], cfast, dmax}, + {nil, map[string]string{"TMROOT": conf}, conf, cvals["moniker"], cfast, dmax}, + // check setting p2p subflags two different ways + {[]string{"--p2p.max_num_peers", "420"}, nil, defaultRoot, defaults.Moniker, defaults.FastSync, 420}, + {nil, map[string]string{"TM_P2P_MAX_NUM_PEERS": "17"}, defaultRoot, defaults.Moniker, defaults.FastSync, 17}, + // try to set env that have no flags attached... + {[]string{"--home", conf}, map[string]string{"TM_MONIKER": "funny"}, conf, "funny", cfast, dmax}, + } + + for idx, tc := range cases { + i := strconv.Itoa(idx) + // test command that does nothing, except trigger unmarshalling in root + noop := &cobra.Command{ + Use: "noop", + RunE: func(cmd *cobra.Command, args []string) error { + return nil + }, + } + noop.Flags().Int("p2p.max_num_peers", defaults.P2P.MaxNumPeers, "") + cmd := isolate(noop) + + args := append([]string{rootName, noop.Use}, tc.args...) + err := cli.RunWithArgs(cmd, args, tc.env) + require.Nil(err, i) + assert.Equal(tc.root, config.RootDir, i) + assert.Equal(tc.root, config.P2P.RootDir, i) + assert.Equal(tc.root, config.Consensus.RootDir, i) + assert.Equal(tc.root, config.Mempool.RootDir, i) + assert.Equal(tc.moniker, config.Moniker, i) + assert.Equal(tc.fastSync, config.FastSync, i) + assert.Equal(tc.maxPeer, config.P2P.MaxNumPeers, i) + } + +} diff --git a/glide.lock b/glide.lock index 7cb29b749..27b469202 100644 --- a/glide.lock +++ b/glide.lock @@ -127,7 +127,7 @@ imports: - iavl - testutil - name: github.com/tendermint/tmlibs - version: 3585a542a0e07d0e9d396b2f809c2826c8536437 + version: 2f02ed18e9b706467c9474d024a25a0b7a9c0e97 subpackages: - autofile - cli From 2a9e89b34f7b686a9b9bc2d9201a2d78f1025934 Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Fri, 5 May 2017 15:50:23 +0200 Subject: [PATCH 275/309] Add basic tests on config, mainly to raise test coverage --- config/config_test.go | 28 +++++++++++++++++++++ config/toml_test.go | 57 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 config/config_test.go create mode 100644 config/toml_test.go diff --git a/config/config_test.go b/config/config_test.go new file mode 100644 index 000000000..6379960fa --- /dev/null +++ b/config/config_test.go @@ -0,0 +1,28 @@ +package config + +import ( + "testing" + + "github.com/stretchr/testify/assert" +) + +func TestDefaultConfig(t *testing.T) { + assert := assert.New(t) + + // set up some defaults + cfg := DefaultConfig() + assert.NotNil(cfg.P2P) + assert.NotNil(cfg.Mempool) + assert.NotNil(cfg.Consensus) + + // check the root dir stuff... + cfg.SetRoot("/foo") + cfg.Genesis = "bar" + cfg.DBPath = "/opt/data" + cfg.Mempool.WalPath = "wal/mem/" + + assert.Equal("/foo/bar", cfg.GenesisFile()) + assert.Equal("/opt/data", cfg.DBDir()) + assert.Equal("/foo/wal/mem", cfg.Mempool.WalDir()) + +} diff --git a/config/toml_test.go b/config/toml_test.go new file mode 100644 index 000000000..d8f372aee --- /dev/null +++ b/config/toml_test.go @@ -0,0 +1,57 @@ +package config + +import ( + "io/ioutil" + "os" + "path/filepath" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func ensureFiles(t *testing.T, rootDir string, files ...string) { + for _, f := range files { + p := rootify(rootDir, f) + _, err := os.Stat(p) + assert.Nil(t, err, p) + } +} + +func TestEnsureRoot(t *testing.T) { + assert, require := assert.New(t), require.New(t) + + // setup temp dir for test + tmpDir, err := ioutil.TempDir("", "config-test") + require.Nil(err) + defer os.RemoveAll(tmpDir) + + // create root dir + EnsureRoot(tmpDir) + + // make sure config is set properly + data, err := ioutil.ReadFile(filepath.Join(tmpDir, "config.toml")) + require.Nil(err) + assert.Equal([]byte(defaultConfig("anonymous")), data) + + ensureFiles(t, tmpDir, "data") +} + +func TestEnsureTestRoot(t *testing.T) { + assert, require := assert.New(t), require.New(t) + + testName := "ensureTestRoot" + + // create root dir + cfg := ResetTestRoot(testName) + rootDir := cfg.RootDir + + // make sure config is set properly + data, err := ioutil.ReadFile(filepath.Join(rootDir, "config.toml")) + require.Nil(err) + assert.Equal([]byte(testConfig("anonymous")), data) + + // TODO: make sure the cfg returned and testconfig are the same! + + ensureFiles(t, rootDir, "data", "genesis.json", "priv_validator.json") +} From edd7263f063556fc631b85ba9693648e0d8f68da Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 5 May 2017 12:25:10 -0400 Subject: [PATCH 276/309] fixes from review --- cmd/tendermint/commands/root.go | 3 +-- node/node.go | 5 ----- 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/cmd/tendermint/commands/root.go b/cmd/tendermint/commands/root.go index fd369d934..7ea5eacfb 100644 --- a/cmd/tendermint/commands/root.go +++ b/cmd/tendermint/commands/root.go @@ -9,12 +9,11 @@ import ( ) var ( - config *cfg.Config + config = cfg.DefaultConfig() log = logger.New("module", "main") ) func init() { - config = cfg.DefaultConfig() RootCmd.PersistentFlags().String("log_level", config.LogLevel, "Log level") } diff --git a/node/node.go b/node/node.go index 6896bc4f1..04a6f3cdf 100644 --- a/node/node.go +++ b/node/node.go @@ -74,11 +74,6 @@ func NewNode(config *cfg.Config, privValidator *types.PrivValidator, clientCreat stateDB := dbm.NewDB("state", config.DBBackend, config.DBDir()) state := sm.GetState(stateDB, config.GenesisFile()) - // add the chainid and number of validators to the global config - // TODO: Set ChainID. eg: - // config.Consensus.SetChainID(state.ChainID) // ... - // but actually consensus doesnt need it since the cs has the state ... - // Create the proxyApp, which manages connections (consensus, mempool, query) // and sync tendermint and the app by replaying any necessary blocks proxyApp := proxy.NewAppConns(clientCreator, consensus.NewHandshaker(state, blockStore)) From 57527f9f67d8ddb1e79b0d8c163d719641a40fe4 Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Fri, 5 May 2017 18:39:19 +0200 Subject: [PATCH 277/309] One silly tests passes on osx, fails on linux... comment out so i can develop --- p2p/netaddress_test.go | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/p2p/netaddress_test.go b/p2p/netaddress_test.go index db871fdec..8c60da256 100644 --- a/p2p/netaddress_test.go +++ b/p2p/netaddress_test.go @@ -23,14 +23,14 @@ func TestNewNetAddress(t *testing.T) { } func TestNewNetAddressString(t *testing.T) { - assert, require := assert.New(t), require.New(t) + assert := assert.New(t) tests := []struct { addr string correct bool }{ {"127.0.0.1:8080", true}, - {"127.0.0:8080", false}, + // {"127.0.0:8080", false}, {"a", false}, {"127.0.0.1:a", false}, {"a:8080", false}, @@ -41,10 +41,11 @@ func TestNewNetAddressString(t *testing.T) { for _, t := range tests { addr, err := NewNetAddressString(t.addr) if t.correct { - require.Nil(err) - assert.Equal(t.addr, addr.String()) + if assert.Nil(err, t.addr) { + assert.Equal(t.addr, addr.String()) + } } else { - require.NotNil(err) + assert.NotNil(err, t.addr) } } } From d2ae7e164af0bb9eb3dbeec3e0b54bbee440f537 Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Fri, 5 May 2017 19:46:32 +0200 Subject: [PATCH 278/309] Make testify a testImport for consistency --- glide.yaml | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/glide.yaml b/glide.yaml index c777d5832..9803f5b91 100644 --- a/glide.yaml +++ b/glide.yaml @@ -11,9 +11,6 @@ import: - package: github.com/pkg/errors - package: github.com/spf13/cobra - package: github.com/spf13/viper -- package: github.com/stretchr/testify - subpackages: - - require - package: github.com/tendermint/abci version: develop subpackages: @@ -49,6 +46,11 @@ import: - context - package: google.golang.org/grpc testImport: +- package: github.com/stretchr/testify + version: ^1.1.4 + subpackages: + - assert + - require - package: github.com/tendermint/merkleeyes version: develop subpackages: From 6312eb91bee05171d97cecd509be115b2c6b6477 Mon Sep 17 00:00:00 2001 From: Adrian Brink Date: Sat, 6 May 2017 12:37:48 +0200 Subject: [PATCH 279/309] Change "make build" to set GitCommit variable As described above. --- Makefile | 3 ++- version/version.go | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index e11152fce..0f8268a49 100644 --- a/Makefile +++ b/Makefile @@ -11,7 +11,8 @@ install: get_vendor_deps @go install ./cmd/tendermint build: - go build -o build/tendermint ./cmd/tendermint + go build --ldflags '-extldflags "-static"' \ + --ldflags "-X github.com/tendermint/tendermint/version.GitCommit=`git rev-parse HEAD`" -o build/tendermint ./cmd/tendermint/ build_race: go build -race -o build/tendermint ./cmd/tendermint diff --git a/version/version.go b/version/version.go index fab2a05b7..ed7e46d55 100644 --- a/version/version.go +++ b/version/version.go @@ -4,4 +4,4 @@ const Maj = "0" const Min = "10" const Fix = "0" -const Version = "0.10.0" +const Version = Maj + "." + Min + "." + Fix From 8c91014cd8e832326b26c54b73d47dcb944139f0 Mon Sep 17 00:00:00 2001 From: Adrian Brink Date: Tue, 9 May 2017 11:37:59 +0200 Subject: [PATCH 280/309] Add git commit hash to version. --- Makefile | 2 +- version/version.go | 20 +++++++++++++++++++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 0f8268a49..2c38119e4 100644 --- a/Makefile +++ b/Makefile @@ -8,7 +8,7 @@ TMHOME = $${TMHOME:-$$HOME/.tendermint} all: install test install: get_vendor_deps - @go install ./cmd/tendermint + @go install --ldflags '-extldflags "-static"' ./cmd/tendermint build: go build --ldflags '-extldflags "-static"' \ diff --git a/version/version.go b/version/version.go index ed7e46d55..8056ac708 100644 --- a/version/version.go +++ b/version/version.go @@ -1,7 +1,25 @@ package version +import ( + "fmt" +) + const Maj = "0" const Min = "10" const Fix = "0" -const Version = Maj + "." + Min + "." + Fix +var ( + // The full version string + Version = "0.10.0" + + // GitCommit is set with --ldflags "-X main.gitCommit=$(git rev-parse HEAD)" + GitCommit string +) + +func init() { + Version = fmt.Sprintf("%d.%d.%d", Maj, Min, Fix) + + if GitCommit != "" { + Version += "-" + GitCommit[:8] + } +} From cd3c3c3bad4092f80e222c72678e5428c290dda9 Mon Sep 17 00:00:00 2001 From: Adrian Brink Date: Tue, 9 May 2017 11:39:46 +0200 Subject: [PATCH 281/309] Modify makefile --- Makefile | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/Makefile b/Makefile index 2c38119e4..7848e4785 100644 --- a/Makefile +++ b/Makefile @@ -8,10 +8,11 @@ TMHOME = $${TMHOME:-$$HOME/.tendermint} all: install test install: get_vendor_deps - @go install --ldflags '-extldflags "-static"' ./cmd/tendermint + @go install --ldflags '-extldflags "-static"' \ + --ldflags "-X github.com/tendermint/tendermint/version.GitCommit=`git rev-parse HEAD`" ./cmd/tendermint build: - go build --ldflags '-extldflags "-static"' \ + go build \ --ldflags "-X github.com/tendermint/tendermint/version.GitCommit=`git rev-parse HEAD`" -o build/tendermint ./cmd/tendermint/ build_race: From 538b325150b6bf830142f8c4f51f495c43cb6200 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Fri, 12 May 2017 20:32:10 +0200 Subject: [PATCH 282/309] update arch proposal [ci skip] [circleci skip] --- docs/architecture/adr-001.md | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/docs/architecture/adr-001.md b/docs/architecture/adr-001.md index 4881adf9a..a11a49e14 100644 --- a/docs/architecture/adr-001.md +++ b/docs/architecture/adr-001.md @@ -27,6 +27,8 @@ type Logger interface { Debug(msg string, keyvals ...interface{}) error Info(msg string, keyvals ...interface{}) error Error(msg string, keyvals ...interface{}) error + + With(keyvals ...interface{}) Logger } ``` @@ -53,13 +55,13 @@ Many people say that they like the current output, so let's stick with it. NOTE[04-25|14:45:08] ABCI Replay Blocks module=consensus appHeight=0 storeHeight=0 stateHeight=0 ``` -One minor change: +Couple of minor changes: ``` -NOTE[04-25|14:45:08][consensus] ABCI Replay Blocks appHeight=0 storeHeight=0 stateHeight=0 +I[04-25|14:45:08.322] ABCI Replay Blocks module=consensus appHeight=0 storeHeight=0 stateHeight=0 ``` -I think it makes sense to move `module` to the beginning because every message has it. +Notice the level is encoded using only one char plus milliseconds. Note: there are many other formats out there like [logfmt](https://brandur.org/logfmt). @@ -153,14 +155,14 @@ Important keyvals should go first. Example: ``` correct -NOTE[04-25|14:45:08][consensus] ABCI Replay Blocks instance=1 appHeight=0 storeHeight=0 stateHeight=0 +I[04-25|14:45:08.322] ABCI Replay Blocks module=consensus instance=1 appHeight=0 storeHeight=0 stateHeight=0 ``` not ``` wrong -NOTE[04-25|14:45:08][consensus] ABCI Replay Blocks appHeight=0 storeHeight=0 stateHeight=0 instance=1 +I[04-25|14:45:08.322] ABCI Replay Blocks module=consensus appHeight=0 storeHeight=0 stateHeight=0 instance=1 ``` for that in most cases you'll need to add `instance` field to a logger upon creating, not when u log a particular message: From f8035441951a8d1cbdbc97ba295ea3b85e3c1981 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Tue, 2 May 2017 11:53:32 +0400 Subject: [PATCH 283/309] new logging --- blockchain/log.go | 7 - blockchain/pool.go | 21 ++- blockchain/pool_test.go | 15 +- blockchain/reactor.go | 18 +-- cmd/tendermint/commands/init.go | 4 +- .../commands/reset_priv_validator.go | 19 ++- cmd/tendermint/commands/root.go | 20 ++- cmd/tendermint/commands/run_node.go | 6 +- cmd/tendermint/commands/show_validator.go | 4 +- config/toml.go | 2 +- consensus/byzantine_test.go | 13 +- consensus/common_test.go | 16 +- consensus/height_vote_set.go | 6 +- consensus/log.go | 18 --- consensus/reactor.go | 84 +++++----- consensus/reactor_test.go | 17 +- consensus/replay.go | 48 +++--- consensus/replay_file.go | 6 +- consensus/replay_test.go | 24 +-- consensus/state.go | 124 +++++++------- consensus/state_test.go | 28 ++-- consensus/ticker.go | 12 +- consensus/wal.go | 6 +- glide.lock | 27 +++- glide.yaml | 6 +- mempool/log.go | 18 --- mempool/mempool.go | 26 +-- mempool/mempool_test.go | 2 + mempool/reactor.go | 14 +- node/log.go | 7 - node/node.go | 33 ++-- node/node_test.go | 5 +- p2p/addrbook.go | 48 +++--- p2p/addrbook_test.go | 8 + p2p/connection.go | 42 ++--- p2p/connection_test.go | 9 +- p2p/glide.lock | 153 ++++++++++++++++++ p2p/listener.go | 21 +-- p2p/listener_test.go | 4 +- p2p/log.go | 7 - p2p/peer.go | 8 +- p2p/pex_reactor.go | 22 +-- p2p/pex_reactor_test.go | 13 +- p2p/switch.go | 39 +++-- p2p/switch_test.go | 9 +- proxy/log.go | 7 - proxy/multi_app_conn.go | 2 +- rpc/core/abci.go | 2 +- rpc/core/blocks.go | 5 +- rpc/core/events.go | 4 +- rpc/core/log.go | 7 - rpc/core/mempool.go | 6 +- rpc/core/net.go | 2 +- rpc/core/pipe.go | 7 + rpc/lib/README.md | 3 +- rpc/lib/client/http_client.go | 2 +- rpc/lib/client/log.go | 7 - rpc/lib/client/ws_client.go | 6 +- rpc/lib/rpc_test.go | 11 +- rpc/lib/server/handlers.go | 41 +++-- rpc/lib/server/http_server.go | 17 +- rpc/lib/server/log.go | 7 - rpc/lib/test/main.go | 9 +- rpc/test/helpers.go | 13 +- state/execution.go | 31 ++-- state/execution_test.go | 2 + state/log.go | 7 - state/state.go | 16 +- state/state_test.go | 6 +- types/log.go | 7 - types/priv_validator.go | 13 +- 71 files changed, 742 insertions(+), 537 deletions(-) delete mode 100644 blockchain/log.go delete mode 100644 consensus/log.go delete mode 100644 mempool/log.go delete mode 100644 node/log.go create mode 100644 p2p/glide.lock delete mode 100644 p2p/log.go delete mode 100644 proxy/log.go delete mode 100644 rpc/core/log.go delete mode 100644 rpc/lib/client/log.go delete mode 100644 rpc/lib/server/log.go delete mode 100644 state/log.go delete mode 100644 types/log.go diff --git a/blockchain/log.go b/blockchain/log.go deleted file mode 100644 index 9ffee7295..000000000 --- a/blockchain/log.go +++ /dev/null @@ -1,7 +0,0 @@ -package blockchain - -import ( - "github.com/tendermint/tmlibs/logger" -) - -var log = logger.New("module", "blockchain") diff --git a/blockchain/pool.go b/blockchain/pool.go index 6422ef2dc..24b9210f5 100644 --- a/blockchain/pool.go +++ b/blockchain/pool.go @@ -5,9 +5,10 @@ import ( "sync" "time" + "github.com/tendermint/tendermint/types" . "github.com/tendermint/tmlibs/common" flow "github.com/tendermint/tmlibs/flowrate" - "github.com/tendermint/tendermint/types" + "github.com/tendermint/tmlibs/log" ) const ( @@ -58,7 +59,7 @@ func NewBlockPool(start int, requestsCh chan<- BlockRequest, timeoutsCh chan<- s requestsCh: requestsCh, timeoutsCh: timeoutsCh, } - bp.BaseService = *NewBaseService(log, "BlockPool", bp) + bp.BaseService = *NewBaseService(nil, "BlockPool", bp) return bp } @@ -106,7 +107,7 @@ func (pool *BlockPool) removeTimedoutPeers() { // XXX remove curRate != 0 if curRate != 0 && curRate < minRecvRate { pool.sendTimeout(peer.id) - log.Warn("SendTimeout", "peer", peer.id, "reason", "curRate too low") + pool.Logger.Error("SendTimeout", "peer", peer.id, "reason", "curRate too low") peer.didTimeout = true } } @@ -132,7 +133,7 @@ func (pool *BlockPool) IsCaughtUp() bool { // Need at least 1 peer to be considered caught up. if len(pool.peers) == 0 { - log.Debug("Blockpool has no peers") + pool.Logger.Debug("Blockpool has no peers") return false } @@ -142,7 +143,7 @@ func (pool *BlockPool) IsCaughtUp() bool { } isCaughtUp := (height > 0 || time.Now().Sub(pool.startTime) > 5*time.Second) && (maxPeerHeight == 0 || height >= maxPeerHeight) - log.Notice(Fmt("IsCaughtUp: %v", isCaughtUp), "height", height, "maxPeerHeight", maxPeerHeight) + pool.Logger.Info(Fmt("IsCaughtUp: %v", isCaughtUp), "height", height, "maxPeerHeight", maxPeerHeight) return isCaughtUp } @@ -226,6 +227,7 @@ func (pool *BlockPool) SetPeerHeight(peerID string, height int) { peer.height = height } else { peer = newBPPeer(pool, peerID, height) + peer.setLogger(pool.Logger.With("peer", peerID)) pool.peers[peerID] = peer } } @@ -328,6 +330,8 @@ type bpPeer struct { numPending int32 timeout *time.Timer didTimeout bool + + logger log.Logger } func newBPPeer(pool *BlockPool, peerID string, height int) *bpPeer { @@ -336,10 +340,15 @@ func newBPPeer(pool *BlockPool, peerID string, height int) *bpPeer { id: peerID, height: height, numPending: 0, + logger: log.NewNopLogger(), } return peer } +func (peer *bpPeer) setLogger(l log.Logger) { + peer.logger = l +} + func (peer *bpPeer) resetMonitor() { peer.recvMonitor = flow.New(time.Second, time.Second*40) var initialValue = float64(minRecvRate) * math.E @@ -377,7 +386,7 @@ func (peer *bpPeer) onTimeout() { defer peer.pool.mtx.Unlock() peer.pool.sendTimeout(peer.id) - log.Warn("SendTimeout", "peer", peer.id, "reason", "onTimeout") + peer.logger.Error("SendTimeout", "reason", "onTimeout") peer.didTimeout = true } diff --git a/blockchain/pool_test.go b/blockchain/pool_test.go index a2eb83a38..e8e982644 100644 --- a/blockchain/pool_test.go +++ b/blockchain/pool_test.go @@ -5,8 +5,9 @@ import ( "testing" "time" - . "github.com/tendermint/tmlibs/common" "github.com/tendermint/tendermint/types" + . "github.com/tendermint/tmlibs/common" + "github.com/tendermint/tmlibs/log" ) func init() { @@ -34,6 +35,7 @@ func TestBasic(t *testing.T) { timeoutsCh := make(chan string, 100) requestsCh := make(chan BlockRequest, 100) pool := NewBlockPool(start, requestsCh, timeoutsCh) + pool.SetLogger(log.TestingLogger()) pool.Start() defer pool.Stop() @@ -65,7 +67,7 @@ func TestBasic(t *testing.T) { case peerID := <-timeoutsCh: t.Errorf("timeout: %v", peerID) case request := <-requestsCh: - log.Info("TEST: Pulled new BlockRequest", "request", request) + t.Logf("Pulled new BlockRequest %v", request) if request.Height == 300 { return // Done! } @@ -73,7 +75,7 @@ func TestBasic(t *testing.T) { go func() { block := &types.Block{Header: &types.Header{Height: request.Height}} pool.AddBlock(request.PeerID, block, 123) - log.Info("TEST: Added block", "block", request.Height, "peer", request.PeerID) + t.Logf("Added block from peer %v (height: %v)", request.PeerID, request.Height) }() } } @@ -85,11 +87,12 @@ func TestTimeout(t *testing.T) { timeoutsCh := make(chan string, 100) requestsCh := make(chan BlockRequest, 100) pool := NewBlockPool(start, requestsCh, timeoutsCh) + pool.SetLogger(log.TestingLogger()) pool.Start() defer pool.Stop() for _, peer := range peers { - log.Info("Peer", "id", peer.id) + t.Logf("Peer #%v", peer.id) } // Introduce each peer. @@ -120,7 +123,7 @@ func TestTimeout(t *testing.T) { for { select { case peerID := <-timeoutsCh: - log.Info("Timeout", "peerID", peerID) + t.Logf("Peer #%v timeouted", peerID) if _, ok := timedOut[peerID]; !ok { counter++ if counter == len(peers) { @@ -128,7 +131,7 @@ func TestTimeout(t *testing.T) { } } case request := <-requestsCh: - log.Info("TEST: Pulled new BlockRequest", "request", request) + t.Logf("Pulled new BlockRequest %v", request) } } } diff --git a/blockchain/reactor.go b/blockchain/reactor.go index b39de838d..1c0ef3a7d 100644 --- a/blockchain/reactor.go +++ b/blockchain/reactor.go @@ -6,7 +6,7 @@ import ( "reflect" "time" - "github.com/tendermint/go-wire" + wire "github.com/tendermint/go-wire" "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/proxy" sm "github.com/tendermint/tendermint/state" @@ -78,7 +78,7 @@ func NewBlockchainReactor(state *sm.State, proxyAppConn proxy.AppConnConsensus, requestsCh: requestsCh, timeoutsCh: timeoutsCh, } - bcR.BaseReactor = *p2p.NewBaseReactor(log, "BlockchainReactor", bcR) + bcR.BaseReactor = *p2p.NewBaseReactor("BlockchainReactor", bcR) return bcR } @@ -128,11 +128,11 @@ func (bcR *BlockchainReactor) RemovePeer(peer *p2p.Peer, reason interface{}) { func (bcR *BlockchainReactor) Receive(chID byte, src *p2p.Peer, msgBytes []byte) { _, msg, err := DecodeMessage(msgBytes) if err != nil { - log.Warn("Error decoding message", "error", err) + bcR.Logger.Error("Error decoding message", "error", err) return } - log.Debug("Receive", "src", src, "chID", chID, "msg", msg) + bcR.Logger.Debug("Receive", "src", src, "chID", chID, "msg", msg) switch msg := msg.(type) { case *bcBlockRequestMessage: @@ -160,7 +160,7 @@ func (bcR *BlockchainReactor) Receive(chID byte, src *p2p.Peer, msgBytes []byte) // Got a peer status. Unverified. bcR.pool.SetPeerHeight(src.Key, msg.Height) default: - log.Warn(cmn.Fmt("Unknown message type %v", reflect.TypeOf(msg))) + bcR.Logger.Error(cmn.Fmt("Unknown message type %v", reflect.TypeOf(msg))) } } @@ -200,10 +200,10 @@ FOR_LOOP: case _ = <-switchToConsensusTicker.C: height, numPending, _ := bcR.pool.GetStatus() outbound, inbound, _ := bcR.Switch.NumPeers() - log.Info("Consensus ticker", "numPending", numPending, "total", len(bcR.pool.requesters), + bcR.Logger.Info("Consensus ticker", "numPending", numPending, "total", len(bcR.pool.requesters), "outbound", outbound, "inbound", inbound) if bcR.pool.IsCaughtUp() { - log.Notice("Time to switch to consensus reactor!", "height", height) + bcR.Logger.Info("Time to switch to consensus reactor!", "height", height) bcR.pool.Stop() conR := bcR.Switch.Reactor("CONSENSUS").(consensusReactor) @@ -217,7 +217,7 @@ FOR_LOOP: for i := 0; i < 10; i++ { // See if there are any blocks to sync. first, second := bcR.pool.PeekTwoBlocks() - //log.Info("TrySync peeked", "first", first, "second", second) + //bcR.Logger.Info("TrySync peeked", "first", first, "second", second) if first == nil || second == nil { // We need both to sync the first block. break SYNC_LOOP @@ -231,7 +231,7 @@ FOR_LOOP: err := bcR.state.Validators.VerifyCommit( bcR.state.ChainID, types.BlockID{first.Hash(), firstPartsHeader}, first.Height, second.LastCommit) if err != nil { - log.Info("error in validation", "error", err) + bcR.Logger.Info("error in validation", "error", err) bcR.pool.RedoRequest(first.Height) break SYNC_LOOP } else { diff --git a/cmd/tendermint/commands/init.go b/cmd/tendermint/commands/init.go index ba3b711b3..cd16707cc 100644 --- a/cmd/tendermint/commands/init.go +++ b/cmd/tendermint/commands/init.go @@ -40,8 +40,8 @@ func initFiles(cmd *cobra.Command, args []string) { genDoc.SaveAs(genFile) } - log.Notice("Initialized tendermint", "genesis", config.GenesisFile(), "priv_validator", config.PrivValidatorFile()) + logger.Info("Initialized tendermint", "genesis", config.GenesisFile(), "priv_validator", config.PrivValidatorFile()) } else { - log.Notice("Already initialized", "priv_validator", config.PrivValidatorFile()) + logger.Info("Already initialized", "priv_validator", config.PrivValidatorFile()) } } diff --git a/cmd/tendermint/commands/reset_priv_validator.go b/cmd/tendermint/commands/reset_priv_validator.go index c10f9c56a..fa12be4ea 100644 --- a/cmd/tendermint/commands/reset_priv_validator.go +++ b/cmd/tendermint/commands/reset_priv_validator.go @@ -5,8 +5,8 @@ import ( "github.com/spf13/cobra" - "github.com/tendermint/log15" "github.com/tendermint/tendermint/types" + "github.com/tendermint/tmlibs/log" ) var resetAllCmd = &cobra.Command{ @@ -29,34 +29,33 @@ func init() { // XXX: this is totally unsafe. // it's only suitable for testnets. func resetAll(cmd *cobra.Command, args []string) { - ResetAll(config.DBDir(), config.PrivValidatorFile(), log) + ResetAll(config.DBDir(), config.PrivValidatorFile(), logger) } // XXX: this is totally unsafe. // it's only suitable for testnets. func resetPrivValidator(cmd *cobra.Command, args []string) { - resetPrivValidatorLocal(config.PrivValidatorFile(), log) + resetPrivValidatorLocal(config.PrivValidatorFile(), logger) } // Exported so other CLI tools can use it -func ResetAll(dbDir, privValFile string, l log15.Logger) { - resetPrivValidatorLocal(privValFile, l) +func ResetAll(dbDir, privValFile string, logger log.Logger) { + resetPrivValidatorLocal(privValFile, logger) os.RemoveAll(dbDir) - l.Notice("Removed all data", "dir", dbDir) + logger.Info("Removed all data", "dir", dbDir) } -func resetPrivValidatorLocal(privValFile string, l log15.Logger) { - +func resetPrivValidatorLocal(privValFile string, logger log.Logger) { // Get PrivValidator var privValidator *types.PrivValidator if _, err := os.Stat(privValFile); err == nil { privValidator = types.LoadPrivValidator(privValFile) privValidator.Reset() - l.Notice("Reset PrivValidator", "file", privValFile) + logger.Info("Reset PrivValidator", "file", privValFile) } else { privValidator = types.GenPrivValidator() privValidator.SetFile(privValFile) privValidator.Save() - l.Notice("Generated PrivValidator", "file", privValFile) + logger.Info("Generated PrivValidator", "file", privValFile) } } diff --git a/cmd/tendermint/commands/root.go b/cmd/tendermint/commands/root.go index 7ea5eacfb..23c792658 100644 --- a/cmd/tendermint/commands/root.go +++ b/cmd/tendermint/commands/root.go @@ -1,16 +1,19 @@ package commands import ( + "fmt" + "os" + "github.com/spf13/cobra" "github.com/spf13/viper" cfg "github.com/tendermint/tendermint/config" - "github.com/tendermint/tmlibs/logger" + "github.com/tendermint/tmlibs/log" ) var ( config = cfg.DefaultConfig() - log = logger.New("module", "main") + logger = log.NewTMLogger(log.NewSyncWriter(os.Stdout)).With("module", "main") ) func init() { @@ -24,7 +27,18 @@ var RootCmd = &cobra.Command{ err := viper.Unmarshal(config) config.SetRoot(config.RootDir) cfg.EnsureRoot(config.RootDir) - logger.SetLogLevel(config.LogLevel) + var option log.Option + switch config.LogLevel { + case "info": + option = log.AllowInfo() + case "debug": + option = log.AllowDebug() + case "error": + option = log.AllowError() + default: + return fmt.Errorf("Expected either \"info\", \"debug\" or \"error\" log level, given %v", config.LogLevel) + } + logger = log.NewFilter(logger, option) return err }, } diff --git a/cmd/tendermint/commands/run_node.go b/cmd/tendermint/commands/run_node.go index a2c363dc9..5e38f2b5f 100644 --- a/cmd/tendermint/commands/run_node.go +++ b/cmd/tendermint/commands/run_node.go @@ -58,7 +58,7 @@ func runNode(cmd *cobra.Command, args []string) error { // always available, remove. genDocFile := config.GenesisFile() if !cmn.FileExists(genDocFile) { - log.Notice(cmn.Fmt("Waiting for genesis file %v...", genDocFile)) + logger.Info(cmn.Fmt("Waiting for genesis file %v...", genDocFile)) for { time.Sleep(time.Second) if !cmn.FileExists(genDocFile) { @@ -80,11 +80,11 @@ func runNode(cmd *cobra.Command, args []string) error { } // Create & start node - n := node.NewNodeDefault(config) + n := node.NewNodeDefault(config, logger.With("module", "node")) if _, err := n.Start(); err != nil { return fmt.Errorf("Failed to start node: %v", err) } else { - log.Notice("Started node", "nodeInfo", n.Switch().NodeInfo()) + logger.Info("Started node", "nodeInfo", n.Switch().NodeInfo()) } // Trap signal, run forever. diff --git a/cmd/tendermint/commands/show_validator.go b/cmd/tendermint/commands/show_validator.go index 6f2e2a07e..53a687c6d 100644 --- a/cmd/tendermint/commands/show_validator.go +++ b/cmd/tendermint/commands/show_validator.go @@ -5,7 +5,7 @@ import ( "github.com/spf13/cobra" - data "github.com/tendermint/go-wire/data" + "github.com/tendermint/go-wire/data" "github.com/tendermint/tendermint/types" ) @@ -20,7 +20,7 @@ func init() { } func showValidator(cmd *cobra.Command, args []string) { - privValidator := types.LoadOrGenPrivValidator(config.PrivValidatorFile()) + privValidator := types.LoadOrGenPrivValidator(config.PrivValidatorFile(), logger) pubKeyJSONBytes, _ := data.ToJSON(privValidator.PubKey) fmt.Println(string(pubKeyJSONBytes)) } diff --git a/config/toml.go b/config/toml.go index d07b3281f..272577140 100644 --- a/config/toml.go +++ b/config/toml.go @@ -35,7 +35,7 @@ node_laddr = "tcp://0.0.0.0:46656" seeds = "" fast_sync = true db_backend = "leveldb" -log_level = "notice" +log_level = "info" rpc_laddr = "tcp://0.0.0.0:46657" ` diff --git a/consensus/byzantine_test.go b/consensus/byzantine_test.go index e33c13d47..94bd82dae 100644 --- a/consensus/byzantine_test.go +++ b/consensus/byzantine_test.go @@ -9,6 +9,7 @@ import ( "github.com/tendermint/tendermint/types" . "github.com/tendermint/tmlibs/common" "github.com/tendermint/tmlibs/events" + "github.com/tendermint/tmlibs/log" ) func init() { @@ -32,8 +33,10 @@ func TestByzantine(t *testing.T) { css[0].SetTimeoutTicker(NewTimeoutTicker()) switches := make([]*p2p.Switch, N) + p2pLogger := log.TestingLogger().With("module", "p2p") for i := 0; i < N; i++ { switches[i] = p2p.NewSwitch(config.P2P) + switches[i].SetLogger(p2pLogger) } reactors := make([]p2p.Reactor, N) @@ -53,13 +56,14 @@ func TestByzantine(t *testing.T) { // make byzantine css[i].decideProposal = func(j int) func(int, int) { return func(height, round int) { - byzantineDecideProposalFunc(height, round, css[j], switches[j]) + byzantineDecideProposalFunc(t, height, round, css[j], switches[j]) } }(i) css[i].doPrevote = func(height, round int) {} } eventSwitch := events.NewEventSwitch() + eventSwitch.SetLogger(log.TestingLogger().With("module", "events")) _, err := eventSwitch.Start() if err != nil { t.Fatalf("Failed to start switch: %v", err) @@ -67,6 +71,7 @@ func TestByzantine(t *testing.T) { eventChans[i] = subscribeToEvent(eventSwitch, "tester", types.EventStringNewBlock(), 1) conR := NewConsensusReactor(css[i], true) // so we dont start the consensus states + conR.SetLogger(log.TestingLogger()) conR.SetEventSwitch(eventSwitch) var conRI p2p.Reactor @@ -115,7 +120,7 @@ func TestByzantine(t *testing.T) { case <-eventChans[ind2]: } - log.Notice("A block has been committed. Healing partition") + t.Log("A block has been committed. Healing partition") // connect the partitions p2p.Connect2Switches(switches, ind0, ind1) @@ -153,7 +158,7 @@ func TestByzantine(t *testing.T) { //------------------------------- // byzantine consensus functions -func byzantineDecideProposalFunc(height, round int, cs *ConsensusState, sw *p2p.Switch) { +func byzantineDecideProposalFunc(t *testing.T, height, round int, cs *ConsensusState, sw *p2p.Switch) { // byzantine user should create two proposals and try to split the vote. // Avoid sending on internalMsgQueue and running consensus state. @@ -174,7 +179,7 @@ func byzantineDecideProposalFunc(height, round int, cs *ConsensusState, sw *p2p. // broadcast conflicting proposals/block parts to peers peers := sw.Peers().List() - log.Notice("Byzantine: broadcasting conflicting proposals", "peers", len(peers)) + t.Logf("Byzantine: broadcasting conflicting proposals to %d peers", len(peers)) for i, peer := range peers { if i < len(peers)/2 { go sendProposalAndParts(height, round, cs, peer, proposal1, block1Hash, blockParts1) diff --git a/consensus/common_test.go b/consensus/common_test.go index 463b748f8..2872397e4 100644 --- a/consensus/common_test.go +++ b/consensus/common_test.go @@ -21,6 +21,7 @@ import ( "github.com/tendermint/tendermint/types" . "github.com/tendermint/tmlibs/common" dbm "github.com/tendermint/tmlibs/db" + "github.com/tendermint/tmlibs/log" "github.com/tendermint/abci/example/counter" "github.com/tendermint/abci/example/dummy" @@ -249,12 +250,15 @@ func newConsensusStateWithConfig(thisConfig *cfg.Config, state *sm.State, pv *ty // Make Mempool mempool := mempl.NewMempool(thisConfig.Mempool, proxyAppConnMem) + mempool.SetLogger(log.TestingLogger().With("module", "mempool")) // Make ConsensusReactor cs := NewConsensusState(thisConfig.Consensus, state, proxyAppConnCon, blockStore, mempool) + cs.SetLogger(log.TestingLogger()) cs.SetPrivValidator(pv) evsw := types.NewEventSwitch() + evsw.SetLogger(log.TestingLogger().With("module", "events")) cs.SetEventSwitch(evsw) evsw.Start() return cs @@ -263,7 +267,7 @@ func newConsensusStateWithConfig(thisConfig *cfg.Config, state *sm.State, pv *ty func loadPrivValidator(config *cfg.Config) *types.PrivValidator { privValidatorFile := config.PrivValidatorFile() ensureDir(path.Dir(privValidatorFile), 0700) - privValidator := types.LoadOrGenPrivValidator(privValidatorFile) + privValidator := types.LoadOrGenPrivValidator(privValidatorFile, log.TestingLogger()) privValidator.Reset() return privValidator } @@ -271,16 +275,20 @@ func loadPrivValidator(config *cfg.Config) *types.PrivValidator { func fixedConsensusState() *ConsensusState { stateDB := dbm.NewMemDB() state := sm.MakeGenesisStateFromFile(stateDB, config.GenesisFile()) + state.SetLogger(log.TestingLogger().With("module", "state")) privValidator := loadPrivValidator(config) cs := newConsensusState(state, privValidator, counter.NewCounterApplication(true)) + cs.SetLogger(log.TestingLogger()) return cs } func fixedConsensusStateDummy() *ConsensusState { stateDB := dbm.NewMemDB() state := sm.MakeGenesisStateFromFile(stateDB, config.GenesisFile()) + state.SetLogger(log.TestingLogger().With("module", "state")) privValidator := loadPrivValidator(config) cs := newConsensusState(state, privValidator, dummy.NewDummyApplication()) + cs.SetLogger(log.TestingLogger()) return cs } @@ -291,6 +299,7 @@ func randConsensusState(nValidators int) (*ConsensusState, []*validatorStub) { vss := make([]*validatorStub, nValidators) cs := newConsensusState(state, privVals[0], counter.NewCounterApplication(true)) + cs.SetLogger(log.TestingLogger()) for i := 0; i < nValidators; i++ { vss[i] = NewValidatorStub(privVals[i], i) @@ -322,10 +331,12 @@ func randConsensusNet(nValidators int, testName string, tickerFunc func() Timeou for i := 0; i < nValidators; i++ { db := dbm.NewMemDB() // each state needs its own db state := sm.MakeGenesisState(db, genDoc) + state.SetLogger(log.TestingLogger().With("module", "state")) state.Save() thisConfig := ResetConfig(Fmt("%s_%d", testName, i)) ensureDir(path.Dir(thisConfig.Consensus.WalFile()), 0700) // dir for wal css[i] = newConsensusStateWithConfig(thisConfig, state, privVals[i], appFunc()) + css[i].SetLogger(log.TestingLogger()) css[i].SetTimeoutTicker(tickerFunc()) } return css @@ -338,6 +349,7 @@ func randConsensusNetWithPeers(nValidators, nPeers int, testName string, tickerF for i := 0; i < nPeers; i++ { db := dbm.NewMemDB() // each state needs its own db state := sm.MakeGenesisState(db, genDoc) + state.SetLogger(log.TestingLogger().With("module", "state")) state.Save() thisConfig := ResetConfig(Fmt("%s_%d", testName, i)) ensureDir(path.Dir(thisConfig.Consensus.WalFile()), 0700) // dir for wal @@ -351,6 +363,7 @@ func randConsensusNetWithPeers(nValidators, nPeers int, testName string, tickerF } css[i] = newConsensusStateWithConfig(thisConfig, state, privVal, appFunc()) + css[i].SetLogger(log.TestingLogger()) css[i].SetTimeoutTicker(tickerFunc()) } return css @@ -392,6 +405,7 @@ func randGenesisState(numValidators int, randPower bool, minPower int64) (*sm.St genDoc, privValidators := randGenesisDoc(numValidators, randPower, minPower) db := dbm.NewMemDB() s0 := sm.MakeGenesisState(db, genDoc) + s0.SetLogger(log.TestingLogger().With("module", "state")) s0.Save() return s0, privValidators } diff --git a/consensus/height_vote_set.go b/consensus/height_vote_set.go index b2aebb095..455004f92 100644 --- a/consensus/height_vote_set.go +++ b/consensus/height_vote_set.go @@ -4,8 +4,8 @@ import ( "strings" "sync" - . "github.com/tendermint/tmlibs/common" "github.com/tendermint/tendermint/types" + . "github.com/tendermint/tmlibs/common" ) type RoundVoteSet struct { @@ -91,7 +91,7 @@ func (hvs *HeightVoteSet) addRound(round int) { if _, ok := hvs.roundVoteSets[round]; ok { PanicSanity("addRound() for an existing round") } - log.Debug("addRound(round)", "round", round) + // log.Debug("addRound(round)", "round", round) prevotes := types.NewVoteSet(hvs.chainID, hvs.height, round, types.VoteTypePrevote, hvs.valSet) precommits := types.NewVoteSet(hvs.chainID, hvs.height, round, types.VoteTypePrecommit, hvs.valSet) hvs.roundVoteSets[round] = RoundVoteSet{ @@ -118,7 +118,7 @@ func (hvs *HeightVoteSet) AddVote(vote *types.Vote, peerKey string) (added bool, // Peer has sent a vote that does not match our round, // for more than one round. Bad peer! // TODO punish peer. - log.Warn("Deal with peer giving votes from unwanted rounds") + // log.Warn("Deal with peer giving votes from unwanted rounds") return } } diff --git a/consensus/log.go b/consensus/log.go deleted file mode 100644 index 3e46c5eea..000000000 --- a/consensus/log.go +++ /dev/null @@ -1,18 +0,0 @@ -package consensus - -import ( - "github.com/tendermint/tmlibs/logger" -) - -var log = logger.New("module", "consensus") - -/* -func init() { - log.SetHandler( - logger.LvlFilterHandler( - logger.LvlDebug, - logger.BypassHandler(), - ), - ) -} -*/ diff --git a/consensus/reactor.go b/consensus/reactor.go index 5734298ef..3bb142625 100644 --- a/consensus/reactor.go +++ b/consensus/reactor.go @@ -8,7 +8,7 @@ import ( "sync" "time" - "github.com/tendermint/go-wire" + wire "github.com/tendermint/go-wire" "github.com/tendermint/tendermint/p2p" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" @@ -41,12 +41,12 @@ func NewConsensusReactor(consensusState *ConsensusState, fastSync bool) *Consens conS: consensusState, fastSync: fastSync, } - conR.BaseReactor = *p2p.NewBaseReactor(log, "ConsensusReactor", conR) + conR.BaseReactor = *p2p.NewBaseReactor("ConsensusReactor", conR) return conR } func (conR *ConsensusReactor) OnStart() error { - log.Notice("ConsensusReactor ", "fastSync", conR.fastSync) + conR.Logger.Info("ConsensusReactor ", "fastSync", conR.fastSync) conR.BaseReactor.OnStart() // callbacks for broadcasting new steps and votes to peers @@ -70,7 +70,7 @@ func (conR *ConsensusReactor) OnStop() { // Switch from the fast_sync to the consensus: // reset the state, turn off fast_sync, start the consensus-state-machine func (conR *ConsensusReactor) SwitchToConsensus(state *sm.State) { - log.Notice("SwitchToConsensus") + conR.Logger.Info("SwitchToConsensus") conR.conS.reconstructLastCommit(state) // NOTE: The line below causes broadcastNewRoundStepRoutine() to // broadcast a NewRoundStepMessage. @@ -148,17 +148,17 @@ func (conR *ConsensusReactor) RemovePeer(peer *p2p.Peer, reason interface{}) { // NOTE: blocks on consensus state for proposals, block parts, and votes func (conR *ConsensusReactor) Receive(chID byte, src *p2p.Peer, msgBytes []byte) { if !conR.IsRunning() { - log.Debug("Receive", "src", src, "chId", chID, "bytes", msgBytes) + conR.Logger.Debug("Receive", "src", src, "chId", chID, "bytes", msgBytes) return } _, msg, err := DecodeMessage(msgBytes) if err != nil { - log.Warn("Error decoding message", "src", src, "chId", chID, "msg", msg, "error", err, "bytes", msgBytes) + conR.Logger.Error("Error decoding message", "src", src, "chId", chID, "msg", msg, "error", err, "bytes", msgBytes) // TODO punish peer? return } - log.Debug("Receive", "src", src, "chId", chID, "msg", msg) + conR.Logger.Debug("Receive", "src", src, "chId", chID, "msg", msg) // Get peer states ps := src.Data.Get(types.PeerStateKey).(*PeerState) @@ -191,7 +191,7 @@ func (conR *ConsensusReactor) Receive(chID byte, src *p2p.Peer, msgBytes []byte) case types.VoteTypePrecommit: ourVotes = votes.Precommits(msg.Round).BitArrayByBlockID(msg.BlockID) default: - log.Warn("Bad VoteSetBitsMessage field Type") + conR.Logger.Error("Bad VoteSetBitsMessage field Type") return } src.TrySend(VoteSetBitsChannel, struct{ ConsensusMessage }{&VoteSetBitsMessage{ @@ -202,12 +202,12 @@ func (conR *ConsensusReactor) Receive(chID byte, src *p2p.Peer, msgBytes []byte) Votes: ourVotes, }}) default: - log.Warn(Fmt("Unknown message type %v", reflect.TypeOf(msg))) + conR.Logger.Error(Fmt("Unknown message type %v", reflect.TypeOf(msg))) } case DataChannel: if conR.fastSync { - log.Warn("Ignoring message received during fastSync", "msg", msg) + conR.Logger.Error("Ignoring message received during fastSync", "msg", msg) return } switch msg := msg.(type) { @@ -220,12 +220,12 @@ func (conR *ConsensusReactor) Receive(chID byte, src *p2p.Peer, msgBytes []byte) ps.SetHasProposalBlockPart(msg.Height, msg.Round, msg.Part.Index) conR.conS.peerMsgQueue <- msgInfo{msg, src.Key} default: - log.Warn(Fmt("Unknown message type %v", reflect.TypeOf(msg))) + conR.Logger.Error(Fmt("Unknown message type %v", reflect.TypeOf(msg))) } case VoteChannel: if conR.fastSync { - log.Warn("Ignoring message received during fastSync", "msg", msg) + conR.Logger.Info("Ignoring message received during fastSync", "msg", msg) return } switch msg := msg.(type) { @@ -242,12 +242,12 @@ func (conR *ConsensusReactor) Receive(chID byte, src *p2p.Peer, msgBytes []byte) default: // don't punish (leave room for soft upgrades) - log.Warn(Fmt("Unknown message type %v", reflect.TypeOf(msg))) + conR.Logger.Error(Fmt("Unknown message type %v", reflect.TypeOf(msg))) } case VoteSetBitsChannel: if conR.fastSync { - log.Warn("Ignoring message received during fastSync", "msg", msg) + conR.Logger.Info("Ignoring message received during fastSync", "msg", msg) return } switch msg := msg.(type) { @@ -265,7 +265,7 @@ func (conR *ConsensusReactor) Receive(chID byte, src *p2p.Peer, msgBytes []byte) case types.VoteTypePrecommit: ourVotes = votes.Precommits(msg.Round).BitArrayByBlockID(msg.BlockID) default: - log.Warn("Bad VoteSetBitsMessage field Type") + conR.Logger.Error("Bad VoteSetBitsMessage field Type") return } ps.ApplyVoteSetBitsMessage(msg, ourVotes) @@ -274,15 +274,15 @@ func (conR *ConsensusReactor) Receive(chID byte, src *p2p.Peer, msgBytes []byte) } default: // don't punish (leave room for soft upgrades) - log.Warn(Fmt("Unknown message type %v", reflect.TypeOf(msg))) + conR.Logger.Error(Fmt("Unknown message type %v", reflect.TypeOf(msg))) } default: - log.Warn(Fmt("Unknown chId %X", chID)) + conR.Logger.Error(Fmt("Unknown chId %X", chID)) } if err != nil { - log.Warn("Error in Receive()", "error", err) + conR.Logger.Error("Error in Receive()", "error", err) } } @@ -376,13 +376,13 @@ func (conR *ConsensusReactor) sendNewRoundStepMessages(peer *p2p.Peer) { } func (conR *ConsensusReactor) gossipDataRoutine(peer *p2p.Peer, ps *PeerState) { - log := log.New("peer", peer) + logger := conR.Logger.With("peer", peer) OUTER_LOOP: for { // Manage disconnects from self or peer. if !peer.IsRunning() || !conR.IsRunning() { - log.Notice(Fmt("Stopping gossipDataRoutine for %v.", peer)) + logger.Info("Stopping gossipDataRoutine for peer") return } rs := conR.conS.GetRoundState() @@ -390,7 +390,7 @@ OUTER_LOOP: // Send proposal Block parts? if rs.ProposalBlockParts.HasHeader(prs.ProposalBlockPartsHeader) { - //log.Info("ProposalBlockParts matched", "blockParts", prs.ProposalBlockParts) + //logger.Info("ProposalBlockParts matched", "blockParts", prs.ProposalBlockParts) if index, ok := rs.ProposalBlockParts.BitArray().Sub(prs.ProposalBlockParts.Copy()).PickRandom(); ok { part := rs.ProposalBlockParts.GetPart(index) msg := &BlockPartMessage{ @@ -407,16 +407,16 @@ OUTER_LOOP: // If the peer is on a previous height, help catch up. if (0 < prs.Height) && (prs.Height < rs.Height) { - //log.Info("Data catchup", "height", rs.Height, "peerHeight", prs.Height, "peerProposalBlockParts", prs.ProposalBlockParts) + //logger.Info("Data catchup", "height", rs.Height, "peerHeight", prs.Height, "peerProposalBlockParts", prs.ProposalBlockParts) if index, ok := prs.ProposalBlockParts.Not().PickRandom(); ok { // Ensure that the peer's PartSetHeader is correct blockMeta := conR.conS.blockStore.LoadBlockMeta(prs.Height) if blockMeta == nil { - log.Warn("Failed to load block meta", "peer height", prs.Height, "our height", rs.Height, "blockstore height", conR.conS.blockStore.Height(), "pv", conR.conS.privValidator) + logger.Error("Failed to load block meta", "peer height", prs.Height, "our height", rs.Height, "blockstore height", conR.conS.blockStore.Height(), "pv", conR.conS.privValidator) time.Sleep(peerGossipSleepDuration) continue OUTER_LOOP } else if !blockMeta.BlockID.PartsHeader.Equals(prs.ProposalBlockPartsHeader) { - log.Info("Peer ProposalBlockPartsHeader mismatch, sleeping", + logger.Info("Peer ProposalBlockPartsHeader mismatch, sleeping", "peerHeight", prs.Height, "blockPartsHeader", blockMeta.BlockID.PartsHeader, "peerBlockPartsHeader", prs.ProposalBlockPartsHeader) time.Sleep(peerGossipSleepDuration) continue OUTER_LOOP @@ -424,7 +424,7 @@ OUTER_LOOP: // Load the part part := conR.conS.blockStore.LoadBlockPart(prs.Height, index) if part == nil { - log.Warn("Could not load part", "index", index, + logger.Error("Could not load part", "index", index, "peerHeight", prs.Height, "blockPartsHeader", blockMeta.BlockID.PartsHeader, "peerBlockPartsHeader", prs.ProposalBlockPartsHeader) time.Sleep(peerGossipSleepDuration) continue OUTER_LOOP @@ -440,7 +440,7 @@ OUTER_LOOP: } continue OUTER_LOOP } else { - //log.Info("No parts to send in catch-up, sleeping") + //logger.Info("No parts to send in catch-up, sleeping") time.Sleep(peerGossipSleepDuration) continue OUTER_LOOP } @@ -448,7 +448,7 @@ OUTER_LOOP: // If height and round don't match, sleep. if (rs.Height != prs.Height) || (rs.Round != prs.Round) { - //log.Info("Peer Height|Round mismatch, sleeping", "peerHeight", prs.Height, "peerRound", prs.Round, "peer", peer) + //logger.Info("Peer Height|Round mismatch, sleeping", "peerHeight", prs.Height, "peerRound", prs.Round, "peer", peer) time.Sleep(peerGossipSleepDuration) continue OUTER_LOOP } @@ -489,7 +489,7 @@ OUTER_LOOP: } func (conR *ConsensusReactor) gossipVotesRoutine(peer *p2p.Peer, ps *PeerState) { - log := log.New("peer", peer) + logger := conR.Logger.With("peer", peer) // Simple hack to throttle logs upon sleep. var sleeping = 0 @@ -498,7 +498,7 @@ OUTER_LOOP: for { // Manage disconnects from self or peer. if !peer.IsRunning() || !conR.IsRunning() { - log.Notice(Fmt("Stopping gossipVotesRoutine for %v.", peer)) + logger.Info("Stopping gossipVotesRoutine for peer") return } rs := conR.conS.GetRoundState() @@ -511,7 +511,7 @@ OUTER_LOOP: sleeping = 0 } - //log.Debug("gossipVotesRoutine", "rsHeight", rs.Height, "rsRound", rs.Round, + //logger.Debug("gossipVotesRoutine", "rsHeight", rs.Height, "rsRound", rs.Round, // "prsHeight", prs.Height, "prsRound", prs.Round, "prsStep", prs.Step) // If height matches, then send LastCommit, Prevotes, Precommits. @@ -519,21 +519,21 @@ OUTER_LOOP: // If there are lastCommits to send... if prs.Step == RoundStepNewHeight { if ps.PickSendVote(rs.LastCommit) { - log.Debug("Picked rs.LastCommit to send") + logger.Debug("Picked rs.LastCommit to send") continue OUTER_LOOP } } // If there are prevotes to send... if prs.Step <= RoundStepPrevote && prs.Round != -1 && prs.Round <= rs.Round { if ps.PickSendVote(rs.Votes.Prevotes(prs.Round)) { - log.Debug("Picked rs.Prevotes(prs.Round) to send") + logger.Debug("Picked rs.Prevotes(prs.Round) to send") continue OUTER_LOOP } } // If there are precommits to send... if prs.Step <= RoundStepPrecommit && prs.Round != -1 && prs.Round <= rs.Round { if ps.PickSendVote(rs.Votes.Precommits(prs.Round)) { - log.Debug("Picked rs.Precommits(prs.Round) to send") + logger.Debug("Picked rs.Precommits(prs.Round) to send") continue OUTER_LOOP } } @@ -541,7 +541,7 @@ OUTER_LOOP: if prs.ProposalPOLRound != -1 { if polPrevotes := rs.Votes.Prevotes(prs.ProposalPOLRound); polPrevotes != nil { if ps.PickSendVote(polPrevotes) { - log.Debug("Picked rs.Prevotes(prs.ProposalPOLRound) to send") + logger.Debug("Picked rs.Prevotes(prs.ProposalPOLRound) to send") continue OUTER_LOOP } } @@ -552,7 +552,7 @@ OUTER_LOOP: // If peer is lagging by height 1, send LastCommit. if prs.Height != 0 && rs.Height == prs.Height+1 { if ps.PickSendVote(rs.LastCommit) { - log.Debug("Picked rs.LastCommit to send") + logger.Debug("Picked rs.LastCommit to send") continue OUTER_LOOP } } @@ -563,9 +563,9 @@ OUTER_LOOP: // Load the block commit for prs.Height, // which contains precommit signatures for prs.Height. commit := conR.conS.blockStore.LoadBlockCommit(prs.Height) - log.Info("Loaded BlockCommit for catch-up", "height", prs.Height, "commit", commit) + logger.Info("Loaded BlockCommit for catch-up", "height", prs.Height, "commit", commit) if ps.PickSendVote(commit) { - log.Debug("Picked Catchup commit to send") + logger.Debug("Picked Catchup commit to send") continue OUTER_LOOP } } @@ -573,7 +573,7 @@ OUTER_LOOP: if sleeping == 0 { // We sent nothing. Sleep... sleeping = 1 - log.Debug("No votes to send, sleeping", "peer", peer, + logger.Debug("No votes to send, sleeping", "peer", peer, "localPV", rs.Votes.Prevotes(rs.Round).BitArray(), "peerPV", prs.Prevotes, "localPC", rs.Votes.Precommits(rs.Round).BitArray(), "peerPC", prs.Precommits) } else if sleeping == 2 { @@ -589,13 +589,13 @@ OUTER_LOOP: // NOTE: `queryMaj23Routine` has a simple crude design since it only comes // into play for liveness when there's a signature DDoS attack happening. func (conR *ConsensusReactor) queryMaj23Routine(peer *p2p.Peer, ps *PeerState) { - log := log.New("peer", peer) + logger := conR.Logger.With("peer", peer) OUTER_LOOP: for { // Manage disconnects from self or peer. if !peer.IsRunning() || !conR.IsRunning() { - log.Notice(Fmt("Stopping queryMaj23Routine for %v.", peer)) + logger.Info("Stopping queryMaj23Routine for peer") return } @@ -952,8 +952,8 @@ func (ps *PeerState) SetHasVote(vote *types.Vote) { } func (ps *PeerState) setHasVote(height int, round int, type_ byte, index int) { - log := log.New("peer", ps.Peer, "peerRound", ps.Round, "height", height, "round", round) - log.Debug("setHasVote(LastCommit)", "lastCommit", ps.LastCommit, "index", index) + logger := ps.Peer.Logger.With("peerRound", ps.Round, "height", height, "round", round) + logger.Debug("setHasVote(LastCommit)", "lastCommit", ps.LastCommit, "index", index) // NOTE: some may be nil BitArrays -> no side effects. ps.getVoteBitArray(height, round, type_).SetIndex(index, true) diff --git a/consensus/reactor_test.go b/consensus/reactor_test.go index f52194588..dec577ac0 100644 --- a/consensus/reactor_test.go +++ b/consensus/reactor_test.go @@ -10,6 +10,7 @@ import ( "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/types" "github.com/tendermint/tmlibs/events" + "github.com/tendermint/tmlibs/log" ) func init() { @@ -24,8 +25,10 @@ func startConsensusNet(t *testing.T, css []*ConsensusState, N int, subscribeEven eventChans := make([]chan interface{}, N) for i := 0; i < N; i++ { reactors[i] = NewConsensusReactor(css[i], true) // so we dont start the consensus states + reactors[i].SetLogger(log.TestingLogger()) eventSwitch := events.NewEventSwitch() + eventSwitch.SetLogger(log.TestingLogger().With("module", "events")) _, err := eventSwitch.Start() if err != nil { t.Fatalf("Failed to start switch: %v", err) @@ -96,7 +99,7 @@ func TestVotingPowerChange(t *testing.T) { }, css) //--------------------------------------------------------------------------- - log.Info("---------------------------- Testing changing the voting power of one validator a few times") + t.Log("---------------------------- Testing changing the voting power of one validator a few times") val1PubKey := css[0].privValidator.(*types.PrivValidator).PubKey updateValidatorTx := dummy.MakeValSetChangeTx(val1PubKey.Bytes(), 25) @@ -157,7 +160,7 @@ func TestValidatorSetChanges(t *testing.T) { }, css) //--------------------------------------------------------------------------- - log.Info("---------------------------- Testing adding one validator") + t.Log("---------------------------- Testing adding one validator") newValidatorPubKey1 := css[nVals].privValidator.(*types.PrivValidator).PubKey newValidatorTx1 := dummy.MakeValSetChangeTx(newValidatorPubKey1.Bytes(), uint64(testMinPower)) @@ -183,7 +186,7 @@ func TestValidatorSetChanges(t *testing.T) { waitForAndValidateBlock(t, nPeers, activeVals, eventChans, css) //--------------------------------------------------------------------------- - log.Info("---------------------------- Testing changing the voting power of one validator") + t.Log("---------------------------- Testing changing the voting power of one validator") updateValidatorPubKey1 := css[nVals].privValidator.(*types.PrivValidator).PubKey updateValidatorTx1 := dummy.MakeValSetChangeTx(updateValidatorPubKey1.Bytes(), 25) @@ -199,7 +202,7 @@ func TestValidatorSetChanges(t *testing.T) { } //--------------------------------------------------------------------------- - log.Info("---------------------------- Testing adding two validators at once") + t.Log("---------------------------- Testing adding two validators at once") newValidatorPubKey2 := css[nVals+1].privValidator.(*types.PrivValidator).PubKey newValidatorTx2 := dummy.MakeValSetChangeTx(newValidatorPubKey2.Bytes(), uint64(testMinPower)) @@ -215,7 +218,7 @@ func TestValidatorSetChanges(t *testing.T) { waitForAndValidateBlock(t, nPeers, activeVals, eventChans, css) //--------------------------------------------------------------------------- - log.Info("---------------------------- Testing removing two validators at once") + t.Log("---------------------------- Testing removing two validators at once") removeValidatorTx2 := dummy.MakeValSetChangeTx(newValidatorPubKey2.Bytes(), 0) removeValidatorTx3 := dummy.MakeValSetChangeTx(newValidatorPubKey3.Bytes(), 0) @@ -251,7 +254,7 @@ func waitForAndValidateBlock(t *testing.T, n int, activeVals map[string]struct{} timeoutWaitGroup(t, n, func(wg *sync.WaitGroup, j int) { newBlockI := <-eventChans[j] newBlock := newBlockI.(types.TMEventData).Unwrap().(types.EventDataNewBlock).Block - log.Warn("Got block", "height", newBlock.Height, "validator", j) + t.Logf("[WARN] Got block height=%v validator=%v", newBlock.Height, j) err := validateBlock(newBlock, activeVals) if err != nil { t.Fatal(err) @@ -262,7 +265,7 @@ func waitForAndValidateBlock(t *testing.T, n int, activeVals map[string]struct{} eventChans[j] <- struct{}{} wg.Done() - log.Warn("Done wait group", "height", newBlock.Height, "validator", j) + t.Logf("[WARN] Done wait group height=%v validator=%v", newBlock.Height, j) }, css) } diff --git a/consensus/replay.go b/consensus/replay.go index 01199007e..04852dba8 100644 --- a/consensus/replay.go +++ b/consensus/replay.go @@ -11,9 +11,10 @@ import ( "time" abci "github.com/tendermint/abci/types" - "github.com/tendermint/go-wire" + wire "github.com/tendermint/go-wire" auto "github.com/tendermint/tmlibs/autofile" cmn "github.com/tendermint/tmlibs/common" + "github.com/tendermint/tmlibs/log" "github.com/tendermint/tendermint/proxy" sm "github.com/tendermint/tendermint/state" @@ -49,7 +50,7 @@ func (cs *ConsensusState) readReplayMessage(msgBytes []byte, newStepCh chan inte // for logging switch m := msg.Msg.(type) { case types.EventDataRoundState: - log.Notice("Replay: New Step", "height", m.Height, "round", m.Round, "step", m.Step) + cs.Logger.Info("Replay: New Step", "height", m.Height, "round", m.Round, "step", m.Step) // these are playback checks ticker := time.After(time.Second * 2) if newStepCh != nil { @@ -71,19 +72,19 @@ func (cs *ConsensusState) readReplayMessage(msgBytes []byte, newStepCh chan inte switch msg := m.Msg.(type) { case *ProposalMessage: p := msg.Proposal - log.Notice("Replay: Proposal", "height", p.Height, "round", p.Round, "header", + cs.Logger.Info("Replay: Proposal", "height", p.Height, "round", p.Round, "header", p.BlockPartsHeader, "pol", p.POLRound, "peer", peerKey) case *BlockPartMessage: - log.Notice("Replay: BlockPart", "height", msg.Height, "round", msg.Round, "peer", peerKey) + cs.Logger.Info("Replay: BlockPart", "height", msg.Height, "round", msg.Round, "peer", peerKey) case *VoteMessage: v := msg.Vote - log.Notice("Replay: Vote", "height", v.Height, "round", v.Round, "type", v.Type, + cs.Logger.Info("Replay: Vote", "height", v.Height, "round", v.Round, "type", v.Type, "blockID", v.BlockID, "peer", peerKey) } cs.handleMsg(m, cs.RoundState) case timeoutInfo: - log.Notice("Replay: Timeout", "height", m.Height, "round", m.Round, "step", m.Step, "dur", m.Duration) + cs.Logger.Info("Replay: Timeout", "height", m.Height, "round", m.Round, "step", m.Step, "dur", m.Duration) cs.handleTimeout(m, cs.RoundState) default: return fmt.Errorf("Replay: Unknown TimedWALMessage type: %v", reflect.TypeOf(msg.Msg)) @@ -113,12 +114,12 @@ func (cs *ConsensusState) catchupReplay(csHeight int) error { // Search for last height marker gr, found, err = cs.wal.group.Search("#ENDHEIGHT: ", makeHeightSearchFunc(csHeight-1)) if err == io.EOF { - log.Warn("Replay: wal.group.Search returned EOF", "#ENDHEIGHT", csHeight-1) + cs.Logger.Error("Replay: wal.group.Search returned EOF", "#ENDHEIGHT", csHeight-1) // if we upgraded from 0.9 to 0.9.1, we may have #HEIGHT instead // TODO (0.10.0): remove this gr, found, err = cs.wal.group.Search("#HEIGHT: ", makeHeightSearchFunc(csHeight)) if err == io.EOF { - log.Warn("Replay: wal.group.Search returned EOF", "#HEIGHT", csHeight) + cs.Logger.Error("Replay: wal.group.Search returned EOF", "#HEIGHT", csHeight) return nil } else if err != nil { return err @@ -133,7 +134,7 @@ func (cs *ConsensusState) catchupReplay(csHeight int) error { // TODO (0.10.0): remove this gr, found, err = cs.wal.group.Search("#HEIGHT: ", makeHeightSearchFunc(csHeight)) if err == io.EOF { - log.Warn("Replay: wal.group.Search returned EOF", "#HEIGHT", csHeight) + cs.Logger.Error("Replay: wal.group.Search returned EOF", "#HEIGHT", csHeight) return nil } else if err != nil { return err @@ -145,7 +146,7 @@ func (cs *ConsensusState) catchupReplay(csHeight int) error { // return errors.New(cmn.Fmt("Cannot replay height %d. WAL does not contain #ENDHEIGHT for %d.", csHeight, csHeight-1)) } - log.Notice("Catchup by replaying consensus messages", "height", csHeight) + cs.Logger.Info("Catchup by replaying consensus messages", "height", csHeight) for { line, err := gr.ReadLine() @@ -163,7 +164,7 @@ func (cs *ConsensusState) catchupReplay(csHeight int) error { return err } } - log.Notice("Replay: Done") + cs.Logger.Info("Replay: Done") return nil } @@ -198,14 +199,19 @@ func makeHeightSearchFunc(height int) auto.SearchFunc { // we were last and using the WAL to recover there type Handshaker struct { - state *sm.State - store types.BlockStore + state *sm.State + store types.BlockStore + logger log.Logger nBlocks int // number of blocks applied to the state } func NewHandshaker(state *sm.State, store types.BlockStore) *Handshaker { - return &Handshaker{state, store, 0} + return &Handshaker{state, store, log.NewNopLogger(), 0} +} + +func (h *Handshaker) SetLogger(l log.Logger) { + h.logger = l } func (h *Handshaker) NBlocks() int { @@ -223,7 +229,7 @@ func (h *Handshaker) Handshake(proxyApp proxy.AppConns) error { blockHeight := int(res.LastBlockHeight) // XXX: beware overflow appHash := res.LastBlockAppHash - log.Notice("ABCI Handshake", "appHeight", blockHeight, "appHash", appHash) + h.logger.Info("ABCI Handshake", "appHeight", blockHeight, "appHash", appHash) // TODO: check version @@ -233,7 +239,7 @@ func (h *Handshaker) Handshake(proxyApp proxy.AppConns) error { return errors.New(cmn.Fmt("Error on replay: %v", err)) } - log.Notice("Completed ABCI Handshake - Tendermint and App are synced", "appHeight", blockHeight, "appHash", appHash) + h.logger.Info("Completed ABCI Handshake - Tendermint and App are synced", "appHeight", blockHeight, "appHash", appHash) // TODO: (on restart) replay mempool @@ -246,7 +252,7 @@ func (h *Handshaker) ReplayBlocks(appHash []byte, appBlockHeight int, proxyApp p storeBlockHeight := h.store.Height() stateBlockHeight := h.state.LastBlockHeight - log.Notice("ABCI Replay Blocks", "appHeight", appBlockHeight, "storeHeight", storeBlockHeight, "stateHeight", stateBlockHeight) + h.logger.Info("ABCI Replay Blocks", "appHeight", appBlockHeight, "storeHeight", storeBlockHeight, "stateHeight", stateBlockHeight) // If appBlockHeight == 0 it means that we are at genesis and hence should send InitChain if appBlockHeight == 0 { @@ -298,14 +304,14 @@ func (h *Handshaker) ReplayBlocks(appHash []byte, appBlockHeight int, proxyApp p // so replayBlock with the real app. // NOTE: We could instead use the cs.WAL on cs.Start, // but we'd have to allow the WAL to replay a block that wrote it's ENDHEIGHT - log.Info("Replay last block using real app") + h.logger.Info("Replay last block using real app") return h.replayBlock(storeBlockHeight, proxyApp.Consensus()) } else if appBlockHeight == storeBlockHeight { // We ran Commit, but didn't save the state, so replayBlock with mock app abciResponses := h.state.LoadABCIResponses() mockApp := newMockProxyApp(appHash, abciResponses) - log.Info("Replay last block using mock app") + h.logger.Info("Replay last block using mock app") return h.replayBlock(storeBlockHeight, mockApp) } @@ -329,9 +335,9 @@ func (h *Handshaker) replayBlocks(proxyApp proxy.AppConns, appBlockHeight, store finalBlock -= 1 } for i := appBlockHeight + 1; i <= finalBlock; i++ { - log.Info("Applying block", "height", i) + h.logger.Info("Applying block", "height", i) block := h.store.LoadBlock(i) - appHash, err = sm.ExecCommitBlock(proxyApp.Consensus(), block) + appHash, err = sm.ExecCommitBlock(proxyApp.Consensus(), block, h.logger) if err != nil { return nil, err } diff --git a/consensus/replay_file.go b/consensus/replay_file.go index a0af8b853..39ce47c5e 100644 --- a/consensus/replay_file.go +++ b/consensus/replay_file.go @@ -113,7 +113,7 @@ func (pb *playback) replayReset(count int, newStepCh chan interface{}) error { pb.fp = fp pb.scanner = bufio.NewScanner(fp) count = pb.count - count - log.Notice(cmn.Fmt("Reseting from %d to %d", pb.count, count)) + fmt.Printf("Reseting from %d to %d\n", pb.count, count) pb.count = 0 pb.cs = newCS for i := 0; pb.scanner.Scan() && i < count; i++ { @@ -126,8 +126,7 @@ func (pb *playback) replayReset(count int, newStepCh chan interface{}) error { } func (cs *ConsensusState) startForReplay() { - - log.Warn("Replay commands are disabled until someone updates them and writes tests") + cs.Logger.Error("Replay commands are disabled until someone updates them and writes tests") /* TODO:! // since we replay tocks we just ignore ticks go func() { @@ -259,6 +258,7 @@ func newConsensusStateForReplay(config cfg.BaseConfig, csConfig *cfg.ConsensusCo } consensusState := NewConsensusState(csConfig, state.Copy(), proxyApp.Consensus(), blockStore, types.MockMempool{}) + consensusState.SetEventSwitch(eventSwitch) return consensusState } diff --git a/consensus/replay_test.go b/consensus/replay_test.go index 778e5c458..468149a3a 100644 --- a/consensus/replay_test.go +++ b/consensus/replay_test.go @@ -13,8 +13,8 @@ import ( "time" "github.com/tendermint/abci/example/dummy" - "github.com/tendermint/go-crypto" - "github.com/tendermint/go-wire" + crypto "github.com/tendermint/go-crypto" + wire "github.com/tendermint/go-wire" cmn "github.com/tendermint/tmlibs/common" dbm "github.com/tendermint/tmlibs/db" @@ -22,6 +22,7 @@ import ( "github.com/tendermint/tendermint/proxy" sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" + "github.com/tendermint/tmlibs/log" ) func init() { @@ -165,9 +166,9 @@ func toPV(pv PrivValidator) *types.PrivValidator { return pv.(*types.PrivValidator) } -func setupReplayTest(thisCase *testCase, nLines int, crashAfter bool) (*ConsensusState, chan interface{}, string, string) { - fmt.Println("-------------------------------------") - log.Notice(cmn.Fmt("Starting replay test %v (of %d lines of WAL). Crash after = %v", thisCase.name, nLines, crashAfter)) +func setupReplayTest(t *testing.T, thisCase *testCase, nLines int, crashAfter bool) (*ConsensusState, chan interface{}, string, string) { + t.Log("-------------------------------------") + t.Logf("Starting replay test %v (of %d lines of WAL). Crash after = %v", thisCase.name, nLines, crashAfter) lineStep := nLines if crashAfter { @@ -186,7 +187,7 @@ func setupReplayTest(thisCase *testCase, nLines int, crashAfter bool) (*Consensu toPV(cs.privValidator).LastHeight = 1 // first block toPV(cs.privValidator).LastStep = thisCase.stepMap[lineStep] - log.Warn("setupReplayTest", "LastStep", toPV(cs.privValidator).LastStep) + t.Logf("[WARN] setupReplayTest LastStep=%v", toPV(cs.privValidator).LastStep) newBlockCh := subscribeToEvent(cs.evsw, "tester", types.EventStringNewBlock(), 1) @@ -211,7 +212,7 @@ func TestWALCrashAfterWrite(t *testing.T) { for _, thisCase := range testCases { split := strings.Split(thisCase.log, "\n") for i := 0; i < len(split)-1; i++ { - cs, newBlockCh, _, walFile := setupReplayTest(thisCase, i+1, true) + cs, newBlockCh, _, walFile := setupReplayTest(t, thisCase, i+1, true) runReplayTest(t, cs, walFile, newBlockCh, thisCase, i+1) } } @@ -225,7 +226,7 @@ func TestWALCrashBeforeWritePropose(t *testing.T) { for _, thisCase := range testCases { lineNum := thisCase.proposeLine // setup replay test where last message is a proposal - cs, newBlockCh, proposalMsg, walFile := setupReplayTest(thisCase, lineNum, false) + cs, newBlockCh, proposalMsg, walFile := setupReplayTest(t, thisCase, lineNum, false) msg := readTimedWALMessage(t, proposalMsg) proposal := msg.Msg.(msgInfo).Msg.(*ProposalMessage) // Set LastSig @@ -249,7 +250,7 @@ func TestWALCrashBeforeWritePrecommit(t *testing.T) { func testReplayCrashBeforeWriteVote(t *testing.T, thisCase *testCase, lineNum int, eventString string) { // setup replay test where last message is a vote - cs, newBlockCh, voteMsg, walFile := setupReplayTest(thisCase, lineNum, false) + cs, newBlockCh, voteMsg, walFile := setupReplayTest(t, thisCase, lineNum, false) types.AddListenerForEvent(cs.evsw, "tester", eventString, func(data types.TMEventData) { msg := readTimedWALMessage(t, voteMsg) vote := msg.Msg.(msgInfo).Msg.(*VoteMessage) @@ -322,6 +323,7 @@ func testHandshakeReplay(t *testing.T, nBlocks int, mode uint) { testPartSize = config.Consensus.BlockPartSize wal, err := NewWAL(walFile, false) + wal.SetLogger(log.TestingLogger()) if err != nil { t.Fatal(err) } @@ -470,7 +472,7 @@ func makeBlockchainFromWAL(wal *WAL) ([]*types.Block, []*types.Commit, error) { } defer gr.Close() - log.Notice("Build a blockchain by reading from the WAL") + // log.Notice("Build a blockchain by reading from the WAL") var blockParts *types.PartSet var blocks []*types.Block @@ -617,6 +619,8 @@ func makeBlockchain(t *testing.T, chainID string, nBlocks int, privVal *types.Pr func stateAndStore(config *cfg.Config, pubKey crypto.PubKey) (*sm.State, *mockBlockStore) { stateDB := dbm.NewMemDB() state := sm.MakeGenesisStateFromFile(stateDB, config.GenesisFile()) + state.SetLogger(log.TestingLogger().With("module", "state")) + store := NewMockBlockStore(config) return state, store } diff --git a/consensus/state.go b/consensus/state.go index 579f22ce5..3ccf4be94 100644 --- a/consensus/state.go +++ b/consensus/state.go @@ -10,7 +10,7 @@ import ( "time" fail "github.com/ebuchman/fail-test" - "github.com/tendermint/go-wire" + wire "github.com/tendermint/go-wire" cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/proxy" sm "github.com/tendermint/tendermint/state" @@ -237,7 +237,7 @@ func NewConsensusState(config *cfg.ConsensusConfig, state *sm.State, proxyAppCon // Don't call scheduleRound0 yet. // We do that upon Start(). cs.reconstructLastCommit(state) - cs.BaseService = *cmn.NewBaseService(log, "ConsensusState", cs) + cs.BaseService = *cmn.NewBaseService(nil, "ConsensusState", cs) return cs } @@ -304,7 +304,7 @@ func (cs *ConsensusState) OnStart() error { walFile := cs.config.WalFile() if err := cs.OpenWAL(walFile); err != nil { - log.Error("Error loading ConsensusState wal", "error", err.Error()) + cs.Logger.Error("Error loading ConsensusState wal", "error", err.Error()) return err } @@ -318,7 +318,7 @@ func (cs *ConsensusState) OnStart() error { // we may have lost some votes if the process crashed // reload from consensus log to catchup if err := cs.catchupReplay(cs.Height); err != nil { - log.Error("Error on catchup replay. Proceeding to start ConsensusState anyway", "error", err.Error()) + cs.Logger.Error("Error on catchup replay. Proceeding to start ConsensusState anyway", "error", err.Error()) // NOTE: if we ever do return an error here, // make sure to stop the timeoutTicker } @@ -361,7 +361,7 @@ func (cs *ConsensusState) Wait() { func (cs *ConsensusState) OpenWAL(walFile string) (err error) { err = cmn.EnsureDir(path.Dir(walFile), 0700) if err != nil { - log.Error("Error ensuring ConsensusState wal dir", "error", err.Error()) + cs.Logger.Error("Error ensuring ConsensusState wal dir", "error", err.Error()) return err } @@ -442,7 +442,7 @@ func (cs *ConsensusState) updateRoundStep(round int, step RoundStepType) { // enterNewRound(height, 0) at cs.StartTime. func (cs *ConsensusState) scheduleRound0(rs *RoundState) { - //log.Info("scheduleRound0", "now", time.Now(), "startTime", cs.StartTime) + //cs.Logger.Info("scheduleRound0", "now", time.Now(), "startTime", cs.StartTime) sleepDuration := rs.StartTime.Sub(time.Now()) cs.scheduleTimeout(sleepDuration, rs.Height, 0, RoundStepNewHeight) } @@ -461,7 +461,7 @@ func (cs *ConsensusState) sendInternalMessage(mi msgInfo) { // be processed out of order. // TODO: use CList here for strict determinism and // attempt push to internalMsgQueue in receiveRoutine - log.Warn("Internal msg queue is full. Using a go-routine") + cs.Logger.Info("Internal msg queue is full. Using a go-routine") go func() { cs.internalMsgQueue <- mi }() } } @@ -507,7 +507,7 @@ func (cs *ConsensusState) updateToState(state *sm.State) { // This happens when SwitchToConsensus() is called in the reactor. // We don't want to reset e.g. the Votes. if cs.state != nil && (state.LastBlockHeight <= cs.state.LastBlockHeight) { - log.Notice("Ignoring updateToState()", "newHeight", state.LastBlockHeight+1, "oldHeight", cs.state.LastBlockHeight+1) + cs.Logger.Info("Ignoring updateToState()", "newHeight", state.LastBlockHeight+1, "oldHeight", cs.state.LastBlockHeight+1) return } @@ -576,7 +576,7 @@ func (cs *ConsensusState) receiveRoutine(maxSteps int) { for { if maxSteps > 0 { if cs.nSteps >= maxSteps { - log.Warn("reached max steps. exiting receive routine") + cs.Logger.Error("reached max steps. exiting receive routine") cs.nSteps = 0 return } @@ -649,19 +649,19 @@ func (cs *ConsensusState) handleMsg(mi msgInfo, rs RoundState) { // the peer is sending us CatchupCommit precommits. // We could make note of this and help filter in broadcastHasVoteMessage(). default: - log.Warn("Unknown msg type", reflect.TypeOf(msg)) + cs.Logger.Error("Unknown msg type", reflect.TypeOf(msg)) } if err != nil { - log.Error("Error with msg", "type", reflect.TypeOf(msg), "peer", peerKey, "error", err, "msg", msg) + cs.Logger.Error("Error with msg", "type", reflect.TypeOf(msg), "peer", peerKey, "error", err, "msg", msg) } } func (cs *ConsensusState) handleTimeout(ti timeoutInfo, rs RoundState) { - log.Debug("Received tock", "timeout", ti.Duration, "height", ti.Height, "round", ti.Round, "step", ti.Step) + cs.Logger.Debug("Received tock", "timeout", ti.Duration, "height", ti.Height, "round", ti.Round, "step", ti.Step) // timeouts must be for current height, round, step if ti.Height != rs.Height || ti.Round < rs.Round || (ti.Round == rs.Round && ti.Step < rs.Step) { - log.Debug("Ignoring tock because we're ahead", "height", rs.Height, "round", rs.Round, "step", rs.Step) + cs.Logger.Debug("Ignoring tock because we're ahead", "height", rs.Height, "round", rs.Round, "step", rs.Step) return } @@ -699,15 +699,15 @@ func (cs *ConsensusState) handleTimeout(ti timeoutInfo, rs RoundState) { // NOTE: cs.StartTime was already set for height. func (cs *ConsensusState) enterNewRound(height int, round int) { if cs.Height != height || round < cs.Round || (cs.Round == round && cs.Step != RoundStepNewHeight) { - log.Debug(cmn.Fmt("enterNewRound(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + cs.Logger.Debug(cmn.Fmt("enterNewRound(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) return } if now := time.Now(); cs.StartTime.After(now) { - log.Warn("Need to set a buffer and log.Warn() here for sanity.", "startTime", cs.StartTime, "now", now) + cs.Logger.Info("Need to set a buffer and log message here for sanity.", "startTime", cs.StartTime, "now", now) } - log.Notice(cmn.Fmt("enterNewRound(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + cs.Logger.Info(cmn.Fmt("enterNewRound(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) // Increment validators if necessary validators := cs.Validators @@ -741,10 +741,10 @@ func (cs *ConsensusState) enterNewRound(height int, round int) { // Enter: from NewRound(height,round). func (cs *ConsensusState) enterPropose(height int, round int) { if cs.Height != height || round < cs.Round || (cs.Round == round && RoundStepPropose <= cs.Step) { - log.Debug(cmn.Fmt("enterPropose(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + cs.Logger.Debug(cmn.Fmt("enterPropose(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) return } - log.Info(cmn.Fmt("enterPropose(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + cs.Logger.Info(cmn.Fmt("enterPropose(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) defer func() { // Done enterPropose: @@ -768,9 +768,9 @@ func (cs *ConsensusState) enterPropose(height int, round int) { } if !bytes.Equal(cs.Validators.GetProposer().Address, cs.privValidator.GetAddress()) { - log.Info("enterPropose: Not our turn to propose", "proposer", cs.Validators.GetProposer().Address, "privValidator", cs.privValidator) + cs.Logger.Info("enterPropose: Not our turn to propose", "proposer", cs.Validators.GetProposer().Address, "privValidator", cs.privValidator) } else { - log.Info("enterPropose: Our turn to propose", "proposer", cs.Validators.GetProposer().Address, "privValidator", cs.privValidator) + cs.Logger.Info("enterPropose: Our turn to propose", "proposer", cs.Validators.GetProposer().Address, "privValidator", cs.privValidator) cs.decideProposal(height, round) } @@ -810,11 +810,11 @@ func (cs *ConsensusState) defaultDecideProposal(height, round int) { part := blockParts.GetPart(i) cs.sendInternalMessage(msgInfo{&BlockPartMessage{cs.Height, cs.Round, part}, ""}) } - log.Info("Signed proposal", "height", height, "round", round, "proposal", proposal) - log.Debug(cmn.Fmt("Signed proposal block: %v", block)) + cs.Logger.Info("Signed proposal", "height", height, "round", round, "proposal", proposal) + cs.Logger.Debug(cmn.Fmt("Signed proposal block: %v", block)) } else { if !cs.replayMode { - log.Warn("enterPropose: Error signing proposal", "height", height, "round", round, "error", err) + cs.Logger.Error("enterPropose: Error signing proposal", "height", height, "round", round, "error", err) } } } @@ -849,7 +849,7 @@ func (cs *ConsensusState) createProposalBlock() (block *types.Block, blockParts commit = cs.LastCommit.MakeCommit() } else { // This shouldn't happen. - log.Error("enterPropose: Cannot propose anything: No commit for the previous block.") + cs.Logger.Error("enterPropose: Cannot propose anything: No commit for the previous block.") return } @@ -867,7 +867,7 @@ func (cs *ConsensusState) createProposalBlock() (block *types.Block, blockParts // Otherwise vote nil. func (cs *ConsensusState) enterPrevote(height int, round int) { if cs.Height != height || round < cs.Round || (cs.Round == round && RoundStepPrevote <= cs.Step) { - log.Debug(cmn.Fmt("enterPrevote(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + cs.Logger.Debug(cmn.Fmt("enterPrevote(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) return } @@ -885,7 +885,7 @@ func (cs *ConsensusState) enterPrevote(height int, round int) { // TODO: catchup event? } - log.Info(cmn.Fmt("enterPrevote(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + cs.Logger.Info(cmn.Fmt("enterPrevote(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) // Sign and broadcast vote as necessary cs.doPrevote(height, round) @@ -897,14 +897,14 @@ func (cs *ConsensusState) enterPrevote(height int, round int) { func (cs *ConsensusState) defaultDoPrevote(height int, round int) { // If a block is locked, prevote that. if cs.LockedBlock != nil { - log.Notice("enterPrevote: Block was locked") + cs.Logger.Info("enterPrevote: Block was locked") cs.signAddVote(types.VoteTypePrevote, cs.LockedBlock.Hash(), cs.LockedBlockParts.Header()) return } // If ProposalBlock is nil, prevote nil. if cs.ProposalBlock == nil { - log.Warn("enterPrevote: ProposalBlock is nil") + cs.Logger.Error("enterPrevote: ProposalBlock is nil") cs.signAddVote(types.VoteTypePrevote, nil, types.PartSetHeader{}) return } @@ -913,7 +913,7 @@ func (cs *ConsensusState) defaultDoPrevote(height int, round int) { err := cs.state.ValidateBlock(cs.ProposalBlock) if err != nil { // ProposalBlock is invalid, prevote nil. - log.Warn("enterPrevote: ProposalBlock is invalid", "error", err) + cs.Logger.Error("enterPrevote: ProposalBlock is invalid", "error", err) cs.signAddVote(types.VoteTypePrevote, nil, types.PartSetHeader{}) return } @@ -928,13 +928,13 @@ func (cs *ConsensusState) defaultDoPrevote(height int, round int) { // Enter: any +2/3 prevotes at next round. func (cs *ConsensusState) enterPrevoteWait(height int, round int) { if cs.Height != height || round < cs.Round || (cs.Round == round && RoundStepPrevoteWait <= cs.Step) { - log.Debug(cmn.Fmt("enterPrevoteWait(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + cs.Logger.Debug(cmn.Fmt("enterPrevoteWait(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) return } if !cs.Votes.Prevotes(round).HasTwoThirdsAny() { cmn.PanicSanity(cmn.Fmt("enterPrevoteWait(%v/%v), but Prevotes does not have any +2/3 votes", height, round)) } - log.Info(cmn.Fmt("enterPrevoteWait(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + cs.Logger.Info(cmn.Fmt("enterPrevoteWait(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) defer func() { // Done enterPrevoteWait: @@ -954,11 +954,11 @@ func (cs *ConsensusState) enterPrevoteWait(height int, round int) { // else, precommit nil otherwise. func (cs *ConsensusState) enterPrecommit(height int, round int) { if cs.Height != height || round < cs.Round || (cs.Round == round && RoundStepPrecommit <= cs.Step) { - log.Debug(cmn.Fmt("enterPrecommit(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + cs.Logger.Debug(cmn.Fmt("enterPrecommit(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) return } - log.Info(cmn.Fmt("enterPrecommit(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + cs.Logger.Info(cmn.Fmt("enterPrecommit(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) defer func() { // Done enterPrecommit: @@ -971,9 +971,9 @@ func (cs *ConsensusState) enterPrecommit(height int, round int) { // If we don't have a polka, we must precommit nil if !ok { if cs.LockedBlock != nil { - log.Notice("enterPrecommit: No +2/3 prevotes during enterPrecommit while we're locked. Precommitting nil") + cs.Logger.Info("enterPrecommit: No +2/3 prevotes during enterPrecommit while we're locked. Precommitting nil") } else { - log.Notice("enterPrecommit: No +2/3 prevotes during enterPrecommit. Precommitting nil.") + cs.Logger.Info("enterPrecommit: No +2/3 prevotes during enterPrecommit. Precommitting nil.") } cs.signAddVote(types.VoteTypePrecommit, nil, types.PartSetHeader{}) return @@ -991,9 +991,9 @@ func (cs *ConsensusState) enterPrecommit(height int, round int) { // +2/3 prevoted nil. Unlock and precommit nil. if len(blockID.Hash) == 0 { if cs.LockedBlock == nil { - log.Notice("enterPrecommit: +2/3 prevoted for nil.") + cs.Logger.Info("enterPrecommit: +2/3 prevoted for nil.") } else { - log.Notice("enterPrecommit: +2/3 prevoted for nil. Unlocking") + cs.Logger.Info("enterPrecommit: +2/3 prevoted for nil. Unlocking") cs.LockedRound = 0 cs.LockedBlock = nil cs.LockedBlockParts = nil @@ -1007,7 +1007,7 @@ func (cs *ConsensusState) enterPrecommit(height int, round int) { // If we're already locked on that block, precommit it, and update the LockedRound if cs.LockedBlock.HashesTo(blockID.Hash) { - log.Notice("enterPrecommit: +2/3 prevoted locked block. Relocking") + cs.Logger.Info("enterPrecommit: +2/3 prevoted locked block. Relocking") cs.LockedRound = round types.FireEventRelock(cs.evsw, cs.RoundStateEvent()) cs.signAddVote(types.VoteTypePrecommit, blockID.Hash, blockID.PartsHeader) @@ -1016,7 +1016,7 @@ func (cs *ConsensusState) enterPrecommit(height int, round int) { // If +2/3 prevoted for proposal block, stage and precommit it if cs.ProposalBlock.HashesTo(blockID.Hash) { - log.Notice("enterPrecommit: +2/3 prevoted proposal block. Locking", "hash", blockID.Hash) + cs.Logger.Info("enterPrecommit: +2/3 prevoted proposal block. Locking", "hash", blockID.Hash) // Validate the block. if err := cs.state.ValidateBlock(cs.ProposalBlock); err != nil { cmn.PanicConsensus(cmn.Fmt("enterPrecommit: +2/3 prevoted for an invalid block: %v", err)) @@ -1048,13 +1048,13 @@ func (cs *ConsensusState) enterPrecommit(height int, round int) { // Enter: any +2/3 precommits for next round. func (cs *ConsensusState) enterPrecommitWait(height int, round int) { if cs.Height != height || round < cs.Round || (cs.Round == round && RoundStepPrecommitWait <= cs.Step) { - log.Debug(cmn.Fmt("enterPrecommitWait(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + cs.Logger.Debug(cmn.Fmt("enterPrecommitWait(%v/%v): Invalid args. Current step: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) return } if !cs.Votes.Precommits(round).HasTwoThirdsAny() { cmn.PanicSanity(cmn.Fmt("enterPrecommitWait(%v/%v), but Precommits does not have any +2/3 votes", height, round)) } - log.Info(cmn.Fmt("enterPrecommitWait(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) + cs.Logger.Info(cmn.Fmt("enterPrecommitWait(%v/%v). Current: %v/%v/%v", height, round, cs.Height, cs.Round, cs.Step)) defer func() { // Done enterPrecommitWait: @@ -1070,10 +1070,10 @@ func (cs *ConsensusState) enterPrecommitWait(height int, round int) { // Enter: +2/3 precommits for block func (cs *ConsensusState) enterCommit(height int, commitRound int) { if cs.Height != height || RoundStepCommit <= cs.Step { - log.Debug(cmn.Fmt("enterCommit(%v/%v): Invalid args. Current step: %v/%v/%v", height, commitRound, cs.Height, cs.Round, cs.Step)) + cs.Logger.Debug(cmn.Fmt("enterCommit(%v/%v): Invalid args. Current step: %v/%v/%v", height, commitRound, cs.Height, cs.Round, cs.Step)) return } - log.Info(cmn.Fmt("enterCommit(%v/%v). Current: %v/%v/%v", height, commitRound, cs.Height, cs.Round, cs.Step)) + cs.Logger.Info(cmn.Fmt("enterCommit(%v/%v). Current: %v/%v/%v", height, commitRound, cs.Height, cs.Round, cs.Step)) defer func() { // Done enterCommit: @@ -1121,13 +1121,13 @@ func (cs *ConsensusState) tryFinalizeCommit(height int) { blockID, ok := cs.Votes.Precommits(cs.CommitRound).TwoThirdsMajority() if !ok || len(blockID.Hash) == 0 { - log.Warn("Attempt to finalize failed. There was no +2/3 majority, or +2/3 was for .", "height", height) + cs.Logger.Error("Attempt to finalize failed. There was no +2/3 majority, or +2/3 was for .", "height", height) return } if !cs.ProposalBlock.HashesTo(blockID.Hash) { // TODO: this happens every time if we're not a validator (ugly logs) // TODO: ^^ wait, why does it matter that we're a validator? - log.Warn("Attempt to finalize failed. We don't have the commit block.", "height", height, "proposal-block", cs.ProposalBlock.Hash(), "commit-block", blockID.Hash) + cs.Logger.Error("Attempt to finalize failed. We don't have the commit block.", "height", height, "proposal-block", cs.ProposalBlock.Hash(), "commit-block", blockID.Hash) return } // go @@ -1137,7 +1137,7 @@ func (cs *ConsensusState) tryFinalizeCommit(height int) { // Increment height and goto RoundStepNewHeight func (cs *ConsensusState) finalizeCommit(height int) { if cs.Height != height || cs.Step != RoundStepCommit { - log.Debug(cmn.Fmt("finalizeCommit(%v): Invalid args. Current step: %v/%v/%v", height, cs.Height, cs.Round, cs.Step)) + cs.Logger.Debug(cmn.Fmt("finalizeCommit(%v): Invalid args. Current step: %v/%v/%v", height, cs.Height, cs.Round, cs.Step)) return } @@ -1157,9 +1157,9 @@ func (cs *ConsensusState) finalizeCommit(height int) { cmn.PanicConsensus(cmn.Fmt("+2/3 committed an invalid block: %v", err)) } - log.Notice(cmn.Fmt("Finalizing commit of block with %d txs", block.NumTxs), + cs.Logger.Info(cmn.Fmt("Finalizing commit of block with %d txs", block.NumTxs), "height", block.Height, "hash", block.Hash(), "root", block.AppHash) - log.Info(cmn.Fmt("%v", block)) + cs.Logger.Info(cmn.Fmt("%v", block)) fail.Fail() // XXX @@ -1172,7 +1172,7 @@ func (cs *ConsensusState) finalizeCommit(height int) { cs.blockStore.SaveBlock(block, blockParts, seenCommit) } else { // Happens during replay if we already saved the block but didn't commit - log.Info("Calling finalizeCommit on already stored block", "height", block.Height) + cs.Logger.Info("Calling finalizeCommit on already stored block", "height", block.Height) } fail.Fail() // XXX @@ -1200,7 +1200,7 @@ func (cs *ConsensusState) finalizeCommit(height int) { // NOTE: the block.AppHash wont reflect these txs until the next block err := stateCopy.ApplyBlock(eventCache, cs.proxyAppConn, block, blockParts.Header(), cs.mempool) if err != nil { - log.Error("Error on ApplyBlock. Did the application crash? Please restart tendermint", "error", err) + cs.Logger.Error("Error on ApplyBlock. Did the application crash? Please restart tendermint", "error", err) return } @@ -1293,7 +1293,7 @@ func (cs *ConsensusState) addProposalBlockPart(height int, part *types.Part, ver var err error cs.ProposalBlock = wire.ReadBinary(&types.Block{}, cs.ProposalBlockParts.GetReader(), types.MaxBlockSize, &n, &err).(*types.Block) // NOTE: it's possible to receive complete proposal blocks for future rounds without having the proposal - log.Info("Received complete proposal block", "height", cs.ProposalBlock.Height, "hash", cs.ProposalBlock.Hash()) + cs.Logger.Info("Received complete proposal block", "height", cs.ProposalBlock.Height, "hash", cs.ProposalBlock.Hash()) if cs.Step == RoundStepPropose && cs.isProposalComplete() { // Move onto the next step cs.enterPrevote(height, cs.Round) @@ -1317,10 +1317,10 @@ func (cs *ConsensusState) tryAddVote(vote *types.Vote, peerKey string) error { return err } else if _, ok := err.(*types.ErrVoteConflictingVotes); ok { if peerKey == "" { - log.Warn("Found conflicting vote from ourselves. Did you unsafe_reset a validator?", "height", vote.Height, "round", vote.Round, "type", vote.Type) + cs.Logger.Error("Found conflicting vote from ourselves. Did you unsafe_reset a validator?", "height", vote.Height, "round", vote.Round, "type", vote.Type) return err } - log.Warn("Found conflicting vote. Publish evidence (TODO)") + cs.Logger.Error("Found conflicting vote. Publish evidence (TODO)") /* TODO evidenceTx := &types.DupeoutTx{ Address: address, @@ -1332,7 +1332,7 @@ func (cs *ConsensusState) tryAddVote(vote *types.Vote, peerKey string) error { return err } else { // Probably an invalid signature. Bad peer. - log.Warn("Error attempting to add vote", "error", err) + cs.Logger.Error("Error attempting to add vote", "error", err) return ErrAddingVote } } @@ -1342,7 +1342,7 @@ func (cs *ConsensusState) tryAddVote(vote *types.Vote, peerKey string) error { //----------------------------------------------------------------------------- func (cs *ConsensusState) addVote(vote *types.Vote, peerKey string) (added bool, err error) { - log.Debug("addVote", "voteHeight", vote.Height, "voteType", vote.Type, "csHeight", cs.Height) + cs.Logger.Debug("addVote", "voteHeight", vote.Height, "voteType", vote.Type, "csHeight", cs.Height) // A precommit for the previous height? // These come in while we wait timeoutCommit @@ -1354,7 +1354,7 @@ func (cs *ConsensusState) addVote(vote *types.Vote, peerKey string) (added bool, } added, err = cs.LastCommit.AddVote(vote) if added { - log.Info(cmn.Fmt("Added to lastPrecommits: %v", cs.LastCommit.StringShort())) + cs.Logger.Info(cmn.Fmt("Added to lastPrecommits: %v", cs.LastCommit.StringShort())) types.FireEventVote(cs.evsw, types.EventDataVote{vote}) // if we can skip timeoutCommit and have all the votes now, @@ -1378,7 +1378,7 @@ func (cs *ConsensusState) addVote(vote *types.Vote, peerKey string) (added bool, switch vote.Type { case types.VoteTypePrevote: prevotes := cs.Votes.Prevotes(vote.Round) - log.Info("Added to prevote", "vote", vote, "prevotes", prevotes.StringShort()) + cs.Logger.Info("Added to prevote", "vote", vote, "prevotes", prevotes.StringShort()) // First, unlock if prevotes is a valid POL. // >> lockRound < POLRound <= unlockOrChangeLockRound (see spec) // NOTE: If (lockRound < POLRound) but !(POLRound <= unlockOrChangeLockRound), @@ -1387,7 +1387,7 @@ func (cs *ConsensusState) addVote(vote *types.Vote, peerKey string) (added bool, if (cs.LockedBlock != nil) && (cs.LockedRound < vote.Round) && (vote.Round <= cs.Round) { blockID, ok := prevotes.TwoThirdsMajority() if ok && !cs.LockedBlock.HashesTo(blockID.Hash) { - log.Notice("Unlocking because of POL.", "lockedRound", cs.LockedRound, "POLRound", vote.Round) + cs.Logger.Info("Unlocking because of POL.", "lockedRound", cs.LockedRound, "POLRound", vote.Round) cs.LockedRound = 0 cs.LockedBlock = nil cs.LockedBlockParts = nil @@ -1411,7 +1411,7 @@ func (cs *ConsensusState) addVote(vote *types.Vote, peerKey string) (added bool, } case types.VoteTypePrecommit: precommits := cs.Votes.Precommits(vote.Round) - log.Info("Added to precommit", "vote", vote, "precommits", precommits.StringShort()) + cs.Logger.Info("Added to precommit", "vote", vote, "precommits", precommits.StringShort()) blockID, ok := precommits.TwoThirdsMajority() if ok { if len(blockID.Hash) == 0 { @@ -1445,7 +1445,7 @@ func (cs *ConsensusState) addVote(vote *types.Vote, peerKey string) (added bool, } // Height mismatch, bad peer? - log.Info("Vote ignored and not added", "voteHeight", vote.Height, "csHeight", cs.Height, "err", err) + cs.Logger.Info("Vote ignored and not added", "voteHeight", vote.Height, "csHeight", cs.Height, "err", err) return } @@ -1473,11 +1473,11 @@ func (cs *ConsensusState) signAddVote(type_ byte, hash []byte, header types.Part vote, err := cs.signVote(type_, hash, header) if err == nil { cs.sendInternalMessage(msgInfo{&VoteMessage{vote}, ""}) - log.Info("Signed and pushed vote", "height", cs.Height, "round", cs.Round, "vote", vote, "error", err) + cs.Logger.Info("Signed and pushed vote", "height", cs.Height, "round", cs.Round, "vote", vote, "error", err) return vote } else { //if !cs.replayMode { - log.Warn("Error signing vote", "height", cs.Height, "round", cs.Round, "vote", vote, "error", err) + cs.Logger.Error("Error signing vote", "height", cs.Height, "round", cs.Round, "vote", vote, "error", err) //} return nil } diff --git a/consensus/state_test.go b/consensus/state_test.go index f4eed5732..2606685a4 100644 --- a/consensus/state_test.go +++ b/consensus/state_test.go @@ -375,7 +375,7 @@ func TestLockNoPOL(t *testing.T) { /// <-newRoundCh - log.Notice("#### ONTO ROUND 1") + t.Log("#### ONTO ROUND 1") /* Round2 (cs1, B) // B B2 */ @@ -420,7 +420,7 @@ func TestLockNoPOL(t *testing.T) { <-timeoutWaitCh <-newRoundCh - log.Notice("#### ONTO ROUND 2") + t.Log("#### ONTO ROUND 2") /* Round3 (vs2, _) // B, B2 */ @@ -461,7 +461,7 @@ func TestLockNoPOL(t *testing.T) { incrementRound(vs2) <-newRoundCh - log.Notice("#### ONTO ROUND 3") + t.Log("#### ONTO ROUND 3") /* Round4 (vs2, C) // B C // B C */ @@ -502,7 +502,7 @@ func TestLockPOLRelock(t *testing.T) { newRoundCh := subscribeToEvent(cs1.evsw, "tester", types.EventStringNewRound(), 1) newBlockCh := subscribeToEvent(cs1.evsw, "tester", types.EventStringNewBlockHeader(), 1) - log.Debug("vs2 last round", "lr", vs2.PrivValidator.LastRound) + t.Logf("vs2 last round %v", vs2.PrivValidator.LastRound) // everything done from perspective of cs1 @@ -548,7 +548,7 @@ func TestLockPOLRelock(t *testing.T) { cs1.SetProposalAndBlock(prop, propBlock, propBlockParts, "some peer") <-newRoundCh - log.Notice("### ONTO ROUND 1") + t.Log("### ONTO ROUND 1") /* Round2 (vs2, C) // B C C C // C C C _) @@ -659,7 +659,7 @@ func TestLockPOLUnlock(t *testing.T) { cs1.SetProposalAndBlock(prop, propBlock, propBlockParts, "some peer") <-newRoundCh - log.Notice("#### ONTO ROUND 1") + t.Log("#### ONTO ROUND 1") /* Round2 (vs2, C) // B nil nil nil // nil nil nil _ @@ -731,7 +731,7 @@ func TestLockPOLSafety1(t *testing.T) { panic("failed to update validator") }*/ - log.Warn("old prop", "hash", fmt.Sprintf("%X", propBlock.Hash())) + t.Logf("old prop hash %v", fmt.Sprintf("%X", propBlock.Hash())) // we do see them precommit nil signAddVotes(cs1, types.VoteTypePrecommit, nil, types.PartSetHeader{}, vs2, vs3, vs4) @@ -746,7 +746,7 @@ func TestLockPOLSafety1(t *testing.T) { cs1.SetProposalAndBlock(prop, propBlock, propBlockParts, "some peer") <-newRoundCh - log.Notice("### ONTO ROUND 1") + t.Log("### ONTO ROUND 1") /*Round2 // we timeout and prevote our lock // a polka happened but we didn't see it! @@ -765,7 +765,7 @@ func TestLockPOLSafety1(t *testing.T) { if rs.LockedBlock != nil { panic("we should not be locked!") } - log.Warn("new prop", "hash", fmt.Sprintf("%X", propBlockHash)) + t.Logf("new prop hash %v", fmt.Sprintf("%X", propBlockHash)) // go to prevote, prevote for proposal block <-voteCh validatePrevote(t, cs1, 1, vss[0], propBlockHash) @@ -786,7 +786,7 @@ func TestLockPOLSafety1(t *testing.T) { <-newRoundCh - log.Notice("### ONTO ROUND 2") + t.Log("### ONTO ROUND 2") /*Round3 we see the polka from round 1 but we shouldn't unlock! */ @@ -805,7 +805,7 @@ func TestLockPOLSafety1(t *testing.T) { // add prevotes from the earlier round addVotes(cs1, prevotes...) - log.Warn("Done adding prevotes!") + t.Log("Done adding prevotes!") ensureNoNewStep(newStepCh) } @@ -849,7 +849,7 @@ func TestLockPOLSafety2(t *testing.T) { cs1.updateRoundStep(0, RoundStepPrecommitWait) - log.Notice("### ONTO Round 1") + t.Log("### ONTO Round 1") // jump in at round 1 height := cs1.Height startTestRound(cs1, height, 1) @@ -886,7 +886,7 @@ func TestLockPOLSafety2(t *testing.T) { addVotes(cs1, prevotes...) <-newRoundCh - log.Notice("### ONTO Round 2") + t.Log("### ONTO Round 2") /*Round2 // now we see the polka from round 1, but we shouldnt unlock */ @@ -1033,7 +1033,7 @@ func TestHalt1(t *testing.T) { re = <-newRoundCh rs = re.(types.TMEventData).Unwrap().(types.EventDataRoundState).RoundState.(*RoundState) - log.Notice("### ONTO ROUND 1") + t.Log("### ONTO ROUND 1") /*Round2 // we timeout and prevote our lock // a polka happened but we didn't see it! diff --git a/consensus/ticker.go b/consensus/ticker.go index f8031e57c..1abab8cf7 100644 --- a/consensus/ticker.go +++ b/consensus/ticker.go @@ -39,8 +39,8 @@ func NewTimeoutTicker() TimeoutTicker { tickChan: make(chan timeoutInfo, tickTockBufferSize), tockChan: make(chan timeoutInfo, tickTockBufferSize), } + tt.BaseService = *NewBaseService(nil, "TimeoutTicker", tt) tt.stopTimer() // don't want to fire until the first scheduled timeout - tt.BaseService = *NewBaseService(log, "TimeoutTicker", tt) return tt } @@ -75,7 +75,7 @@ func (t *timeoutTicker) stopTimer() { select { case <-t.timer.C: default: - log.Debug("Timer already stopped") + t.Logger.Debug("Timer already stopped") } } } @@ -84,12 +84,12 @@ func (t *timeoutTicker) stopTimer() { // timers are interupted and replaced by new ticks from later steps // timeouts of 0 on the tickChan will be immediately relayed to the tockChan func (t *timeoutTicker) timeoutRoutine() { - log.Debug("Starting timeout routine") + t.Logger.Debug("Starting timeout routine") var ti timeoutInfo for { select { case newti := <-t.tickChan: - log.Debug("Received tick", "old_ti", ti, "new_ti", newti) + t.Logger.Debug("Received tick", "old_ti", ti, "new_ti", newti) // ignore tickers for old height/round/step if newti.Height < ti.Height { @@ -111,9 +111,9 @@ func (t *timeoutTicker) timeoutRoutine() { // NOTE time.Timer allows duration to be non-positive ti = newti t.timer.Reset(ti.Duration) - log.Debug("Scheduled timeout", "dur", ti.Duration, "height", ti.Height, "round", ti.Round, "step", ti.Step) + t.Logger.Debug("Scheduled timeout", "dur", ti.Duration, "height", ti.Height, "round", ti.Round, "step", ti.Step) case <-t.timer.C: - log.Info("Timed out", "dur", ti.Duration, "height", ti.Height, "round", ti.Round, "step", ti.Step) + t.Logger.Info("Timed out", "dur", ti.Duration, "height", ti.Height, "round", ti.Round, "step", ti.Step) // go routine here gaurantees timeoutRoutine doesn't block. // Determinism comes from playback in the receiveRoutine. // We can eliminate it by merging the timeoutRoutine into receiveRoutine diff --git a/consensus/wal.go b/consensus/wal.go index e855694a0..dde9b1b94 100644 --- a/consensus/wal.go +++ b/consensus/wal.go @@ -3,10 +3,10 @@ package consensus import ( "time" + wire "github.com/tendermint/go-wire" + "github.com/tendermint/tendermint/types" auto "github.com/tendermint/tmlibs/autofile" . "github.com/tendermint/tmlibs/common" - "github.com/tendermint/go-wire" - "github.com/tendermint/tendermint/types" ) //-------------------------------------------------------- @@ -49,7 +49,7 @@ func NewWAL(walFile string, light bool) (*WAL, error) { group: group, light: light, } - wal.BaseService = *NewBaseService(log, "WAL", wal) + wal.BaseService = *NewBaseService(nil, "WAL", wal) _, err = wal.Start() return wal, err } diff --git a/glide.lock b/glide.lock index 27b469202..07f9cffb0 100644 --- a/glide.lock +++ b/glide.lock @@ -1,5 +1,5 @@ -hash: c715f30f5021a73c8d35229ad5bb7473bd5b18a24707b3211f264658c44ef63f -updated: 2017-05-05T00:50:11.28834974-04:00 +hash: 83b5ca94602b8296526e421b9bc0a99584cff3909684fbda49c31ffcde1eea98 +updated: 2017-05-05T18:00:37.128906219Z imports: - name: github.com/btcsuite/btcd version: 4b348c1d33373d672edd83fc576892d0e46686d2 @@ -13,6 +13,14 @@ imports: version: 95f809107225be108efcf10a3509e4ea6ceef3c4 - name: github.com/fsnotify/fsnotify version: 4da3e2cfbabc9f751898f250b49f2439785783a1 +- name: github.com/go-kit/kit + version: 0873e56b0faeae3a1d661b10d629135508ea5504 + subpackages: + - log + - log/level + - log/term +- name: github.com/go-logfmt/logfmt + version: 390ab7935ee28ec6b286364bba9b4dd6410cb3d5 - name: github.com/go-stack/stack version: 7a2f19628aabfe68f0766b59e74d6315f8347d22 - name: github.com/gogo/protobuf @@ -43,6 +51,8 @@ imports: version: 76626ae9c91c4f2a10f34cad8ce83ea42c93bb75 - name: github.com/jmhodges/levigo version: c42d9e0ca023e2198120196f842701bb4c55d7b9 +- name: github.com/kr/logfmt + version: b84e30acd515aadc4b783ad4ff83aff3299bdfe0 - name: github.com/magiconair/properties version: 51463bfca2576e06c62a8504b5c0f06d61312647 - name: github.com/mattn/go-colorable @@ -68,11 +78,11 @@ imports: - name: github.com/spf13/cast version: acbeb36b902d72a7a4c18e8f3241075e7ab763e4 - name: github.com/spf13/cobra - version: 8f0203be891287870100e4af46262cdf4a4261d1 + version: db6b9a8b3f3f400c8ecb4a4d7d02245b8facad66 - name: github.com/spf13/jwalterweatherman version: fa7ca7e836cf3a8bb4ebf799f472c12d7e903d66 - name: github.com/spf13/pflag - version: c990990ab4981d84da820b7b00c85139ca150b5f + version: 80fe0fb4eba54167e2ccae1c6c950e72abf61b73 - name: github.com/spf13/viper version: 0967fc9aceab2ce9da34061253ac10fb99bba5b2 - name: github.com/stretchr/testify @@ -96,7 +106,7 @@ imports: - leveldb/table - leveldb/util - name: github.com/tendermint/abci - version: 8d8e35ae537538c9cf6808be3ca9dd7dab81b7f6 + version: 50a9967c79d89742151c7f1a981678df8c21f9dc subpackages: - client - example/counter @@ -109,7 +119,7 @@ imports: - edwards25519 - extra25519 - name: github.com/tendermint/go-crypto - version: 524ba917a3a1636f21ab2c0bf76b6526903ab879 + version: e71bbb2509b586f0b24f120b6ba57f32aefa1579 - name: github.com/tendermint/go-wire version: b53add0b622662731985485f3a19be7f684660b8 subpackages: @@ -120,14 +130,14 @@ imports: subpackages: - term - name: github.com/tendermint/merkleeyes - version: d0aa363fd4e015e509038c3a0ec493bc62ee0b8a + version: c722818b460381bc5b82e38c73ff6e22a9df624d subpackages: - app - client - iavl - testutil - name: github.com/tendermint/tmlibs - version: 2f02ed18e9b706467c9474d024a25a0b7a9c0e97 + version: 240215f2aa26d53223c618a5a2127a08d37868f0 subpackages: - autofile - cli @@ -136,6 +146,7 @@ imports: - db - events - flowrate + - log - logger - merkle - test diff --git a/glide.yaml b/glide.yaml index 9803f5b91..a7d3fb79f 100644 --- a/glide.yaml +++ b/glide.yaml @@ -12,7 +12,7 @@ import: - package: github.com/spf13/cobra - package: github.com/spf13/viper - package: github.com/tendermint/abci - version: develop + version: feature/new-logging subpackages: - client - example/dummy @@ -25,7 +25,7 @@ import: - data - package: github.com/tendermint/log15 - package: github.com/tendermint/tmlibs - version: cli + version: log subpackages: - autofile - cli @@ -34,7 +34,7 @@ import: - db - events - flowrate - - logger + - log - merkle - package: golang.org/x/crypto subpackages: diff --git a/mempool/log.go b/mempool/log.go deleted file mode 100644 index ac9596d5e..000000000 --- a/mempool/log.go +++ /dev/null @@ -1,18 +0,0 @@ -package mempool - -import ( - "github.com/tendermint/tmlibs/logger" -) - -var log = logger.New("module", "mempool") - -/* -func init() { - log.SetHandler( - logger.LvlFilterHandler( - logger.LvlDebug, - logger.BypassHandler(), - ), - ) -} -*/ diff --git a/mempool/mempool.go b/mempool/mempool.go index 44a20e6f5..81bcb483e 100644 --- a/mempool/mempool.go +++ b/mempool/mempool.go @@ -7,6 +7,8 @@ import ( "sync/atomic" "time" + "github.com/pkg/errors" + abci "github.com/tendermint/abci/types" auto "github.com/tendermint/tmlibs/autofile" "github.com/tendermint/tmlibs/clist" @@ -15,6 +17,7 @@ import ( cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/proxy" "github.com/tendermint/tendermint/types" + "github.com/tendermint/tmlibs/log" ) /* @@ -65,6 +68,8 @@ type Mempool struct { // A log of mempool txs wal *auto.AutoFile + + logger log.Logger } func NewMempool(config *cfg.MempoolConfig, proxyAppConn proxy.AppConnMempool) *Mempool { @@ -77,26 +82,29 @@ func NewMempool(config *cfg.MempoolConfig, proxyAppConn proxy.AppConnMempool) *M rechecking: 0, recheckCursor: nil, recheckEnd: nil, - - cache: newTxCache(cacheSize), + logger: log.NewNopLogger(), + cache: newTxCache(cacheSize), } mempool.initWAL() proxyAppConn.SetResponseCallback(mempool.resCb) return mempool } +// SetLogger allows you to set your own Logger. +func (mem *Mempool) SetLogger(l log.Logger) { + mem.logger = l +} + func (mem *Mempool) initWAL() { walDir := mem.config.WalDir() if walDir != "" { err := cmn.EnsureDir(walDir, 0700) if err != nil { - log.Error("Error ensuring Mempool wal dir", "error", err) - cmn.PanicSanity(err) + cmn.PanicSanity(errors.Wrap(err, "Error ensuring Mempool wal dir")) } af, err := auto.OpenAutoFile(walDir + "/wal") if err != nil { - log.Error("Error opening Mempool wal file", "error", err) - cmn.PanicSanity(err) + cmn.PanicSanity(errors.Wrap(err, "Error opening Mempool wal file")) } mem.wal = af } @@ -203,7 +211,7 @@ func (mem *Mempool) resCbNormal(req *abci.Request, res *abci.Response) { mem.txs.PushBack(memTx) } else { // ignore bad transaction - log.Info("Bad Transaction", "res", r) + mem.logger.Info("Bad Transaction", "res", r) // remove from cache (it might be good later) mem.cache.Remove(req.GetCheckTx().Tx) @@ -241,7 +249,7 @@ func (mem *Mempool) resCbRecheck(req *abci.Request, res *abci.Response) { if mem.recheckCursor == nil { // Done! atomic.StoreInt32(&mem.rechecking, 0) - log.Info("Done rechecking txs") + mem.logger.Info("Done rechecking txs") } default: // ignore other messages @@ -300,7 +308,7 @@ func (mem *Mempool) Update(height int, txs types.Txs) { // NOTE/XXX: in some apps a tx could be invalidated due to EndBlock, // so we really still do need to recheck, but this is for debugging if mem.config.Recheck && (mem.config.RecheckEmpty || len(txs) > 0) { - log.Info("Recheck txs", "numtxs", len(goodTxs)) + mem.logger.Info("Recheck txs", "numtxs", len(goodTxs)) mem.recheckTxs(goodTxs) // At this point, mem.txs are being rechecked. // mem.recheckCursor re-scans mem.txs and possibly removes some txs. diff --git a/mempool/mempool_test.go b/mempool/mempool_test.go index dd15493d0..a4ae6679e 100644 --- a/mempool/mempool_test.go +++ b/mempool/mempool_test.go @@ -8,6 +8,7 @@ import ( cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/proxy" "github.com/tendermint/tendermint/types" + "github.com/tendermint/tmlibs/log" ) func TestSerialReap(t *testing.T) { @@ -19,6 +20,7 @@ func TestSerialReap(t *testing.T) { appConnMem, _ := cc.NewABCIClient() appConnCon, _ := cc.NewABCIClient() mempool := NewMempool(config.Mempool, appConnMem) + mempool.SetLogger(log.TestingLogger()) deliverTxsRange := func(start, end int) { // Deliver some txs. diff --git a/mempool/reactor.go b/mempool/reactor.go index 169228982..842e11538 100644 --- a/mempool/reactor.go +++ b/mempool/reactor.go @@ -7,7 +7,7 @@ import ( "time" abci "github.com/tendermint/abci/types" - "github.com/tendermint/go-wire" + wire "github.com/tendermint/go-wire" "github.com/tendermint/tmlibs/clist" cfg "github.com/tendermint/tendermint/config" @@ -35,7 +35,7 @@ func NewMempoolReactor(config *cfg.MempoolConfig, mempool *Mempool) *MempoolReac config: config, Mempool: mempool, } - memR.BaseReactor = *p2p.NewBaseReactor(log, "MempoolReactor", memR) + memR.BaseReactor = *p2p.NewBaseReactor("MempoolReactor", memR) return memR } @@ -63,24 +63,24 @@ func (memR *MempoolReactor) RemovePeer(peer *p2p.Peer, reason interface{}) { func (memR *MempoolReactor) Receive(chID byte, src *p2p.Peer, msgBytes []byte) { _, msg, err := DecodeMessage(msgBytes) if err != nil { - log.Warn("Error decoding message", "error", err) + memR.Logger.Error("Error decoding message", "error", err) return } - log.Debug("Receive", "src", src, "chId", chID, "msg", msg) + memR.Logger.Debug("Receive", "src", src, "chId", chID, "msg", msg) switch msg := msg.(type) { case *TxMessage: err := memR.Mempool.CheckTx(msg.Tx, nil) if err != nil { // Bad, seen, or conflicting tx. - log.Info("Could not add tx", "tx", msg.Tx) + memR.Logger.Info("Could not add tx", "tx", msg.Tx) return } else { - log.Info("Added valid tx", "tx", msg.Tx) + memR.Logger.Info("Added valid tx", "tx", msg.Tx) } // broadcasting happens from go routines per peer default: - log.Warn(fmt.Sprintf("Unknown message type %v", reflect.TypeOf(msg))) + memR.Logger.Error(fmt.Sprintf("Unknown message type %v", reflect.TypeOf(msg))) } } diff --git a/node/log.go b/node/log.go deleted file mode 100644 index 946d963cf..000000000 --- a/node/log.go +++ /dev/null @@ -1,7 +0,0 @@ -package node - -import ( - "github.com/tendermint/tmlibs/logger" -) - -var log = logger.New("module", "node") diff --git a/node/node.go b/node/node.go index 04a6f3cdf..5d9e67844 100644 --- a/node/node.go +++ b/node/node.go @@ -28,6 +28,7 @@ import ( "github.com/tendermint/tendermint/version" cmn "github.com/tendermint/tmlibs/common" dbm "github.com/tendermint/tmlibs/db" + "github.com/tendermint/tmlibs/log" _ "net/http/pprof" ) @@ -57,15 +58,14 @@ type Node struct { txIndexer txindex.TxIndexer } -func NewNodeDefault(config *cfg.Config) *Node { +func NewNodeDefault(config *cfg.Config, logger log.Logger) *Node { // Get PrivValidator - privValidator := types.LoadOrGenPrivValidator(config.PrivValidatorFile()) + privValidator := types.LoadOrGenPrivValidator(config.PrivValidatorFile(), logger) return NewNode(config, privValidator, - proxy.DefaultClientCreator(config.ProxyApp, config.ABCI, config.DBDir())) + proxy.DefaultClientCreator(config.ProxyApp, config.ABCI, config.DBDir()), logger) } -func NewNode(config *cfg.Config, privValidator *types.PrivValidator, clientCreator proxy.ClientCreator) *Node { - +func NewNode(config *cfg.Config, privValidator *types.PrivValidator, clientCreator proxy.ClientCreator, logger log.Logger) *Node { // Get BlockStore blockStoreDB := dbm.NewDB("blockstore", config.DBBackend, config.DBDir()) blockStore := bc.NewBlockStore(blockStoreDB) @@ -73,6 +73,7 @@ func NewNode(config *cfg.Config, privValidator *types.PrivValidator, clientCreat // Get State stateDB := dbm.NewDB("state", config.DBBackend, config.DBDir()) state := sm.GetState(stateDB, config.GenesisFile()) + state.SetLogger(logger.With("module", "state")) // Create the proxyApp, which manages connections (consensus, mempool, query) // and sync tendermint and the app by replaying any necessary blocks @@ -83,6 +84,7 @@ func NewNode(config *cfg.Config, privValidator *types.PrivValidator, clientCreat // reload the state (it may have been updated by the handshake) state = sm.LoadState(stateDB) + state.SetLogger(logger.With("module", "state")) // Transaction indexing var txIndexer txindex.TxIndexer @@ -120,6 +122,7 @@ func NewNode(config *cfg.Config, privValidator *types.PrivValidator, clientCreat // Make MempoolReactor mempool := mempl.NewMempool(config.Mempool, proxyApp.Mempool()) + mempool.SetLogger(logger.With("module", "mempool")) mempoolReactor := mempl.NewMempoolReactor(config.Mempool, mempool) // Make ConsensusReactor @@ -178,7 +181,7 @@ func NewNode(config *cfg.Config, privValidator *types.PrivValidator, clientCreat if profileHost != "" { go func() { - log.Warn("Profile server", "error", http.ListenAndServe(profileHost, nil)) + logger.Error("Profile server", "error", http.ListenAndServe(profileHost, nil)) }() } @@ -200,15 +203,14 @@ func NewNode(config *cfg.Config, privValidator *types.PrivValidator, clientCreat proxyApp: proxyApp, txIndexer: txIndexer, } - node.BaseService = *cmn.NewBaseService(log, "Node", node) + node.BaseService = *cmn.NewBaseService(logger, "Node", node) return node } func (n *Node) OnStart() error { - // Create & add listener protocol, address := ProtocolAndAddress(n.config.P2P.ListenAddress) - l := p2p.NewDefaultListener(protocol, address, n.config.P2P.SkipUPNP) + l := p2p.NewDefaultListener(protocol, address, n.config.P2P.SkipUPNP, n.Logger.With("module", "p2p")) n.sw.AddListener(l) // Start the switch @@ -243,14 +245,14 @@ func (n *Node) OnStart() error { func (n *Node) OnStop() { n.BaseService.OnStop() - log.Notice("Stopping Node") + n.Logger.Info("Stopping Node") // TODO: gracefully disconnect from peers. n.sw.Stop() for _, l := range n.rpcListeners { - log.Info("Closing rpc listener", "listener", l) + n.Logger.Info("Closing rpc listener", "listener", l) if err := l.Close(); err != nil { - log.Error("Error closing listener", "listener", l, "error", err) + n.Logger.Error("Error closing listener", "listener", l, "error", err) } } } @@ -289,6 +291,7 @@ func (n *Node) ConfigureRPC() { rpccore.SetAddrBook(n.addrBook) rpccore.SetProxyAppQuery(n.proxyApp.Query()) rpccore.SetTxIndexer(n.txIndexer) + rpccore.SetLogger(n.Logger.With("module", "rpc")) } func (n *Node) startRPC() ([]net.Listener, error) { @@ -299,10 +302,12 @@ func (n *Node) startRPC() ([]net.Listener, error) { listeners := make([]net.Listener, len(listenAddrs)) for i, listenAddr := range listenAddrs { mux := http.NewServeMux() + rpcLogger := n.Logger.With("module", "rpcserver") wm := rpcserver.NewWebsocketManager(rpccore.Routes, n.evsw) + wm.SetLogger(rpcLogger) mux.HandleFunc("/websocket", wm.WebsocketHandler) - rpcserver.RegisterRPCFuncs(mux, rpccore.Routes) - listener, err := rpcserver.StartHTTPServer(listenAddr, mux) + rpcserver.RegisterRPCFuncs(mux, rpccore.Routes, rpcLogger) + listener, err := rpcserver.StartHTTPServer(listenAddr, mux, rpcLogger) if err != nil { return nil, err } diff --git a/node/node_test.go b/node/node_test.go index e00a67ecb..3c751af6e 100644 --- a/node/node_test.go +++ b/node/node_test.go @@ -5,15 +5,16 @@ import ( "time" cfg "github.com/tendermint/tendermint/config" + "github.com/tendermint/tmlibs/log" ) func TestNodeStartStop(t *testing.T) { config := cfg.ResetTestRoot("node_node_test") // Create & start node - n := NewNodeDefault(config) + n := NewNodeDefault(config, log.TestingLogger()) n.Start() - log.Notice("Started node", "nodeInfo", n.sw.NodeInfo()) + t.Logf("Started node %v", n.sw.NodeInfo()) // Wait a bit to initialize // TODO remove time.Sleep(), make asynchronous. diff --git a/p2p/addrbook.go b/p2p/addrbook.go index 3210273b7..1df0817ee 100644 --- a/p2p/addrbook.go +++ b/p2p/addrbook.go @@ -107,7 +107,7 @@ func NewAddrBook(filePath string, routabilityStrict bool) *AddrBook { routabilityStrict: routabilityStrict, } am.init() - am.BaseService = *cmn.NewBaseService(log, "AddrBook", am) + am.BaseService = *cmn.NewBaseService(nil, "AddrBook", am) return am } @@ -147,7 +147,7 @@ func (a *AddrBook) Wait() { func (a *AddrBook) AddOurAddress(addr *NetAddress) { a.mtx.Lock() defer a.mtx.Unlock() - log.Info("Add our address to book", "addr", addr) + a.Logger.Info("Add our address to book", "addr", addr) a.ourAddrs[addr.String()] = addr } @@ -163,7 +163,7 @@ func (a *AddrBook) OurAddresses() []*NetAddress { func (a *AddrBook) AddAddress(addr *NetAddress, src *NetAddress) { a.mtx.Lock() defer a.mtx.Unlock() - log.Info("Add address to book", "addr", addr, "src", src) + a.Logger.Info("Add address to book", "addr", addr, "src", src) a.addAddress(addr, src) } @@ -271,7 +271,7 @@ func (a *AddrBook) RemoveAddress(addr *NetAddress) { if ka == nil { return } - log.Info("Remove address from book", "addr", addr) + a.Logger.Info("Remove address from book", "addr", addr) a.removeFromAllBuckets(ka) } @@ -318,7 +318,7 @@ type addrBookJSON struct { } func (a *AddrBook) saveToFile(filePath string) { - log.Info("Saving AddrBook to file", "size", a.Size()) + a.Logger.Info("Saving AddrBook to file", "size", a.Size()) a.mtx.Lock() defer a.mtx.Unlock() @@ -335,12 +335,12 @@ func (a *AddrBook) saveToFile(filePath string) { jsonBytes, err := json.MarshalIndent(aJSON, "", "\t") if err != nil { - log.Error("Failed to save AddrBook to file", "err", err) + a.Logger.Error("Failed to save AddrBook to file", "err", err) return } err = cmn.WriteFileAtomic(filePath, jsonBytes, 0644) if err != nil { - log.Error("Failed to save AddrBook to file", "file", filePath, "error", err) + a.Logger.Error("Failed to save AddrBook to file", "file", filePath, "error", err) } } @@ -387,7 +387,7 @@ func (a *AddrBook) loadFromFile(filePath string) bool { // Save saves the book. func (a *AddrBook) Save() { - log.Info("Saving AddrBook to file", "size", a.Size()) + a.Logger.Info("Saving AddrBook to file", "size", a.Size()) a.saveToFile(a.filePath) } @@ -407,7 +407,7 @@ out: dumpAddressTicker.Stop() a.saveToFile(a.filePath) a.wg.Done() - log.Notice("Address handler done") + a.Logger.Info("Address handler done") } func (a *AddrBook) getBucket(bucketType byte, bucketIdx int) map[string]*knownAddress { @@ -427,7 +427,7 @@ func (a *AddrBook) getBucket(bucketType byte, bucketIdx int) map[string]*knownAd func (a *AddrBook) addToNewBucket(ka *knownAddress, bucketIdx int) bool { // Sanity check if ka.isOld() { - log.Warn(cmn.Fmt("Cannot add address already in old bucket to a new bucket: %v", ka)) + a.Logger.Error(cmn.Fmt("Cannot add address already in old bucket to a new bucket: %v", ka)) return false } @@ -441,7 +441,7 @@ func (a *AddrBook) addToNewBucket(ka *knownAddress, bucketIdx int) bool { // Enforce max addresses. if len(bucket) > newBucketSize { - log.Notice("new bucket is full, expiring old ") + a.Logger.Info("new bucket is full, expiring old ") a.expireNew(bucketIdx) } @@ -461,11 +461,11 @@ func (a *AddrBook) addToNewBucket(ka *knownAddress, bucketIdx int) bool { func (a *AddrBook) addToOldBucket(ka *knownAddress, bucketIdx int) bool { // Sanity check if ka.isNew() { - log.Warn(cmn.Fmt("Cannot add new address to old bucket: %v", ka)) + a.Logger.Error(cmn.Fmt("Cannot add new address to old bucket: %v", ka)) return false } if len(ka.Buckets) != 0 { - log.Warn(cmn.Fmt("Cannot add already old address to another old bucket: %v", ka)) + a.Logger.Error(cmn.Fmt("Cannot add already old address to another old bucket: %v", ka)) return false } @@ -496,7 +496,7 @@ func (a *AddrBook) addToOldBucket(ka *knownAddress, bucketIdx int) bool { func (a *AddrBook) removeFromBucket(ka *knownAddress, bucketType byte, bucketIdx int) { if ka.BucketType != bucketType { - log.Warn(cmn.Fmt("Bucket type mismatch: %v", ka)) + a.Logger.Error(cmn.Fmt("Bucket type mismatch: %v", ka)) return } bucket := a.getBucket(bucketType, bucketIdx) @@ -538,7 +538,7 @@ func (a *AddrBook) pickOldest(bucketType byte, bucketIdx int) *knownAddress { func (a *AddrBook) addAddress(addr, src *NetAddress) { if a.routabilityStrict && !addr.Routable() { - log.Warn(cmn.Fmt("Cannot add non-routable address %v", addr)) + a.Logger.Error(cmn.Fmt("Cannot add non-routable address %v", addr)) return } if _, ok := a.ourAddrs[addr.String()]; ok { @@ -569,7 +569,7 @@ func (a *AddrBook) addAddress(addr, src *NetAddress) { bucket := a.calcNewBucket(addr, src) a.addToNewBucket(ka, bucket) - log.Notice("Added new address", "address", addr, "total", a.size()) + a.Logger.Info("Added new address", "address", addr, "total", a.size()) } // Make space in the new buckets by expiring the really bad entries. @@ -578,7 +578,7 @@ func (a *AddrBook) expireNew(bucketIdx int) { for addrStr, ka := range a.addrNew[bucketIdx] { // If an entry is bad, throw it away if ka.isBad() { - log.Notice(cmn.Fmt("expiring bad address %v", addrStr)) + a.Logger.Info(cmn.Fmt("expiring bad address %v", addrStr)) a.removeFromBucket(ka, bucketTypeNew, bucketIdx) return } @@ -595,11 +595,11 @@ func (a *AddrBook) expireNew(bucketIdx int) { func (a *AddrBook) moveToOld(ka *knownAddress) { // Sanity check if ka.isOld() { - log.Warn(cmn.Fmt("Cannot promote address that is already old %v", ka)) + a.Logger.Error(cmn.Fmt("Cannot promote address that is already old %v", ka)) return } if len(ka.Buckets) == 0 { - log.Warn(cmn.Fmt("Cannot promote address that isn't in any new buckets %v", ka)) + a.Logger.Error(cmn.Fmt("Cannot promote address that isn't in any new buckets %v", ka)) return } @@ -624,13 +624,13 @@ func (a *AddrBook) moveToOld(ka *knownAddress) { if !added { added := a.addToNewBucket(oldest, freedBucket) if !added { - log.Warn(cmn.Fmt("Could not migrate oldest %v to freedBucket %v", oldest, freedBucket)) + a.Logger.Error(cmn.Fmt("Could not migrate oldest %v to freedBucket %v", oldest, freedBucket)) } } // Finally, add to bucket again. added = a.addToOldBucket(ka, oldBucketIdx) if !added { - log.Warn(cmn.Fmt("Could not re-add ka %v to oldBucketIdx %v", ka, oldBucketIdx)) + a.Logger.Error(cmn.Fmt("Could not re-add ka %v to oldBucketIdx %v", ka, oldBucketIdx)) } } } @@ -778,7 +778,8 @@ func (ka *knownAddress) markGood() { func (ka *knownAddress) addBucketRef(bucketIdx int) int { for _, bucket := range ka.Buckets { if bucket == bucketIdx { - log.Warn(cmn.Fmt("Bucket already exists in ka.Buckets: %v", ka)) + // TODO refactor to return error? + // log.Warn(Fmt("Bucket already exists in ka.Buckets: %v", ka)) return -1 } } @@ -794,7 +795,8 @@ func (ka *knownAddress) removeBucketRef(bucketIdx int) int { } } if len(buckets) != len(ka.Buckets)-1 { - log.Warn(cmn.Fmt("bucketIdx not found in ka.Buckets: %v", ka)) + // TODO refactor to return error? + // log.Warn(Fmt("bucketIdx not found in ka.Buckets: %v", ka)) return -1 } ka.Buckets = buckets diff --git a/p2p/addrbook_test.go b/p2p/addrbook_test.go index 16aea8ef9..9b83be180 100644 --- a/p2p/addrbook_test.go +++ b/p2p/addrbook_test.go @@ -7,6 +7,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/tendermint/tmlibs/log" ) func createTempFileName(prefix string) string { @@ -27,9 +28,11 @@ func TestAddrBookSaveLoad(t *testing.T) { // 0 addresses book := NewAddrBook(fname, true) + book.SetLogger(log.TestingLogger()) book.saveToFile(fname) book = NewAddrBook(fname, true) + book.SetLogger(log.TestingLogger()) book.loadFromFile(fname) assert.Zero(t, book.Size()) @@ -45,6 +48,7 @@ func TestAddrBookSaveLoad(t *testing.T) { book.saveToFile(fname) book = NewAddrBook(fname, true) + book.SetLogger(log.TestingLogger()) book.loadFromFile(fname) assert.Equal(t, 100, book.Size()) @@ -56,6 +60,7 @@ func TestAddrBookLookup(t *testing.T) { randAddrs := randNetAddressPairs(t, 100) book := NewAddrBook(fname, true) + book.SetLogger(log.TestingLogger()) for _, addrSrc := range randAddrs { addr := addrSrc.addr src := addrSrc.src @@ -76,6 +81,7 @@ func TestAddrBookPromoteToOld(t *testing.T) { randAddrs := randNetAddressPairs(t, 100) book := NewAddrBook(fname, true) + book.SetLogger(log.TestingLogger()) for _, addrSrc := range randAddrs { book.AddAddress(addrSrc.addr, addrSrc.src) } @@ -106,6 +112,7 @@ func TestAddrBookHandlesDuplicates(t *testing.T) { fname := createTempFileName("addrbook_test") book := NewAddrBook(fname, true) + book.SetLogger(log.TestingLogger()) randAddrs := randNetAddressPairs(t, 100) @@ -152,6 +159,7 @@ func randIPv4Address(t *testing.T) *NetAddress { func TestAddrBookRemoveAddress(t *testing.T) { fname := createTempFileName("addrbook_test") book := NewAddrBook(fname, true) + book.SetLogger(log.TestingLogger()) addr := randIPv4Address(t) book.AddAddress(addr, addr) diff --git a/p2p/connection.go b/p2p/connection.go index b8b000553..36f15abb7 100644 --- a/p2p/connection.go +++ b/p2p/connection.go @@ -140,7 +140,7 @@ func NewMConnectionWithConfig(conn net.Conn, chDescs []*ChannelDescriptor, onRec mconn.channels = channels mconn.channelsIdx = channelsIdx - mconn.BaseService = *cmn.NewBaseService(log, "MConnection", mconn) + mconn.BaseService = *cmn.NewBaseService(nil, "MConnection", mconn) return mconn } @@ -177,10 +177,10 @@ func (c *MConnection) String() string { } func (c *MConnection) flush() { - log.Debug("Flush", "conn", c) + c.Logger.Debug("Flush", "conn", c) err := c.bufWriter.Flush() if err != nil { - log.Warn("MConnection flush failed", "error", err) + c.Logger.Error("MConnection flush failed", "error", err) } } @@ -208,12 +208,12 @@ func (c *MConnection) Send(chID byte, msg interface{}) bool { return false } - log.Debug("Send", "channel", chID, "conn", c, "msg", msg) //, "bytes", wire.BinaryBytes(msg)) + c.Logger.Debug("Send", "channel", chID, "conn", c, "msg", msg) //, "bytes", wire.BinaryBytes(msg)) // Send message to channel. channel, ok := c.channelsIdx[chID] if !ok { - log.Error(cmn.Fmt("Cannot send bytes, unknown channel %X", chID)) + c.Logger.Error(cmn.Fmt("Cannot send bytes, unknown channel %X", chID)) return false } @@ -225,7 +225,7 @@ func (c *MConnection) Send(chID byte, msg interface{}) bool { default: } } else { - log.Warn("Send failed", "channel", chID, "conn", c, "msg", msg) + c.Logger.Error("Send failed", "channel", chID, "conn", c, "msg", msg) } return success } @@ -237,12 +237,12 @@ func (c *MConnection) TrySend(chID byte, msg interface{}) bool { return false } - log.Debug("TrySend", "channel", chID, "conn", c, "msg", msg) + c.Logger.Debug("TrySend", "channel", chID, "conn", c, "msg", msg) // Send message to channel. channel, ok := c.channelsIdx[chID] if !ok { - log.Error(cmn.Fmt("Cannot send bytes, unknown channel %X", chID)) + c.Logger.Error(cmn.Fmt("Cannot send bytes, unknown channel %X", chID)) return false } @@ -267,7 +267,7 @@ func (c *MConnection) CanSend(chID byte) bool { channel, ok := c.channelsIdx[chID] if !ok { - log.Error(cmn.Fmt("Unknown channel %X", chID)) + c.Logger.Error(cmn.Fmt("Unknown channel %X", chID)) return false } return channel.canSend() @@ -291,12 +291,12 @@ FOR_LOOP: channel.updateStats() } case <-c.pingTimer.Ch: - log.Debug("Send Ping") + c.Logger.Debug("Send Ping") wire.WriteByte(packetTypePing, c.bufWriter, &n, &err) c.sendMonitor.Update(int(n)) c.flush() case <-c.pong: - log.Debug("Send Pong") + c.Logger.Debug("Send Pong") wire.WriteByte(packetTypePong, c.bufWriter, &n, &err) c.sendMonitor.Update(int(n)) c.flush() @@ -318,7 +318,7 @@ FOR_LOOP: break FOR_LOOP } if err != nil { - log.Warn("Connection failed @ sendRoutine", "conn", c, "error", err) + c.Logger.Error("Connection failed @ sendRoutine", "conn", c, "error", err) c.stopForError(err) break FOR_LOOP } @@ -367,13 +367,13 @@ func (c *MConnection) sendMsgPacket() bool { if leastChannel == nil { return true } else { - // log.Info("Found a msgPacket to send") + // c.Logger.Info("Found a msgPacket to send") } // Make & send a msgPacket from this channel n, err := leastChannel.writeMsgPacketTo(c.bufWriter) if err != nil { - log.Warn("Failed to write msgPacket", "error", err) + c.Logger.Error("Failed to write msgPacket", "error", err) c.stopForError(err) return true } @@ -415,7 +415,7 @@ FOR_LOOP: c.recvMonitor.Update(int(n)) if err != nil { if c.IsRunning() { - log.Warn("Connection failed @ recvRoutine (reading byte)", "conn", c, "error", err) + c.Logger.Error("Connection failed @ recvRoutine (reading byte)", "conn", c, "error", err) c.stopForError(err) } break FOR_LOOP @@ -425,18 +425,18 @@ FOR_LOOP: switch pktType { case packetTypePing: // TODO: prevent abuse, as they cause flush()'s. - log.Debug("Receive Ping") + c.Logger.Debug("Receive Ping") c.pong <- struct{}{} case packetTypePong: // do nothing - log.Debug("Receive Pong") + c.Logger.Debug("Receive Pong") case packetTypeMsg: pkt, n, err := msgPacket{}, int(0), error(nil) wire.ReadBinaryPtr(&pkt, c.bufReader, maxMsgPacketTotalSize, &n, &err) c.recvMonitor.Update(int(n)) if err != nil { if c.IsRunning() { - log.Warn("Connection failed @ recvRoutine", "conn", c, "error", err) + c.Logger.Error("Connection failed @ recvRoutine", "conn", c, "error", err) c.stopForError(err) } break FOR_LOOP @@ -448,13 +448,13 @@ FOR_LOOP: msgBytes, err := channel.recvMsgPacket(pkt) if err != nil { if c.IsRunning() { - log.Warn("Connection failed @ recvRoutine", "conn", c, "error", err) + c.Logger.Error("Connection failed @ recvRoutine", "conn", c, "error", err) c.stopForError(err) } break FOR_LOOP } if msgBytes != nil { - log.Debug("Received bytes", "chID", pkt.ChannelID, "msgBytes", msgBytes) + c.Logger.Debug("Received bytes", "chID", pkt.ChannelID, "msgBytes", msgBytes) c.onReceive(pkt.ChannelID, msgBytes) } default: @@ -626,7 +626,7 @@ func (ch *Channel) nextMsgPacket() msgPacket { // Not goroutine-safe func (ch *Channel) writeMsgPacketTo(w io.Writer) (n int, err error) { packet := ch.nextMsgPacket() - log.Debug("Write Msg Packet", "conn", ch.conn, "packet", packet) + // log.Debug("Write Msg Packet", "conn", ch.conn, "packet", packet) wire.WriteByte(packetTypeMsg, w, &n, &err) wire.WriteBinary(packet, w, &n, &err) if err == nil { diff --git a/p2p/connection_test.go b/p2p/connection_test.go index 993d2d737..71c3d64c2 100644 --- a/p2p/connection_test.go +++ b/p2p/connection_test.go @@ -8,6 +8,7 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" p2p "github.com/tendermint/tendermint/p2p" + "github.com/tendermint/tmlibs/log" ) func createMConnection(conn net.Conn) *p2p.MConnection { @@ -15,12 +16,16 @@ func createMConnection(conn net.Conn) *p2p.MConnection { } onError := func(r interface{}) { } - return createMConnectionWithCallbacks(conn, onReceive, onError) + c := createMConnectionWithCallbacks(conn, onReceive, onError) + c.SetLogger(log.TestingLogger()) + return c } func createMConnectionWithCallbacks(conn net.Conn, onReceive func(chID byte, msgBytes []byte), onError func(r interface{})) *p2p.MConnection { chDescs := []*p2p.ChannelDescriptor{&p2p.ChannelDescriptor{ID: 0x01, Priority: 1, SendQueueCapacity: 1}} - return p2p.NewMConnection(conn, chDescs, onReceive, onError) + c := p2p.NewMConnection(conn, chDescs, onReceive, onError) + c.SetLogger(log.TestingLogger()) + return c } func TestMConnectionSend(t *testing.T) { diff --git a/p2p/glide.lock b/p2p/glide.lock new file mode 100644 index 000000000..e396152cb --- /dev/null +++ b/p2p/glide.lock @@ -0,0 +1,153 @@ +hash: 56a5590512e71b5bae4af7bd6c5e352008ad5725a8595c3e128cd18042f95b4c +updated: 2017-05-02T13:43:02.638937348Z +imports: +- name: github.com/btcsuite/btcd + version: 4b348c1d33373d672edd83fc576892d0e46686d2 + subpackages: + - btcec +- name: github.com/ebuchman/fail-test + version: 95f809107225be108efcf10a3509e4ea6ceef3c4 +- name: github.com/fsnotify/fsnotify + version: 4da3e2cfbabc9f751898f250b49f2439785783a1 +- name: github.com/go-kit/kit + version: 8a2988aa81f699fc1e647c3c9dddce0113ef1bfb + subpackages: + - log + - log/level + - log/term +- name: github.com/go-logfmt/logfmt + version: 390ab7935ee28ec6b286364bba9b4dd6410cb3d5 +- name: github.com/go-stack/stack + version: 100eb0c0a9c5b306ca2fb4f165df21d80ada4b82 +- name: github.com/gogo/protobuf + version: 100ba4e885062801d56799d78530b73b178a78f3 + subpackages: + - proto +- name: github.com/golang/protobuf + version: 2bba0603135d7d7f5cb73b2125beeda19c09f4ef + subpackages: + - proto +- name: github.com/gorilla/websocket + version: 3ab3a8b8831546bd18fd182c20687ca853b2bb13 +- name: github.com/hashicorp/hcl + version: 7fa7fff964d035e8a162cce3a164b3ad02ad651b + subpackages: + - hcl/ast + - hcl/parser + - hcl/scanner + - hcl/strconv + - hcl/token + - json/parser + - json/scanner + - json/token +- name: github.com/kr/logfmt + version: b84e30acd515aadc4b783ad4ff83aff3299bdfe0 +- name: github.com/magiconair/properties + version: 51463bfca2576e06c62a8504b5c0f06d61312647 +- name: github.com/mattn/go-colorable + version: ded68f7a9561c023e790de24279db7ebf473ea80 +- name: github.com/mattn/go-isatty + version: fc9e8d8ef48496124e79ae0df75490096eccf6fe +- name: github.com/mitchellh/mapstructure + version: cc8532a8e9a55ea36402aa21efdf403a60d34096 +- name: github.com/pelletier/go-buffruneio + version: c37440a7cf42ac63b919c752ca73a85067e05992 +- name: github.com/pelletier/go-toml + version: fe206efb84b2bc8e8cfafe6b4c1826622be969e3 +- name: github.com/pkg/errors + version: 645ef00459ed84a119197bfb8d8205042c6df63d +- name: github.com/spf13/afero + version: 9be650865eab0c12963d8753212f4f9c66cdcf12 + subpackages: + - mem +- name: github.com/spf13/cast + version: acbeb36b902d72a7a4c18e8f3241075e7ab763e4 +- name: github.com/spf13/cobra + version: 10f6b9d7e1631a54ad07c5c0fb71c28a1abfd3c2 +- name: github.com/spf13/jwalterweatherman + version: fa7ca7e836cf3a8bb4ebf799f472c12d7e903d66 +- name: github.com/spf13/pflag + version: 2300d0f8576fe575f71aaa5b9bbe4e1b0dc2eb51 +- name: github.com/spf13/viper + version: 0967fc9aceab2ce9da34061253ac10fb99bba5b2 +- name: github.com/stretchr/testify + version: 69483b4bd14f5845b5a1e55bca19e954e827f1d0 + subpackages: + - assert + - require +- name: github.com/tendermint/abci + version: 8d8e35ae537538c9cf6808be3ca9dd7dab81b7f6 + subpackages: + - client + - example/dummy + - types +- name: github.com/tendermint/ed25519 + version: 1f52c6f8b8a5c7908aff4497c186af344b428925 + subpackages: + - edwards25519 + - extra25519 +- name: github.com/tendermint/go-crypto + version: 197a2b270fd94ee03824b158e738fce62862d0b8 +- name: github.com/tendermint/go-wire + version: b53add0b622662731985485f3a19be7f684660b8 + subpackages: + - data +- name: github.com/tendermint/log15 + version: ae0f3d6450da9eac7074b439c8e1c3cabf0d5ce6 + subpackages: + - term +- name: github.com/tendermint/tmlibs + version: 9687e4202662c11add147906faf5503af519b4ef + subpackages: + - autofile + - clist + - common + - db + - events + - flowrate + - log + - logger + - merkle +- name: golang.org/x/crypto + version: 96846453c37f0876340a66a47f3f75b1f3a6cd2d + subpackages: + - curve25519 + - nacl/box + - nacl/secretbox + - openpgp/armor + - openpgp/errors + - poly1305 + - ripemd160 + - salsa20/salsa +- name: golang.org/x/net + version: c8c74377599bd978aee1cf3b9b63a8634051cec2 + subpackages: + - context +- name: golang.org/x/sys + version: ea9bcade75cb975a0b9738936568ab388b845617 + subpackages: + - unix +- name: golang.org/x/text + version: 19e3104b43db45fca0303f489a9536087b184802 + subpackages: + - transform + - unicode/norm +- name: google.golang.org/grpc + version: 6914ab1e338c92da4218a23d27fcd03d0ad78d46 +- name: gopkg.in/yaml.v2 + version: cd8b52f8269e0feb286dfeef29f8fe4d5b397e0b +testImports: +- name: github.com/davecgh/go-spew + version: 6d212800a42e8ab5c146b8ace3490ee17e5225f9 + subpackages: + - spew +- name: github.com/pmezard/go-difflib + version: d8ed2627bdf02c080bf22230dbb337003b7aba2d + subpackages: + - difflib +- name: github.com/tendermint/merkleeyes + version: d0aa363fd4e015e509038c3a0ec493bc62ee0b8a + subpackages: + - app + - iavl + - testutil diff --git a/p2p/listener.go b/p2p/listener.go index 9dc9a7e48..d31f0de83 100644 --- a/p2p/listener.go +++ b/p2p/listener.go @@ -8,6 +8,7 @@ import ( "github.com/tendermint/tendermint/p2p/upnp" cmn "github.com/tendermint/tmlibs/common" + "github.com/tendermint/tmlibs/log" ) type Listener interface { @@ -47,7 +48,7 @@ func splitHostPort(addr string) (host string, port int) { } // skipUPNP: If true, does not try getUPNPExternalAddress() -func NewDefaultListener(protocol string, lAddr string, skipUPNP bool) Listener { +func NewDefaultListener(protocol string, lAddr string, skipUPNP bool, logger log.Logger) Listener { // Local listen IP & port lAddrIP, lAddrPort := splitHostPort(lAddr) @@ -67,7 +68,7 @@ func NewDefaultListener(protocol string, lAddr string, skipUPNP bool) Listener { } // Actual listener local IP & port listenerIP, listenerPort := splitHostPort(listener.Addr().String()) - log.Info("Local listener", "ip", listenerIP, "port", listenerPort) + logger.Info("Local listener", "ip", listenerIP, "port", listenerPort) // Determine internal address... var intAddr *NetAddress @@ -81,7 +82,7 @@ func NewDefaultListener(protocol string, lAddr string, skipUPNP bool) Listener { if !skipUPNP { // If the lAddrIP is INADDR_ANY, try UPnP if lAddrIP == "" || lAddrIP == "0.0.0.0" { - extAddr = getUPNPExternalAddress(lAddrPort, listenerPort) + extAddr = getUPNPExternalAddress(lAddrPort, listenerPort, logger) } } // Otherwise just use the local address... @@ -98,7 +99,7 @@ func NewDefaultListener(protocol string, lAddr string, skipUPNP bool) Listener { extAddr: extAddr, connections: make(chan net.Conn, numBufferedConnections), } - dl.BaseService = *cmn.NewBaseService(log, "DefaultListener", dl) + dl.BaseService = *cmn.NewBaseService(logger, "DefaultListener", dl) dl.Start() // Started upon construction return dl } @@ -166,17 +167,17 @@ func (l *DefaultListener) String() string { /* external address helpers */ // UPNP external address discovery & port mapping -func getUPNPExternalAddress(externalPort, internalPort int) *NetAddress { - log.Info("Getting UPNP external address") +func getUPNPExternalAddress(externalPort, internalPort int, logger log.Logger) *NetAddress { + logger.Info("Getting UPNP external address") nat, err := upnp.Discover() if err != nil { - log.Info("Could not perform UPNP discover", "error", err) + logger.Info("Could not perform UPNP discover", "error", err) return nil } ext, err := nat.GetExternalAddress() if err != nil { - log.Info("Could not get UPNP external address", "error", err) + logger.Info("Could not get UPNP external address", "error", err) return nil } @@ -187,11 +188,11 @@ func getUPNPExternalAddress(externalPort, internalPort int) *NetAddress { externalPort, err = nat.AddPortMapping("tcp", externalPort, internalPort, "tendermint", 0) if err != nil { - log.Info("Could not add UPNP port mapping", "error", err) + logger.Info("Could not add UPNP port mapping", "error", err) return nil } - log.Info("Got UPNP external address", "address", ext) + logger.Info("Got UPNP external address", "address", ext) return NewNetAddressIPPort(ext, uint16(externalPort)) } diff --git a/p2p/listener_test.go b/p2p/listener_test.go index 0f8a54946..c3d33a9ae 100644 --- a/p2p/listener_test.go +++ b/p2p/listener_test.go @@ -3,11 +3,13 @@ package p2p import ( "bytes" "testing" + + "github.com/tendermint/tmlibs/log" ) func TestListener(t *testing.T) { // Create a listener - l := NewDefaultListener("tcp", ":8001", true) + l := NewDefaultListener("tcp", ":8001", true, log.TestingLogger()) // Dial the listener lAddr := l.ExternalAddress() diff --git a/p2p/log.go b/p2p/log.go deleted file mode 100644 index af3203409..000000000 --- a/p2p/log.go +++ /dev/null @@ -1,7 +0,0 @@ -package p2p - -import ( - "github.com/tendermint/tmlibs/logger" -) - -var log = logger.New("module", "p2p") diff --git a/p2p/peer.go b/p2p/peer.go index a1a37a2ae..51a4e1189 100644 --- a/p2p/peer.go +++ b/p2p/peer.go @@ -115,7 +115,7 @@ func newPeerFromConnAndConfig(rawConn net.Conn, outbound bool, reactorsByCh map[ p.mconn = createMConnection(conn, p, reactorsByCh, chDescs, onPeerError, config.MConfig) - p.BaseService = *cmn.NewBaseService(log, "Peer", p) + p.BaseService = *cmn.NewBaseService(nil, "Peer", p) return p, nil } @@ -156,7 +156,7 @@ func (p *Peer) HandshakeTimeout(ourNodeInfo *NodeInfo, timeout time.Duration) er func() { var n int wire.ReadBinary(peerNodeInfo, p.conn, maxNodeInfoSize, &n, &err2) - log.Notice("Peer handshake", "peerNodeInfo", peerNodeInfo) + p.Logger.Info("Peer handshake", "peerNodeInfo", peerNodeInfo) }) if err1 != nil { return errors.Wrap(err1, "Error during handshake/write") @@ -279,10 +279,10 @@ func (p *Peer) Get(key string) interface{} { } func dial(addr *NetAddress, config *PeerConfig) (net.Conn, error) { - log.Info("Dialing address", "address", addr) + // log.Info("Dialing address", "address", addr) conn, err := addr.DialTimeout(config.DialTimeout * time.Second) if err != nil { - log.Info("Failed dialing address", "address", addr, "error", err) + // log.Info("Failed dialing address", "address", addr, "error", err) return nil, err } return conn, nil diff --git a/p2p/pex_reactor.go b/p2p/pex_reactor.go index 03a383c85..269a8d006 100644 --- a/p2p/pex_reactor.go +++ b/p2p/pex_reactor.go @@ -7,8 +7,8 @@ import ( "reflect" "time" - cmn "github.com/tendermint/tmlibs/common" wire "github.com/tendermint/go-wire" + cmn "github.com/tendermint/tmlibs/common" ) const ( @@ -61,7 +61,7 @@ func NewPEXReactor(b *AddrBook) *PEXReactor { msgCountByPeer: cmn.NewCMap(), maxMsgCountByPeer: defaultMaxMsgCountByPeer, } - r.BaseReactor = *NewBaseReactor(log, "PEXReactor", r) + r.BaseReactor = *NewBaseReactor("PEXReactor", r) return r } @@ -105,7 +105,7 @@ func (r *PEXReactor) AddPeer(p *Peer) { addr, err := NewNetAddressString(p.ListenAddr) if err != nil { // this should never happen - log.Error("Error in AddPeer: invalid peer address", "addr", p.ListenAddr, "error", err) + r.Logger.Error("Error in AddPeer: invalid peer address", "addr", p.ListenAddr, "error", err) return } r.book.AddAddress(addr, addr) @@ -125,17 +125,17 @@ func (r *PEXReactor) Receive(chID byte, src *Peer, msgBytes []byte) { r.IncrementMsgCountForPeer(srcAddrStr) if r.ReachedMaxMsgCountForPeer(srcAddrStr) { - log.Warn("Maximum number of messages reached for peer", "peer", srcAddrStr) + r.Logger.Error("Maximum number of messages reached for peer", "peer", srcAddrStr) // TODO remove src from peers? return } _, msg, err := DecodeMessage(msgBytes) if err != nil { - log.Warn("Error decoding message", "error", err) + r.Logger.Error("Error decoding message", "error", err) return } - log.Notice("Received message", "msg", msg) + r.Logger.Info("Received message", "msg", msg) switch msg := msg.(type) { case *pexRequestMessage: @@ -150,7 +150,7 @@ func (r *PEXReactor) Receive(chID byte, src *Peer, msgBytes []byte) { } } default: - log.Warn(fmt.Sprintf("Unknown message type %v", reflect.TypeOf(msg))) + r.Logger.Error(fmt.Sprintf("Unknown message type %v", reflect.TypeOf(msg))) } } @@ -230,7 +230,7 @@ func (r *PEXReactor) ensurePeersRoutine() { func (r *PEXReactor) ensurePeers() { numOutPeers, _, numDialing := r.Switch.NumPeers() numToDial := minNumOutboundPeers - (numOutPeers + numDialing) - log.Info("Ensure peers", "numOutPeers", numOutPeers, "numDialing", numDialing, "numToDial", numToDial) + r.Logger.Info("Ensure peers", "numOutPeers", numOutPeers, "numDialing", numDialing, "numToDial", numToDial) if numToDial <= 0 { return } @@ -257,13 +257,13 @@ func (r *PEXReactor) ensurePeers() { alreadyDialing := r.Switch.IsDialing(try) alreadyConnected := r.Switch.Peers().Has(try.IP.String()) if alreadySelected || alreadyDialing || alreadyConnected { - // log.Info("Cannot dial address", "addr", try, + // r.Logger.Info("Cannot dial address", "addr", try, // "alreadySelected", alreadySelected, // "alreadyDialing", alreadyDialing, // "alreadyConnected", alreadyConnected) continue } else { - log.Info("Will dial address", "addr", try) + r.Logger.Info("Will dial address", "addr", try) picked = try break } @@ -289,7 +289,7 @@ func (r *PEXReactor) ensurePeers() { if peers := r.Switch.Peers().List(); len(peers) > 0 { i := rand.Int() % len(peers) peer := peers[i] - log.Info("No addresses to dial. Sending pexRequest to random peer", "peer", peer) + r.Logger.Info("No addresses to dial. Sending pexRequest to random peer", "peer", peer) r.RequestPEX(peer) } } diff --git a/p2p/pex_reactor_test.go b/p2p/pex_reactor_test.go index ef2629027..7e69ace35 100644 --- a/p2p/pex_reactor_test.go +++ b/p2p/pex_reactor_test.go @@ -11,6 +11,7 @@ import ( "github.com/stretchr/testify/require" wire "github.com/tendermint/go-wire" cmn "github.com/tendermint/tmlibs/common" + "github.com/tendermint/tmlibs/log" ) func TestPEXReactorBasic(t *testing.T) { @@ -20,8 +21,10 @@ func TestPEXReactorBasic(t *testing.T) { require.Nil(err) defer os.RemoveAll(dir) book := NewAddrBook(dir+"addrbook.json", true) + book.SetLogger(log.TestingLogger()) r := NewPEXReactor(book) + r.SetLogger(log.TestingLogger()) assert.NotNil(r) assert.NotEmpty(r.GetChannels()) @@ -34,8 +37,10 @@ func TestPEXReactorAddRemovePeer(t *testing.T) { require.Nil(err) defer os.RemoveAll(dir) book := NewAddrBook(dir+"addrbook.json", true) + book.SetLogger(log.TestingLogger()) r := NewPEXReactor(book) + r.SetLogger(log.TestingLogger()) size := book.Size() peer := createRandomPeer(false) @@ -65,11 +70,13 @@ func TestPEXReactorRunning(t *testing.T) { require.Nil(err) defer os.RemoveAll(dir) book := NewAddrBook(dir+"addrbook.json", false) + book.SetLogger(log.TestingLogger()) // create switches for i := 0; i < N; i++ { switches[i] = makeSwitch(config, i, "127.0.0.1", "123.123.123", func(i int, sw *Switch) *Switch { r := NewPEXReactor(book) + r.SetLogger(log.TestingLogger()) r.SetEnsurePeersPeriod(250 * time.Millisecond) sw.AddReactor("pex", r) return sw @@ -80,7 +87,7 @@ func TestPEXReactorRunning(t *testing.T) { for _, s := range switches { addr, _ := NewNetAddressString(s.NodeInfo().ListenAddr) book.AddAddress(addr, addr) - s.AddListener(NewDefaultListener("tcp", s.NodeInfo().ListenAddr, true)) + s.AddListener(NewDefaultListener("tcp", s.NodeInfo().ListenAddr, true, log.TestingLogger())) } // start switches @@ -112,8 +119,10 @@ func TestPEXReactorReceive(t *testing.T) { require.Nil(err) defer os.RemoveAll(dir) book := NewAddrBook(dir+"addrbook.json", true) + book.SetLogger(log.TestingLogger()) r := NewPEXReactor(book) + r.SetLogger(log.TestingLogger()) peer := createRandomPeer(false) @@ -135,8 +144,10 @@ func TestPEXReactorAbuseFromPeer(t *testing.T) { require.Nil(err) defer os.RemoveAll(dir) book := NewAddrBook(dir+"addrbook.json", true) + book.SetLogger(log.TestingLogger()) r := NewPEXReactor(book) + r.SetLogger(log.TestingLogger()) r.SetMaxMsgCountByPeer(5) peer := createRandomPeer(false) diff --git a/p2p/switch.go b/p2p/switch.go index 9fe001eff..cab446f29 100644 --- a/p2p/switch.go +++ b/p2p/switch.go @@ -8,7 +8,6 @@ import ( "time" crypto "github.com/tendermint/go-crypto" - "github.com/tendermint/log15" cfg "github.com/tendermint/tendermint/config" cmn "github.com/tendermint/tmlibs/common" ) @@ -35,9 +34,9 @@ type BaseReactor struct { Switch *Switch } -func NewBaseReactor(log log15.Logger, name string, impl Reactor) *BaseReactor { +func NewBaseReactor(name string, impl Reactor) *BaseReactor { return &BaseReactor{ - BaseService: *cmn.NewBaseService(log, name, impl), + BaseService: *cmn.NewBaseService(nil, name, impl), Switch: nil, } } @@ -92,7 +91,7 @@ func NewSwitch(config *cfg.P2PConfig) *Switch { dialing: cmn.NewCMap(), nodeInfo: nil, } - sw.BaseService = *cmn.NewBaseService(log, "P2P Switch", sw) + sw.BaseService = *cmn.NewBaseService(nil, "P2P Switch", sw) return sw } @@ -225,7 +224,7 @@ func (sw *Switch) AddPeer(peer *Peer) error { // Add the peer to .peers // ignore if duplicate or if we already have too many for that IP range if err := sw.peers.Add(peer); err != nil { - log.Notice("Ignoring peer", "error", err, "peer", peer) + sw.Logger.Info("Ignoring peer", "error", err, "peer", peer) peer.Stop() return err } @@ -235,7 +234,7 @@ func (sw *Switch) AddPeer(peer *Peer) error { sw.startInitPeer(peer) } - log.Notice("Added peer", "peer", peer) + sw.Logger.Info("Added peer", "peer", peer) return nil } @@ -306,10 +305,10 @@ func (sw *Switch) DialSeeds(addrBook *AddrBook, seeds []string) error { func (sw *Switch) dialSeed(addr *NetAddress) { peer, err := sw.DialPeerWithAddress(addr, true) if err != nil { - log.Error("Error dialing seed", "error", err) + sw.Logger.Error("Error dialing seed", "error", err) return } else { - log.Notice("Connected to seed", "peer", peer) + sw.Logger.Info("Connected to seed", "peer", peer) } } @@ -319,7 +318,7 @@ func (sw *Switch) DialPeerWithAddress(addr *NetAddress, persistent bool) (*Peer, peer, err := newOutboundPeerWithConfig(addr, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey, sw.peerConfig) if err != nil { - log.Info("Failed dialing peer", "address", addr, "error", err) + sw.Logger.Info("Failed dialing peer", "address", addr, "error", err) return nil, err } if persistent { @@ -327,11 +326,11 @@ func (sw *Switch) DialPeerWithAddress(addr *NetAddress, persistent bool) (*Peer, } err = sw.AddPeer(peer) if err != nil { - log.Info("Failed adding peer", "address", addr, "error", err) + sw.Logger.Info("Failed adding peer", "address", addr, "error", err) peer.CloseConn() return nil, err } - log.Notice("Dialed and added peer", "address", addr, "peer", peer) + sw.Logger.Info("Dialed and added peer", "address", addr, "peer", peer) return peer, nil } @@ -345,7 +344,7 @@ func (sw *Switch) IsDialing(addr *NetAddress) bool { // NOTE: Broadcast uses goroutines, so order of broadcast may not be preserved. func (sw *Switch) Broadcast(chID byte, msg interface{}) chan bool { successChan := make(chan bool, len(sw.peers.List())) - log.Debug("Broadcast", "channel", chID, "msg", msg) + sw.Logger.Debug("Broadcast", "channel", chID, "msg", msg) for _, peer := range sw.peers.List() { go func(peer *Peer) { success := peer.Send(chID, msg) @@ -377,12 +376,12 @@ func (sw *Switch) Peers() IPeerSet { // TODO: make record depending on reason. func (sw *Switch) StopPeerForError(peer *Peer, reason interface{}) { addr := NewNetAddress(peer.Addr()) - log.Notice("Stopping peer for error", "peer", peer, "error", reason) + sw.Logger.Info("Stopping peer for error", "peer", peer, "error", reason) sw.stopAndRemovePeer(peer, reason) if peer.IsPersistent() { go func() { - log.Notice("Reconnecting to peer", "peer", peer) + sw.Logger.Info("Reconnecting to peer", "peer", peer) for i := 1; i < reconnectAttempts; i++ { if !sw.IsRunning() { return @@ -391,15 +390,15 @@ func (sw *Switch) StopPeerForError(peer *Peer, reason interface{}) { peer, err := sw.DialPeerWithAddress(addr, true) if err != nil { if i == reconnectAttempts { - log.Notice("Error reconnecting to peer. Giving up", "tries", i, "error", err) + sw.Logger.Info("Error reconnecting to peer. Giving up", "tries", i, "error", err) return } - log.Notice("Error reconnecting to peer. Trying again", "tries", i, "error", err) + sw.Logger.Info("Error reconnecting to peer. Trying again", "tries", i, "error", err) time.Sleep(reconnectInterval) continue } - log.Notice("Reconnected to peer", "peer", peer) + sw.Logger.Info("Reconnected to peer", "peer", peer) return } }() @@ -409,7 +408,7 @@ func (sw *Switch) StopPeerForError(peer *Peer, reason interface{}) { // Disconnect from a peer gracefully. // TODO: handle graceful disconnects. func (sw *Switch) StopPeerGracefully(peer *Peer) { - log.Notice("Stopping peer gracefully") + sw.Logger.Info("Stopping peer gracefully") sw.stopAndRemovePeer(peer, nil) } @@ -431,14 +430,14 @@ func (sw *Switch) listenerRoutine(l Listener) { // ignore connection if we already have enough maxPeers := sw.config.MaxNumPeers if maxPeers <= sw.peers.Size() { - log.Info("Ignoring inbound connection: already have enough peers", "address", inConn.RemoteAddr().String(), "numPeers", sw.peers.Size(), "max", maxPeers) + sw.Logger.Info("Ignoring inbound connection: already have enough peers", "address", inConn.RemoteAddr().String(), "numPeers", sw.peers.Size(), "max", maxPeers) continue } // New inbound connection! err := sw.addPeerWithConnectionAndConfig(inConn, sw.peerConfig) if err != nil { - log.Notice("Ignoring inbound connection: error while adding peer", "address", inConn.RemoteAddr().String(), "error", err) + sw.Logger.Info("Ignoring inbound connection: error while adding peer", "address", inConn.RemoteAddr().String(), "error", err) continue } diff --git a/p2p/switch_test.go b/p2p/switch_test.go index da5f43aa3..a6e960cdf 100644 --- a/p2p/switch_test.go +++ b/p2p/switch_test.go @@ -12,9 +12,9 @@ import ( "github.com/stretchr/testify/require" crypto "github.com/tendermint/go-crypto" wire "github.com/tendermint/go-wire" - cmn "github.com/tendermint/tmlibs/common" cfg "github.com/tendermint/tendermint/config" + "github.com/tendermint/tmlibs/log" ) var ( @@ -50,7 +50,8 @@ func NewTestReactor(channels []*ChannelDescriptor, logMessages bool) *TestReacto logMessages: logMessages, msgsReceived: make(map[byte][]PeerMessage), } - tr.BaseReactor = *NewBaseReactor(log, "TestReactor", tr) + tr.BaseReactor = *NewBaseReactor("TestReactor", tr) + tr.SetLogger(log.TestingLogger()) return tr } @@ -285,7 +286,6 @@ func TestSwitchReconnectsToPersistentPeer(t *testing.T) { } func BenchmarkSwitches(b *testing.B) { - b.StopTimer() s1, s2 := makeSwitchPair(b, func(i int, sw *Switch) *Switch { @@ -322,10 +322,9 @@ func BenchmarkSwitches(b *testing.B) { } } - log.Warn(cmn.Fmt("success: %v, failure: %v", numSuccess, numFailure)) + b.Logf("success: %v, failure: %v", numSuccess, numFailure) // Allow everything to flush before stopping switches & closing connections. b.StopTimer() time.Sleep(1000 * time.Millisecond) - } diff --git a/proxy/log.go b/proxy/log.go deleted file mode 100644 index d1d241bf1..000000000 --- a/proxy/log.go +++ /dev/null @@ -1,7 +0,0 @@ -package proxy - -import ( - "github.com/tendermint/tmlibs/logger" -) - -var log = logger.New("module", "proxy") diff --git a/proxy/multi_app_conn.go b/proxy/multi_app_conn.go index 8043f4818..0556a824f 100644 --- a/proxy/multi_app_conn.go +++ b/proxy/multi_app_conn.go @@ -48,7 +48,7 @@ func NewMultiAppConn(clientCreator ClientCreator, handshaker Handshaker) *multiA handshaker: handshaker, clientCreator: clientCreator, } - multiAppConn.BaseService = *cmn.NewBaseService(log, "multiAppConn", multiAppConn) + multiAppConn.BaseService = *cmn.NewBaseService(nil, "multiAppConn", multiAppConn) return multiAppConn } diff --git a/rpc/core/abci.go b/rpc/core/abci.go index 169447526..0cb29f479 100644 --- a/rpc/core/abci.go +++ b/rpc/core/abci.go @@ -17,7 +17,7 @@ func ABCIQuery(path string, data data.Bytes, prove bool) (*ctypes.ResultABCIQuer if err != nil { return nil, err } - log.Info("ABCIQuery", "path", path, "data", data, "result", resQuery) + logger.Info("ABCIQuery", "path", path, "data", data, "result", resQuery) return &ctypes.ResultABCIQuery{ resQuery.Result(), }, nil diff --git a/rpc/core/blocks.go b/rpc/core/blocks.go index ef3474127..4914fcb31 100644 --- a/rpc/core/blocks.go +++ b/rpc/core/blocks.go @@ -2,9 +2,10 @@ package core import ( "fmt" - . "github.com/tendermint/tmlibs/common" + ctypes "github.com/tendermint/tendermint/rpc/core/types" "github.com/tendermint/tendermint/types" + . "github.com/tendermint/tmlibs/common" ) //----------------------------------------------------------------------------- @@ -19,7 +20,7 @@ func BlockchainInfo(minHeight, maxHeight int) (*ctypes.ResultBlockchainInfo, err if minHeight == 0 { minHeight = MaxInt(1, maxHeight-20) } - log.Debug("BlockchainInfoHandler", "maxHeight", maxHeight, "minHeight", minHeight) + logger.Debug("BlockchainInfoHandler", "maxHeight", maxHeight, "minHeight", minHeight) blockMetas := []*types.BlockMeta{} for height := maxHeight; height >= minHeight; height-- { diff --git a/rpc/core/events.go b/rpc/core/events.go index fa40c5a81..d7cd75612 100644 --- a/rpc/core/events.go +++ b/rpc/core/events.go @@ -7,7 +7,7 @@ import ( ) func Subscribe(wsCtx rpctypes.WSRPCContext, event string) (*ctypes.ResultSubscribe, error) { - log.Notice("Subscribe to event", "remote", wsCtx.GetRemoteAddr(), "event", event) + logger.Info("Subscribe to event", "remote", wsCtx.GetRemoteAddr(), "event", event) types.AddListenerForEvent(wsCtx.GetEventSwitch(), wsCtx.GetRemoteAddr(), event, func(msg types.TMEventData) { // NOTE: EventSwitch callbacks must be nonblocking // NOTE: RPCResponses of subscribed events have id suffix "#event" @@ -18,7 +18,7 @@ func Subscribe(wsCtx rpctypes.WSRPCContext, event string) (*ctypes.ResultSubscri } func Unsubscribe(wsCtx rpctypes.WSRPCContext, event string) (*ctypes.ResultUnsubscribe, error) { - log.Notice("Unsubscribe to event", "remote", wsCtx.GetRemoteAddr(), "event", event) + logger.Info("Unsubscribe to event", "remote", wsCtx.GetRemoteAddr(), "event", event) wsCtx.GetEventSwitch().RemoveListenerForEvent(event, wsCtx.GetRemoteAddr()) return &ctypes.ResultUnsubscribe{}, nil } diff --git a/rpc/core/log.go b/rpc/core/log.go deleted file mode 100644 index d359bee26..000000000 --- a/rpc/core/log.go +++ /dev/null @@ -1,7 +0,0 @@ -package core - -import ( - "github.com/tendermint/log15" -) - -var log = log15.New("module", "rpc") diff --git a/rpc/core/mempool.go b/rpc/core/mempool.go index a6e7093fd..1988b05c6 100644 --- a/rpc/core/mempool.go +++ b/rpc/core/mempool.go @@ -59,7 +59,7 @@ func BroadcastTxCommit(tx types.Tx) (*ctypes.ResultBroadcastTxCommit, error) { checkTxResCh <- res }) if err != nil { - log.Error("err", "err", err) + logger.Error("err", "err", err) return nil, fmt.Errorf("Error broadcasting transaction: %v", err) } checkTxRes := <-checkTxResCh @@ -85,7 +85,7 @@ func BroadcastTxCommit(tx types.Tx) (*ctypes.ResultBroadcastTxCommit, error) { Data: deliverTxRes.Data, Log: deliverTxRes.Log, } - log.Notice("DeliverTx passed ", "tx", data.Bytes(tx), "response", deliverTxR) + logger.Info("DeliverTx passed ", "tx", data.Bytes(tx), "response", deliverTxR) return &ctypes.ResultBroadcastTxCommit{ CheckTx: checkTxR.Result(), DeliverTx: deliverTxR.Result(), @@ -93,7 +93,7 @@ func BroadcastTxCommit(tx types.Tx) (*ctypes.ResultBroadcastTxCommit, error) { Height: deliverTxRes.Height, }, nil case <-timer.C: - log.Error("failed to include tx") + logger.Error("failed to include tx") return &ctypes.ResultBroadcastTxCommit{ CheckTx: checkTxR.Result(), DeliverTx: abci.Result{}, diff --git a/rpc/core/net.go b/rpc/core/net.go index 31d9c34ea..b56216ca7 100644 --- a/rpc/core/net.go +++ b/rpc/core/net.go @@ -38,7 +38,7 @@ func UnsafeDialSeeds(seeds []string) (*ctypes.ResultDialSeeds, error) { return &ctypes.ResultDialSeeds{}, fmt.Errorf("No seeds provided") } // starts go routines to dial each seed after random delays - log.Info("DialSeeds", "addrBook", addrBook, "seeds", seeds) + logger.Info("DialSeeds", "addrBook", addrBook, "seeds", seeds) err := p2pSwitch.DialSeeds(addrBook, seeds) if err != nil { return &ctypes.ResultDialSeeds{}, err diff --git a/rpc/core/pipe.go b/rpc/core/pipe.go index 7a6a2d326..a18de2ad8 100644 --- a/rpc/core/pipe.go +++ b/rpc/core/pipe.go @@ -7,6 +7,7 @@ import ( "github.com/tendermint/tendermint/proxy" "github.com/tendermint/tendermint/state/txindex" "github.com/tendermint/tendermint/types" + "github.com/tendermint/tmlibs/log" ) //---------------------------------------------- @@ -44,6 +45,8 @@ var ( genDoc *types.GenesisDoc // cache the genesis structure addrBook *p2p.AddrBook txIndexer txindex.TxIndexer + + logger log.Logger ) func SetEventSwitch(evsw types.EventSwitch) { @@ -85,3 +88,7 @@ func SetProxyAppQuery(appConn proxy.AppConnQuery) { func SetTxIndexer(indexer txindex.TxIndexer) { txIndexer = indexer } + +func SetLogger(l log.Logger) { + logger = l +} diff --git a/rpc/lib/README.md b/rpc/lib/README.md index 6fe44c22f..de481c2f6 100644 --- a/rpc/lib/README.md +++ b/rpc/lib/README.md @@ -82,8 +82,9 @@ mux := http.NewServeMux() rpcserver.RegisterRPCFuncs(mux, Routes) wm := rpcserver.NewWebsocketManager(Routes, nil) mux.HandleFunc("/websocket", wm.WebsocketHandler) +logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) go func() { - _, err := rpcserver.StartHTTPServer("0.0.0.0:8008", mux) + _, err := rpcserver.StartHTTPServer("0.0.0.0:8008", mux, logger) if err != nil { panic(err) } diff --git a/rpc/lib/client/http_client.go b/rpc/lib/client/http_client.go index 9ad6386dc..33daf353a 100644 --- a/rpc/lib/client/http_client.go +++ b/rpc/lib/client/http_client.go @@ -26,7 +26,7 @@ func makeHTTPDialer(remoteAddr string) (string, func(string, string) (net.Conn, parts := strings.SplitN(remoteAddr, "://", 2) var protocol, address string if len(parts) != 2 { - log.Warn("WARNING (tendermint/rpc/lib): Please use fully formed listening addresses, including the tcp:// or unix:// prefix") + // log.Warn("WARNING (tendermint/rpc/lib): Please use fully formed listening addresses, including the tcp:// or unix:// prefix") protocol = types.SocketType(remoteAddr) address = remoteAddr } else { diff --git a/rpc/lib/client/log.go b/rpc/lib/client/log.go deleted file mode 100644 index 8b33e2f10..000000000 --- a/rpc/lib/client/log.go +++ /dev/null @@ -1,7 +0,0 @@ -package rpcclient - -import ( - "github.com/tendermint/log15" -) - -var log = log15.New("module", "rpcclient") diff --git a/rpc/lib/client/ws_client.go b/rpc/lib/client/ws_client.go index 833668d85..1ad744e87 100644 --- a/rpc/lib/client/ws_client.go +++ b/rpc/lib/client/ws_client.go @@ -37,7 +37,7 @@ func NewWSClient(remoteAddr, endpoint string) *WSClient { Endpoint: endpoint, Conn: nil, } - wsClient.BaseService = *cmn.NewBaseService(log, "WSClient", wsClient) + wsClient.BaseService = *cmn.NewBaseService(nil, "WSClient", wsClient) return wsClient } @@ -100,14 +100,14 @@ func (wsc *WSClient) receiveEventsRoutine() { for { _, data, err := wsc.ReadMessage() if err != nil { - log.Info("WSClient failed to read message", "error", err, "data", string(data)) + wsc.Logger.Info("WSClient failed to read message", "error", err, "data", string(data)) wsc.Stop() break } else { var response types.RPCResponse err := json.Unmarshal(data, &response) if err != nil { - log.Info("WSClient failed to parse message", "error", err, "data", string(data)) + wsc.Logger.Info("WSClient failed to parse message", "error", err, "data", string(data)) wsc.ErrorsCh <- err continue } diff --git a/rpc/lib/rpc_test.go b/rpc/lib/rpc_test.go index 3a2b36d51..c7bed052f 100644 --- a/rpc/lib/rpc_test.go +++ b/rpc/lib/rpc_test.go @@ -17,6 +17,7 @@ import ( client "github.com/tendermint/tendermint/rpc/lib/client" server "github.com/tendermint/tendermint/rpc/lib/server" types "github.com/tendermint/tendermint/rpc/lib/types" + "github.com/tendermint/tmlibs/log" ) // Client and Server should work over tcp or unix sockets @@ -86,22 +87,24 @@ func init() { } mux := http.NewServeMux() - server.RegisterRPCFuncs(mux, Routes) + server.RegisterRPCFuncs(mux, Routes, log.TestingLogger()) wm := server.NewWebsocketManager(Routes, nil) + wm.SetLogger(log.TestingLogger()) mux.HandleFunc(websocketEndpoint, wm.WebsocketHandler) go func() { - _, err := server.StartHTTPServer(tcpAddr, mux) + _, err := server.StartHTTPServer(tcpAddr, mux, log.TestingLogger()) if err != nil { panic(err) } }() mux2 := http.NewServeMux() - server.RegisterRPCFuncs(mux2, Routes) + server.RegisterRPCFuncs(mux2, Routes, log.TestingLogger()) wm = server.NewWebsocketManager(Routes, nil) + wm.SetLogger(log.TestingLogger()) mux2.HandleFunc(websocketEndpoint, wm.WebsocketHandler) go func() { - _, err := server.StartHTTPServer(unixAddr, mux2) + _, err := server.StartHTTPServer(unixAddr, mux2, log.TestingLogger()) if err != nil { panic(err) } diff --git a/rpc/lib/server/handlers.go b/rpc/lib/server/handlers.go index 5e6252d43..f35a5df8d 100644 --- a/rpc/lib/server/handlers.go +++ b/rpc/lib/server/handlers.go @@ -18,18 +18,19 @@ import ( types "github.com/tendermint/tendermint/rpc/lib/types" cmn "github.com/tendermint/tmlibs/common" events "github.com/tendermint/tmlibs/events" + "github.com/tendermint/tmlibs/log" ) // Adds a route for each function in the funcMap, as well as general jsonrpc and websocket handlers for all functions. // "result" is the interface on which the result objects are registered, and is popualted with every RPCResponse -func RegisterRPCFuncs(mux *http.ServeMux, funcMap map[string]*RPCFunc) { +func RegisterRPCFuncs(mux *http.ServeMux, funcMap map[string]*RPCFunc, logger log.Logger) { // HTTP endpoints for funcName, rpcFunc := range funcMap { - mux.HandleFunc("/"+funcName, makeHTTPHandler(rpcFunc)) + mux.HandleFunc("/"+funcName, makeHTTPHandler(rpcFunc, logger)) } // JSONRPC endpoints - mux.HandleFunc("/", makeJSONRPCHandler(funcMap)) + mux.HandleFunc("/", makeJSONRPCHandler(funcMap, logger)) } //------------------------------------- @@ -95,7 +96,7 @@ func funcReturnTypes(f interface{}) []reflect.Type { // rpc.json // jsonrpc calls grab the given method's function info and runs reflect.Call -func makeJSONRPCHandler(funcMap map[string]*RPCFunc) http.HandlerFunc { +func makeJSONRPCHandler(funcMap map[string]*RPCFunc, logger log.Logger) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { b, _ := ioutil.ReadAll(r.Body) // if its an empty request (like from a browser), @@ -130,7 +131,7 @@ func makeJSONRPCHandler(funcMap map[string]*RPCFunc) http.HandlerFunc { return } returns := rpcFunc.f.Call(args) - log.Info("HTTPJSONRPC", "method", request.Method, "args", args, "returns", returns) + logger.Info("HTTPJSONRPC", "method", request.Method, "args", args, "returns", returns) result, err := unreflectResult(returns) if err != nil { WriteRPCResponseHTTPError(w, http.StatusInternalServerError, types.NewRPCResponse(request.ID, result, err.Error())) @@ -223,7 +224,7 @@ func jsonParamsToArgsWS(rpcFunc *RPCFunc, params *json.RawMessage, wsCtx types.W // rpc.http // convert from a function name to the http handler -func makeHTTPHandler(rpcFunc *RPCFunc) func(http.ResponseWriter, *http.Request) { +func makeHTTPHandler(rpcFunc *RPCFunc, logger log.Logger) func(http.ResponseWriter, *http.Request) { // Exception for websocket endpoints if rpcFunc.ws { return func(w http.ResponseWriter, r *http.Request) { @@ -232,14 +233,14 @@ func makeHTTPHandler(rpcFunc *RPCFunc) func(http.ResponseWriter, *http.Request) } // All other endpoints return func(w http.ResponseWriter, r *http.Request) { - log.Debug("HTTP HANDLER", "req", r) + logger.Debug("HTTP HANDLER", "req", r) args, err := httpParamsToArgs(rpcFunc, r) if err != nil { WriteRPCResponseHTTPError(w, http.StatusBadRequest, types.NewRPCResponse("", nil, fmt.Sprintf("Error converting http params to args: %v", err.Error()))) return } returns := rpcFunc.f.Call(args) - log.Info("HTTPRestRPC", "method", r.URL.Path, "args", args, "returns", returns) + logger.Info("HTTPRestRPC", "method", r.URL.Path, "args", args, "returns", returns) result, err := unreflectResult(returns) if err != nil { WriteRPCResponseHTTPError(w, http.StatusInternalServerError, types.NewRPCResponse("", nil, err.Error())) @@ -367,7 +368,7 @@ func NewWSConnection(baseConn *websocket.Conn, funcMap map[string]*RPCFunc, evsw funcMap: funcMap, evsw: evsw, } - wsc.BaseService = *cmn.NewBaseService(log, "wsConnection", wsc) + wsc.BaseService = *cmn.NewBaseService(nil, "wsConnection", wsc) return wsc } @@ -417,7 +418,7 @@ func (wsc *wsConnection) OnStop() { func (wsc *wsConnection) readTimeoutRoutine() { select { case <-wsc.readTimeout.C: - log.Notice("Stopping connection due to read timeout") + wsc.Logger.Info("Stopping connection due to read timeout") wsc.Stop() case <-wsc.Quit: return @@ -476,7 +477,7 @@ func (wsc *wsConnection) readRoutine() { // We use `readTimeout` to handle read timeouts. _, in, err := wsc.baseConn.ReadMessage() if err != nil { - log.Notice("Failed to read from connection", "remote", wsc.remoteAddr, "err", err.Error()) + wsc.Logger.Info("Failed to read from connection", "remote", wsc.remoteAddr, "err", err.Error()) // an error reading the connection, // kill the connection wsc.Stop() @@ -509,7 +510,7 @@ func (wsc *wsConnection) readRoutine() { continue } returns := rpcFunc.f.Call(args) - log.Info("WSJSONRPC", "method", request.Method, "args", args, "returns", returns) + wsc.Logger.Info("WSJSONRPC", "method", request.Method, "args", args, "returns", returns) result, err := unreflectResult(returns) if err != nil { wsc.WriteRPCResponse(types.NewRPCResponse(request.ID, nil, err.Error())) @@ -533,18 +534,18 @@ func (wsc *wsConnection) writeRoutine() { case <-wsc.pingTicker.C: err := wsc.baseConn.WriteMessage(websocket.PingMessage, []byte{}) if err != nil { - log.Error("Failed to write ping message on websocket", "error", err) + wsc.Logger.Error("Failed to write ping message on websocket", "error", err) wsc.Stop() return } case msg := <-wsc.writeChan: jsonBytes, err := json.Marshal(msg) if err != nil { - log.Error("Failed to marshal RPCResponse to JSON", "error", err) + wsc.Logger.Error("Failed to marshal RPCResponse to JSON", "error", err) } else { wsc.baseConn.SetWriteDeadline(time.Now().Add(time.Second * wsWriteTimeoutSeconds)) if err = wsc.baseConn.WriteMessage(websocket.TextMessage, jsonBytes); err != nil { - log.Warn("Failed to write response on websocket", "error", err) + wsc.Logger.Error("Failed to write response on websocket", "error", err) wsc.Stop() return } @@ -562,6 +563,7 @@ type WebsocketManager struct { websocket.Upgrader funcMap map[string]*RPCFunc evsw events.EventSwitch + logger log.Logger } func NewWebsocketManager(funcMap map[string]*RPCFunc, evsw events.EventSwitch) *WebsocketManager { @@ -576,21 +578,26 @@ func NewWebsocketManager(funcMap map[string]*RPCFunc, evsw events.EventSwitch) * return true }, }, + logger: log.NewNopLogger(), } } +func (wm *WebsocketManager) SetLogger(l log.Logger) { + wm.logger = l +} + // Upgrade the request/response (via http.Hijack) and starts the wsConnection. func (wm *WebsocketManager) WebsocketHandler(w http.ResponseWriter, r *http.Request) { wsConn, err := wm.Upgrade(w, r, nil) if err != nil { // TODO - return http error - log.Error("Failed to upgrade to websocket connection", "error", err) + wm.logger.Error("Failed to upgrade to websocket connection", "error", err) return } // register connection con := NewWSConnection(wsConn, wm.funcMap, wm.evsw) - log.Notice("New websocket connection", "remote", con.remoteAddr) + wm.logger.Info("New websocket connection", "remote", con.remoteAddr) con.Start() // Blocking } diff --git a/rpc/lib/server/http_server.go b/rpc/lib/server/http_server.go index b51699c22..01b5b17d9 100644 --- a/rpc/lib/server/http_server.go +++ b/rpc/lib/server/http_server.go @@ -13,14 +13,15 @@ import ( "github.com/pkg/errors" types "github.com/tendermint/tendermint/rpc/lib/types" + "github.com/tendermint/tmlibs/log" ) -func StartHTTPServer(listenAddr string, handler http.Handler) (listener net.Listener, err error) { +func StartHTTPServer(listenAddr string, handler http.Handler, logger log.Logger) (listener net.Listener, err error) { // listenAddr should be fully formed including tcp:// or unix:// prefix var proto, addr string parts := strings.SplitN(listenAddr, "://", 2) if len(parts) != 2 { - log.Warn("WARNING (tendermint/rpc/lib): Please use fully formed listening addresses, including the tcp:// or unix:// prefix") + logger.Error("WARNING (tendermint/rpc/lib): Please use fully formed listening addresses, including the tcp:// or unix:// prefix") // we used to allow addrs without tcp/unix prefix by checking for a colon // TODO: Deprecate proto = types.SocketType(listenAddr) @@ -30,7 +31,7 @@ func StartHTTPServer(listenAddr string, handler http.Handler) (listener net.List proto, addr = parts[0], parts[1] } - log.Notice(fmt.Sprintf("Starting RPC HTTP server on %s socket %v", proto, addr)) + logger.Info(fmt.Sprintf("Starting RPC HTTP server on %s socket %v", proto, addr)) listener, err = net.Listen(proto, addr) if err != nil { return nil, errors.Errorf("Failed to listen to %v: %v", listenAddr, err) @@ -39,9 +40,9 @@ func StartHTTPServer(listenAddr string, handler http.Handler) (listener net.List go func() { res := http.Serve( listener, - RecoverAndLogHandler(handler), + RecoverAndLogHandler(handler, logger), ) - log.Crit("RPC HTTP server stopped", "result", res) + logger.Error("RPC HTTP server stopped", "result", res) }() return listener, nil } @@ -72,7 +73,7 @@ func WriteRPCResponseHTTP(w http.ResponseWriter, res types.RPCResponse) { // Wraps an HTTP handler, adding error logging. // If the inner function panics, the outer function recovers, logs, sends an // HTTP 500 error response. -func RecoverAndLogHandler(handler http.Handler) http.Handler { +func RecoverAndLogHandler(handler http.Handler, logger log.Logger) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // Wrap the ResponseWriter to remember the status rww := &ResponseWriterWrapper{-1, w} @@ -96,7 +97,7 @@ func RecoverAndLogHandler(handler http.Handler) http.Handler { WriteRPCResponseHTTP(rww, res) } else { // For the rest, - log.Error("Panic in RPC HTTP handler", "error", e, "stack", string(debug.Stack())) + logger.Error("Panic in RPC HTTP handler", "error", e, "stack", string(debug.Stack())) rww.WriteHeader(http.StatusInternalServerError) WriteRPCResponseHTTP(rww, types.NewRPCResponse("", nil, fmt.Sprintf("Internal Server Error: %v", e))) } @@ -107,7 +108,7 @@ func RecoverAndLogHandler(handler http.Handler) http.Handler { if rww.Status == -1 { rww.Status = 200 } - log.Info("Served RPC HTTP response", + logger.Info("Served RPC HTTP response", "method", r.Method, "url", r.URL, "status", rww.Status, "duration", durationMS, "remoteAddr", r.RemoteAddr, diff --git a/rpc/lib/server/log.go b/rpc/lib/server/log.go deleted file mode 100644 index 704e22e30..000000000 --- a/rpc/lib/server/log.go +++ /dev/null @@ -1,7 +0,0 @@ -package rpcserver - -import ( - "github.com/tendermint/log15" -) - -var log = log15.New("module", "rpcserver") diff --git a/rpc/lib/test/main.go b/rpc/lib/test/main.go index 8e63cdc38..702ed9f73 100644 --- a/rpc/lib/test/main.go +++ b/rpc/lib/test/main.go @@ -3,9 +3,11 @@ package main import ( "fmt" "net/http" + "os" - cmn "github.com/tendermint/tmlibs/common" rpcserver "github.com/tendermint/tendermint/rpc/lib/server" + cmn "github.com/tendermint/tmlibs/common" + "github.com/tendermint/tmlibs/log" ) var routes = map[string]*rpcserver.RPCFunc{ @@ -22,8 +24,9 @@ type Result struct { func main() { mux := http.NewServeMux() - rpcserver.RegisterRPCFuncs(mux, routes) - _, err := rpcserver.StartHTTPServer("0.0.0.0:8008", mux) + logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) + rpcserver.RegisterRPCFuncs(mux, routes, logger) + _, err := rpcserver.StartHTTPServer("0.0.0.0:8008", mux, logger) if err != nil { cmn.Exit(err.Error()) } diff --git a/rpc/test/helpers.go b/rpc/test/helpers.go index 034816cd1..130a45956 100644 --- a/rpc/test/helpers.go +++ b/rpc/test/helpers.go @@ -11,7 +11,7 @@ import ( "time" "github.com/stretchr/testify/require" - logger "github.com/tendermint/tmlibs/logger" + "github.com/tendermint/tmlibs/log" abci "github.com/tendermint/abci/types" cfg "github.com/tendermint/tendermint/config" @@ -25,8 +25,6 @@ import ( var config *cfg.Config -const tmLogLevel = "error" - // f**ing long, but unique for each test func makePathname() string { // get path @@ -63,9 +61,6 @@ func GetConfig() *cfg.Config { config.P2P.ListenAddress = tm config.RPCListenAddress = rpc config.GRPCListenAddress = grpc - - // Shut up the logging - logger.SetLogLevel(tmLogLevel) } return config } @@ -108,10 +103,12 @@ func StartTendermint(app abci.Application) *nm.Node { func NewTendermint(app abci.Application) *nm.Node { // Create & start node config := GetConfig() + logger := log.NewTMLogger(log.NewSyncWriter(os.Stdout)) + logger = log.NewFilter(logger, log.AllowError()) privValidatorFile := config.PrivValidatorFile() - privValidator := types.LoadOrGenPrivValidator(privValidatorFile) + privValidator := types.LoadOrGenPrivValidator(privValidatorFile, logger) papp := proxy.NewLocalClientCreator(app) - node := nm.NewNode(config, privValidator, papp) + node := nm.NewNode(config, privValidator, papp, logger) return node } diff --git a/state/execution.go b/state/execution.go index b06974cd8..aefb66aeb 100644 --- a/state/execution.go +++ b/state/execution.go @@ -11,6 +11,7 @@ import ( "github.com/tendermint/tendermint/state/txindex" "github.com/tendermint/tendermint/types" cmn "github.com/tendermint/tmlibs/common" + "github.com/tendermint/tmlibs/log" ) //-------------------------------------------------- @@ -26,7 +27,7 @@ func (s *State) ValExecBlock(eventCache types.Fireable, proxyAppConn proxy.AppCo } // Execute the block txs - abciResponses, err := execBlockOnProxyApp(eventCache, proxyAppConn, block) + abciResponses, err := execBlockOnProxyApp(eventCache, proxyAppConn, block, s.logger) if err != nil { // There was some error in proxyApp // TODO Report error and wait for proxyApp to be available. @@ -39,7 +40,7 @@ func (s *State) ValExecBlock(eventCache types.Fireable, proxyAppConn proxy.AppCo // Executes block's transactions on proxyAppConn. // Returns a list of transaction results and updates to the validator set // TODO: Generate a bitmap or otherwise store tx validity in state. -func execBlockOnProxyApp(eventCache types.Fireable, proxyAppConn proxy.AppConnConsensus, block *types.Block) (*ABCIResponses, error) { +func execBlockOnProxyApp(eventCache types.Fireable, proxyAppConn proxy.AppConnConsensus, block *types.Block, logger log.Logger) (*ABCIResponses, error) { var validTxs, invalidTxs = 0, 0 txIndex := 0 @@ -58,7 +59,7 @@ func execBlockOnProxyApp(eventCache types.Fireable, proxyAppConn proxy.AppConnCo if txResult.Code == abci.CodeType_OK { validTxs++ } else { - log.Debug("Invalid tx", "code", txResult.Code, "log", txResult.Log) + logger.Debug("Invalid tx", "code", txResult.Code, "log", txResult.Log) invalidTxs++ txError = txResult.Code.String() } @@ -84,7 +85,7 @@ func execBlockOnProxyApp(eventCache types.Fireable, proxyAppConn proxy.AppConnCo // Begin block err := proxyAppConn.BeginBlockSync(block.Hash(), types.TM2PB.Header(block.Header)) if err != nil { - log.Warn("Error in proxyAppConn.BeginBlock", "error", err) + logger.Error("Error in proxyAppConn.BeginBlock", "error", err) return nil, err } @@ -99,15 +100,15 @@ func execBlockOnProxyApp(eventCache types.Fireable, proxyAppConn proxy.AppConnCo // End block abciResponses.EndBlock, err = proxyAppConn.EndBlockSync(uint64(block.Height)) if err != nil { - log.Warn("Error in proxyAppConn.EndBlock", "error", err) + logger.Error("Error in proxyAppConn.EndBlock", "error", err) return nil, err } valDiff := abciResponses.EndBlock.Diffs - log.Info("Executed block", "height", block.Height, "valid txs", validTxs, "invalid txs", invalidTxs) + logger.Info("Executed block", "height", block.Height, "valid txs", validTxs, "invalid txs", invalidTxs) if len(valDiff) > 0 { - log.Info("Update to validator set", "updates", abci.ValidatorsString(valDiff)) + logger.Info("Update to validator set", "updates", abci.ValidatorsString(valDiff)) } return abciResponses, nil @@ -251,14 +252,14 @@ func (s *State) CommitStateUpdateMempool(proxyAppConn proxy.AppConnConsensus, bl // Commit block, get hash back res := proxyAppConn.CommitSync() if res.IsErr() { - log.Warn("Error in proxyAppConn.CommitSync", "error", res) + s.logger.Error("Error in proxyAppConn.CommitSync", "error", res) return res } if res.Log != "" { - log.Debug("Commit.Log: " + res.Log) + s.logger.Debug("Commit.Log: " + res.Log) } - log.Info("Committed state", "hash", res.Data) + s.logger.Info("Committed state", "hash", fmt.Sprintf("%X", res.Data)) // Set the state's new AppHash s.AppHash = res.Data @@ -286,21 +287,21 @@ func (s *State) indexTxs(abciResponses *ABCIResponses) { // Exec and commit a block on the proxyApp without validating or mutating the state // Returns the application root hash (result of abci.Commit) -func ExecCommitBlock(appConnConsensus proxy.AppConnConsensus, block *types.Block) ([]byte, error) { +func ExecCommitBlock(appConnConsensus proxy.AppConnConsensus, block *types.Block, logger log.Logger) ([]byte, error) { var eventCache types.Fireable // nil - _, err := execBlockOnProxyApp(eventCache, appConnConsensus, block) + _, err := execBlockOnProxyApp(eventCache, appConnConsensus, block, logger) if err != nil { - log.Warn("Error executing block on proxy app", "height", block.Height, "err", err) + logger.Error("Error executing block on proxy app", "height", block.Height, "err", err) return nil, err } // Commit block, get hash back res := appConnConsensus.CommitSync() if res.IsErr() { - log.Warn("Error in proxyAppConn.CommitSync", "error", res) + logger.Error("Error in proxyAppConn.CommitSync", "error", res) return nil, res } if res.Log != "" { - log.Info("Commit.Log: " + res.Log) + logger.Info("Commit.Log: " + res.Log) } return res.Data, nil } diff --git a/state/execution_test.go b/state/execution_test.go index 68c318448..3ebc05d37 100644 --- a/state/execution_test.go +++ b/state/execution_test.go @@ -11,6 +11,7 @@ import ( "github.com/tendermint/tendermint/state/txindex" "github.com/tendermint/tendermint/types" dbm "github.com/tendermint/tmlibs/db" + "github.com/tendermint/tmlibs/log" ) var ( @@ -28,6 +29,7 @@ func TestApplyBlock(t *testing.T) { defer proxyApp.Stop() state := state() + state.SetLogger(log.TestingLogger()) indexer := &dummyIndexer{0} state.TxIndexer = indexer diff --git a/state/log.go b/state/log.go deleted file mode 100644 index 0a2351324..000000000 --- a/state/log.go +++ /dev/null @@ -1,7 +0,0 @@ -package state - -import ( - "github.com/tendermint/tmlibs/logger" -) - -var log = logger.New("module", "state") diff --git a/state/state.go b/state/state.go index bacde0ab5..6b4a46bd8 100644 --- a/state/state.go +++ b/state/state.go @@ -9,8 +9,9 @@ import ( abci "github.com/tendermint/abci/types" cmn "github.com/tendermint/tmlibs/common" dbm "github.com/tendermint/tmlibs/db" + "github.com/tendermint/tmlibs/log" - "github.com/tendermint/go-wire" + wire "github.com/tendermint/go-wire" "github.com/tendermint/tendermint/state/txindex" "github.com/tendermint/tendermint/state/txindex/null" "github.com/tendermint/tendermint/types" @@ -48,6 +49,8 @@ type State struct { // Intermediate results from processing // Persisted separately from the state abciResponses *ABCIResponses + + logger log.Logger } func LoadState(db dbm.DB) *State { @@ -71,6 +74,14 @@ func loadState(db dbm.DB, key []byte) *State { return s } +func (s *State) SetLogger(l log.Logger) { + s.logger = l +} + +func (s *State) GetLogger() log.Logger { + return s.logger +} + func (s *State) Copy() *State { return &State{ db: s.db, @@ -83,6 +94,7 @@ func (s *State) Copy() *State { LastValidators: s.LastValidators.Copy(), AppHash: s.AppHash, TxIndexer: s.TxIndexer, // pointer here, not value + logger: s.logger, } } @@ -140,7 +152,7 @@ func (s *State) SetBlockAndValidators(header *types.Header, blockPartsHeader typ // update the validator set with the latest abciResponses err := updateValidators(nextValSet, abciResponses.EndBlock.Diffs) if err != nil { - log.Warn("Error changing validator set", "error", err) + s.logger.Error("Error changing validator set", "error", err) // TODO: err or carry on? } // Update validator accums and set state variables diff --git a/state/state_test.go b/state/state_test.go index 10bf07938..e97c3289a 100644 --- a/state/state_test.go +++ b/state/state_test.go @@ -6,9 +6,10 @@ import ( "github.com/stretchr/testify/assert" abci "github.com/tendermint/abci/types" - "github.com/tendermint/go-crypto" + crypto "github.com/tendermint/go-crypto" cfg "github.com/tendermint/tendermint/config" dbm "github.com/tendermint/tmlibs/db" + "github.com/tendermint/tmlibs/log" ) func TestStateCopyEquals(t *testing.T) { @@ -17,6 +18,7 @@ func TestStateCopyEquals(t *testing.T) { // Get State db stateDB := dbm.NewDB("state", config.DBBackend, config.DBDir()) state := GetState(stateDB, config.GenesisFile()) + state.SetLogger(log.TestingLogger()) stateCopy := state.Copy() @@ -36,6 +38,7 @@ func TestStateSaveLoad(t *testing.T) { // Get State db stateDB := dbm.NewDB("state", config.DBBackend, config.DBDir()) state := GetState(stateDB, config.GenesisFile()) + state.SetLogger(log.TestingLogger()) state.LastBlockHeight += 1 state.Save() @@ -52,6 +55,7 @@ func TestABCIResponsesSaveLoad(t *testing.T) { config := cfg.ResetTestRoot("state_") stateDB := dbm.NewDB("state", config.DBBackend, config.DBDir()) state := GetState(stateDB, config.GenesisFile()) + state.SetLogger(log.TestingLogger()) state.LastBlockHeight += 1 diff --git a/types/log.go b/types/log.go deleted file mode 100644 index 5a4b363ba..000000000 --- a/types/log.go +++ /dev/null @@ -1,7 +0,0 @@ -package types - -import ( - "github.com/tendermint/tmlibs/logger" -) - -var log = logger.New("module", "types") diff --git a/types/priv_validator.go b/types/priv_validator.go index b73591ddc..8d598ff1d 100644 --- a/types/priv_validator.go +++ b/types/priv_validator.go @@ -9,9 +9,10 @@ import ( "os" "sync" - . "github.com/tendermint/tmlibs/common" - "github.com/tendermint/go-crypto" + crypto "github.com/tendermint/go-crypto" data "github.com/tendermint/go-wire/data" + . "github.com/tendermint/tmlibs/common" + "github.com/tendermint/tmlibs/log" ) const ( @@ -107,17 +108,17 @@ func LoadPrivValidator(filePath string) *PrivValidator { return &privVal } -func LoadOrGenPrivValidator(filePath string) *PrivValidator { +func LoadOrGenPrivValidator(filePath string, logger log.Logger) *PrivValidator { var privValidator *PrivValidator if _, err := os.Stat(filePath); err == nil { privValidator = LoadPrivValidator(filePath) - log.Notice("Loaded PrivValidator", + logger.Info("Loaded PrivValidator", "file", filePath, "privValidator", privValidator) } else { privValidator = GenPrivValidator() privValidator.SetFile(filePath) privValidator.Save() - log.Notice("Generated PrivValidator", "file", filePath) + logger.Info("Generated PrivValidator", "file", filePath) } return privValidator } @@ -212,7 +213,7 @@ func (privVal *PrivValidator) signBytesHRS(height, round int, step int8, signByt // NOTE: proposals are non-deterministic (include time), // so we can actually lose them, but will still never sign conflicting ones if bytes.Equal(privVal.LastSignBytes, signBytes) { - log.Notice("Using privVal.LastSignature", "sig", privVal.LastSignature) + // log.Notice("Using privVal.LastSignature", "sig", privVal.LastSignature) return privVal.LastSignature, nil } } From 16509ac3dbd41af8189383e5c6b822da5be2806e Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 5 May 2017 19:19:46 -0400 Subject: [PATCH 284/309] p2p: fix race by peer.Start() before peers.Add() --- p2p/peer_set.go | 4 +--- p2p/switch.go | 20 ++++++++++++-------- p2p/switch_test.go | 1 + 3 files changed, 14 insertions(+), 11 deletions(-) diff --git a/p2p/peer_set.go b/p2p/peer_set.go index f3bc1edaf..c5206d2d5 100644 --- a/p2p/peer_set.go +++ b/p2p/peer_set.go @@ -16,7 +16,6 @@ type IPeerSet interface { // PeerSet is a special structure for keeping a table of peers. // Iteration over the peers is super fast and thread-safe. -// We also track how many peers per IP range and avoid too many type PeerSet struct { mtx sync.Mutex lookup map[string]*peerSetItem @@ -35,8 +34,7 @@ func NewPeerSet() *PeerSet { } } -// Returns false if peer with key (PubKeyEd25519) is already in set -// or if we have too many peers from the peer's IP range +// Returns false if peer with key (PubKeyEd25519) is already set func (ps *PeerSet) Add(peer *Peer) error { ps.mtx.Lock() defer ps.mtx.Unlock() diff --git a/p2p/switch.go b/p2p/switch.go index cab446f29..9d778f4bd 100644 --- a/p2p/switch.go +++ b/p2p/switch.go @@ -76,8 +76,7 @@ type Switch struct { } var ( - ErrSwitchDuplicatePeer = errors.New("Duplicate peer") - ErrSwitchMaxPeersPerIPRange = errors.New("IP range has too many peers") + ErrSwitchDuplicatePeer = errors.New("Duplicate peer") ) func NewSwitch(config *cfg.P2PConfig) *Switch { @@ -221,12 +220,10 @@ func (sw *Switch) AddPeer(peer *Peer) error { return err } - // Add the peer to .peers - // ignore if duplicate or if we already have too many for that IP range - if err := sw.peers.Add(peer); err != nil { - sw.Logger.Info("Ignoring peer", "error", err, "peer", peer) - peer.Stop() - return err + // Check for duplicate peer + if sw.peers.Has(peer.Key) { + return ErrSwitchDuplicatePeer + } // Start peer @@ -234,6 +231,13 @@ func (sw *Switch) AddPeer(peer *Peer) error { sw.startInitPeer(peer) } + // Add the peer to .peers. + // We start it first so that a peer in the list is safe to Stop. + // It should not err since we already checked peers.Has() + if err := sw.peers.Add(peer); err != nil { + return err + } + sw.Logger.Info("Added peer", "peer", peer) return nil } diff --git a/p2p/switch_test.go b/p2p/switch_test.go index a6e960cdf..eed7d1fab 100644 --- a/p2p/switch_test.go +++ b/p2p/switch_test.go @@ -279,6 +279,7 @@ func TestSwitchReconnectsToPersistentPeer(t *testing.T) { // simulate failure by closing connection peer.CloseConn() + // TODO: actually detect the disconnection and wait for reconnect time.Sleep(100 * time.Millisecond) assert.NotZero(sw.Peers().Size()) From bc4e6566e71d34dd4d705a887d8dac8c7f9cc889 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Thu, 11 May 2017 10:33:23 +0200 Subject: [PATCH 285/309] [p2p] refactor upnp to use new logger --- cmd/tendermint/commands/probe_upnp.go | 3 +-- p2p/upnp/log.go | 7 ------ p2p/upnp/probe.go | 35 ++++++++++++++------------- 3 files changed, 19 insertions(+), 26 deletions(-) delete mode 100644 p2p/upnp/log.go diff --git a/cmd/tendermint/commands/probe_upnp.go b/cmd/tendermint/commands/probe_upnp.go index 330dcf17d..e23e48973 100644 --- a/cmd/tendermint/commands/probe_upnp.go +++ b/cmd/tendermint/commands/probe_upnp.go @@ -20,8 +20,7 @@ func init() { } func probeUpnp(cmd *cobra.Command, args []string) error { - - capabilities, err := upnp.Probe() + capabilities, err := upnp.Probe(logger) if err != nil { fmt.Println("Probe failed: %v", err) } else { diff --git a/p2p/upnp/log.go b/p2p/upnp/log.go deleted file mode 100644 index 45e44439c..000000000 --- a/p2p/upnp/log.go +++ /dev/null @@ -1,7 +0,0 @@ -package upnp - -import ( - "github.com/tendermint/tmlibs/logger" -) - -var log = logger.New("module", "upnp") diff --git a/p2p/upnp/probe.go b/p2p/upnp/probe.go index 14dd496ac..3537e1c65 100644 --- a/p2p/upnp/probe.go +++ b/p2p/upnp/probe.go @@ -7,6 +7,7 @@ import ( "time" cmn "github.com/tendermint/tmlibs/common" + "github.com/tendermint/tmlibs/log" ) type UPNPCapabilities struct { @@ -14,24 +15,24 @@ type UPNPCapabilities struct { Hairpin bool } -func makeUPNPListener(intPort int, extPort int) (NAT, net.Listener, net.IP, error) { +func makeUPNPListener(intPort int, extPort int, logger log.Logger) (NAT, net.Listener, net.IP, error) { nat, err := Discover() if err != nil { return nil, nil, nil, errors.New(fmt.Sprintf("NAT upnp could not be discovered: %v", err)) } - log.Info(cmn.Fmt("ourIP: %v", nat.(*upnpNAT).ourIP)) + logger.Info(cmn.Fmt("ourIP: %v", nat.(*upnpNAT).ourIP)) ext, err := nat.GetExternalAddress() if err != nil { return nat, nil, nil, errors.New(fmt.Sprintf("External address error: %v", err)) } - log.Info(cmn.Fmt("External address: %v", ext)) + logger.Info(cmn.Fmt("External address: %v", ext)) port, err := nat.AddPortMapping("tcp", extPort, intPort, "Tendermint UPnP Probe", 0) if err != nil { return nat, nil, ext, errors.New(fmt.Sprintf("Port mapping error: %v", err)) } - log.Info(cmn.Fmt("Port mapping mapped: %v", port)) + logger.Info(cmn.Fmt("Port mapping mapped: %v", port)) // also run the listener, open for all remote addresses. listener, err := net.Listen("tcp", fmt.Sprintf(":%v", intPort)) @@ -41,22 +42,22 @@ func makeUPNPListener(intPort int, extPort int) (NAT, net.Listener, net.IP, erro return nat, listener, ext, nil } -func testHairpin(listener net.Listener, extAddr string) (supportsHairpin bool) { +func testHairpin(listener net.Listener, extAddr string, logger log.Logger) (supportsHairpin bool) { // Listener go func() { inConn, err := listener.Accept() if err != nil { - log.Notice(cmn.Fmt("Listener.Accept() error: %v", err)) + logger.Info(cmn.Fmt("Listener.Accept() error: %v", err)) return } - log.Info(cmn.Fmt("Accepted incoming connection: %v -> %v", inConn.LocalAddr(), inConn.RemoteAddr())) + logger.Info(cmn.Fmt("Accepted incoming connection: %v -> %v", inConn.LocalAddr(), inConn.RemoteAddr())) buf := make([]byte, 1024) n, err := inConn.Read(buf) if err != nil { - log.Notice(cmn.Fmt("Incoming connection read error: %v", err)) + logger.Info(cmn.Fmt("Incoming connection read error: %v", err)) return } - log.Info(cmn.Fmt("Incoming connection read %v bytes: %X", n, buf)) + logger.Info(cmn.Fmt("Incoming connection read %v bytes: %X", n, buf)) if string(buf) == "test data" { supportsHairpin = true return @@ -66,28 +67,28 @@ func testHairpin(listener net.Listener, extAddr string) (supportsHairpin bool) { // Establish outgoing outConn, err := net.Dial("tcp", extAddr) if err != nil { - log.Notice(cmn.Fmt("Outgoing connection dial error: %v", err)) + logger.Info(cmn.Fmt("Outgoing connection dial error: %v", err)) return } n, err := outConn.Write([]byte("test data")) if err != nil { - log.Notice(cmn.Fmt("Outgoing connection write error: %v", err)) + logger.Info(cmn.Fmt("Outgoing connection write error: %v", err)) return } - log.Info(cmn.Fmt("Outgoing connection wrote %v bytes", n)) + logger.Info(cmn.Fmt("Outgoing connection wrote %v bytes", n)) // Wait for data receipt time.Sleep(1 * time.Second) return } -func Probe() (caps UPNPCapabilities, err error) { - log.Info("Probing for UPnP!") +func Probe(logger log.Logger) (caps UPNPCapabilities, err error) { + logger.Info("Probing for UPnP!") intPort, extPort := 8001, 8001 - nat, listener, ext, err := makeUPNPListener(intPort, extPort) + nat, listener, ext, err := makeUPNPListener(intPort, extPort, logger) if err != nil { return } @@ -97,12 +98,12 @@ func Probe() (caps UPNPCapabilities, err error) { defer func() { err = nat.DeletePortMapping("tcp", intPort, extPort) if err != nil { - log.Warn(cmn.Fmt("Port mapping delete error: %v", err)) + logger.Error(cmn.Fmt("Port mapping delete error: %v", err)) } listener.Close() }() - supportsHairpin := testHairpin(listener, fmt.Sprintf("%v:%v", ext, extPort)) + supportsHairpin := testHairpin(listener, fmt.Sprintf("%v:%v", ext, extPort), logger) if supportsHairpin { caps.Hairpin = true } From 3e1343dc6bcd23346e394185cbb55b153a14c72e Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Fri, 12 May 2017 17:40:57 +0200 Subject: [PATCH 286/309] has as a base16 string --- blockchain/pool_test.go | 6 +++--- consensus/state.go | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/blockchain/pool_test.go b/blockchain/pool_test.go index e8e982644..43ddbaddf 100644 --- a/blockchain/pool_test.go +++ b/blockchain/pool_test.go @@ -92,7 +92,7 @@ func TestTimeout(t *testing.T) { defer pool.Stop() for _, peer := range peers { - t.Logf("Peer #%v", peer.id) + t.Logf("Peer %v", peer.id) } // Introduce each peer. @@ -123,7 +123,7 @@ func TestTimeout(t *testing.T) { for { select { case peerID := <-timeoutsCh: - t.Logf("Peer #%v timeouted", peerID) + t.Logf("Peer %v timeouted", peerID) if _, ok := timedOut[peerID]; !ok { counter++ if counter == len(peers) { @@ -131,7 +131,7 @@ func TestTimeout(t *testing.T) { } } case request := <-requestsCh: - t.Logf("Pulled new BlockRequest %v", request) + t.Logf("Pulled new BlockRequest %+v", request) } } } diff --git a/consensus/state.go b/consensus/state.go index 3ccf4be94..b0822c4ac 100644 --- a/consensus/state.go +++ b/consensus/state.go @@ -1293,7 +1293,7 @@ func (cs *ConsensusState) addProposalBlockPart(height int, part *types.Part, ver var err error cs.ProposalBlock = wire.ReadBinary(&types.Block{}, cs.ProposalBlockParts.GetReader(), types.MaxBlockSize, &n, &err).(*types.Block) // NOTE: it's possible to receive complete proposal blocks for future rounds without having the proposal - cs.Logger.Info("Received complete proposal block", "height", cs.ProposalBlock.Height, "hash", cs.ProposalBlock.Hash()) + cs.Logger.Info("Received complete proposal block", "height", cs.ProposalBlock.Height, "hash", fmt.Sprintf("%X", cs.ProposalBlock.Hash())) if cs.Step == RoundStepPropose && cs.isProposalComplete() { // Move onto the next step cs.enterPrevote(height, cs.Round) From c9cd8de9c6322fab79427b7ef4011dbc1bf28d41 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Fri, 12 May 2017 19:17:08 +0200 Subject: [PATCH 287/309] set logger --- blockchain/pool.go | 1 + consensus/reactor.go | 2 +- glide.lock | 32 ++++++++++++++++---------------- glide.yaml | 2 +- node/node.go | 1 + p2p/pex_reactor_test.go | 4 +++- p2p/switch.go | 5 +++-- 7 files changed, 26 insertions(+), 21 deletions(-) diff --git a/blockchain/pool.go b/blockchain/pool.go index 24b9210f5..a657b091e 100644 --- a/blockchain/pool.go +++ b/blockchain/pool.go @@ -281,6 +281,7 @@ func (pool *BlockPool) makeNextRequester() { nextHeight := pool.height + len(pool.requesters) request := newBPRequester(pool, nextHeight) + request.SetLogger(pool.Logger.With("height", nextHeight)) pool.requesters[nextHeight] = request pool.numPending++ diff --git a/consensus/reactor.go b/consensus/reactor.go index 3bb142625..4285a2e08 100644 --- a/consensus/reactor.go +++ b/consensus/reactor.go @@ -573,7 +573,7 @@ OUTER_LOOP: if sleeping == 0 { // We sent nothing. Sleep... sleeping = 1 - logger.Debug("No votes to send, sleeping", "peer", peer, + logger.Debug("No votes to send, sleeping", "localPV", rs.Votes.Prevotes(rs.Round).BitArray(), "peerPV", prs.Prevotes, "localPC", rs.Votes.Precommits(rs.Round).BitArray(), "peerPC", prs.Precommits) } else if sleeping == 2 { diff --git a/glide.lock b/glide.lock index 07f9cffb0..d5bb37d79 100644 --- a/glide.lock +++ b/glide.lock @@ -1,8 +1,8 @@ -hash: 83b5ca94602b8296526e421b9bc0a99584cff3909684fbda49c31ffcde1eea98 -updated: 2017-05-05T18:00:37.128906219Z +hash: 9f0eb87d9c5ebe5d81759b20be7c626d081c0cfc6647b0dd586f4a682d796b58 +updated: 2017-05-12T16:57:05.086543617Z imports: - name: github.com/btcsuite/btcd - version: 4b348c1d33373d672edd83fc576892d0e46686d2 + version: 1ae306021e323ae11c71ffb8546fbd9019e6cb6f subpackages: - btcec - name: github.com/davecgh/go-spew @@ -14,7 +14,7 @@ imports: - name: github.com/fsnotify/fsnotify version: 4da3e2cfbabc9f751898f250b49f2439785783a1 - name: github.com/go-kit/kit - version: 0873e56b0faeae3a1d661b10d629135508ea5504 + version: d67bb4c202e3b91377d1079b110a6c9ce23ab2f8 subpackages: - log - log/level @@ -28,7 +28,7 @@ imports: subpackages: - proto - name: github.com/golang/protobuf - version: 18c9bb3261723cd5401db4d0c9fbc5c3b6c70fe8 + version: 157d9c53be5810dd5a0fac4a467f7d5f400042ea subpackages: - proto - ptypes/any @@ -37,7 +37,7 @@ imports: - name: github.com/gorilla/websocket version: a91eba7f97777409bc2c443f5534d41dd20c5720 - name: github.com/hashicorp/hcl - version: a4b07c25de5ff55ad3b8936cea69a79a3d95a855 + version: 392dba7d905ed5d04a5794ba89f558b27e2ba1ca subpackages: - hcl/ast - hcl/parser @@ -64,7 +64,7 @@ imports: - name: github.com/pelletier/go-buffruneio version: c37440a7cf42ac63b919c752ca73a85067e05992 - name: github.com/pelletier/go-toml - version: 97253b98df84f9eef872866d079e74b8265150f1 + version: 685a1f1cb7a66b9cadbe8f1ac49d9f8f567d6a9d - name: github.com/pkg/errors version: c605e284fe17294bda444b34710735b29d1a9d90 - name: github.com/pmezard/go-difflib @@ -78,11 +78,11 @@ imports: - name: github.com/spf13/cast version: acbeb36b902d72a7a4c18e8f3241075e7ab763e4 - name: github.com/spf13/cobra - version: db6b9a8b3f3f400c8ecb4a4d7d02245b8facad66 + version: 3454e0e28e69c1b8effa6b5123c8e4185e20d696 - name: github.com/spf13/jwalterweatherman - version: fa7ca7e836cf3a8bb4ebf799f472c12d7e903d66 + version: 8f07c835e5cc1450c082fe3a439cf87b0cbb2d99 - name: github.com/spf13/pflag - version: 80fe0fb4eba54167e2ccae1c6c950e72abf61b73 + version: e57e3eeb33f795204c1ca35f56c44f83227c6e66 - name: github.com/spf13/viper version: 0967fc9aceab2ce9da34061253ac10fb99bba5b2 - name: github.com/stretchr/testify @@ -137,7 +137,7 @@ imports: - iavl - testutil - name: github.com/tendermint/tmlibs - version: 240215f2aa26d53223c618a5a2127a08d37868f0 + version: 25a5bc2697d2c9aedb6594366e5269bbe8f6e6ee subpackages: - autofile - cli @@ -151,7 +151,7 @@ imports: - merkle - test - name: golang.org/x/crypto - version: 5a033cc77e57eca05bdb50522851d29e03569cbe + version: ab89591268e0c8b748cbe4047b00197516011af5 subpackages: - curve25519 - nacl/box @@ -162,7 +162,7 @@ imports: - ripemd160 - salsa20/salsa - name: golang.org/x/net - version: feeb485667d1fdabe727840fe00adc22431bc86e + version: c9b681d35165f1995d6f3034e61f8761d4b90c99 subpackages: - context - http2 @@ -172,11 +172,11 @@ imports: - lex/httplex - trace - name: golang.org/x/sys - version: 9ccfe848b9db8435a24c424abbc07a921adf1df5 + version: 156c5a2da4a2085250f45d65e24fabe6ed437394 subpackages: - unix - name: golang.org/x/text - version: 470f45bf29f4147d6fbd7dfd0a02a848e49f5bf4 + version: 19e51611da83d6be54ddafce4a4af510cb3e9ea4 subpackages: - secure/bidirule - transform @@ -187,7 +187,7 @@ imports: subpackages: - googleapis/rpc/status - name: google.golang.org/grpc - version: 844f573616520565fdc6fb4db242321b5456fd6d + version: a0c3e72252b6fbf4826bb143e450eb05588a9d6d subpackages: - codes - credentials diff --git a/glide.yaml b/glide.yaml index a7d3fb79f..faaa1bee4 100644 --- a/glide.yaml +++ b/glide.yaml @@ -25,7 +25,7 @@ import: - data - package: github.com/tendermint/log15 - package: github.com/tendermint/tmlibs - version: log + version: develop subpackages: - autofile - cli diff --git a/node/node.go b/node/node.go index 5d9e67844..83f1577bd 100644 --- a/node/node.go +++ b/node/node.go @@ -127,6 +127,7 @@ func NewNode(config *cfg.Config, privValidator *types.PrivValidator, clientCreat // Make ConsensusReactor consensusState := consensus.NewConsensusState(config.Consensus, state.Copy(), proxyApp.Consensus(), blockStore, mempool) + consensusState.SetLogger(logger.With("module", "consensus")) if privValidator != nil { consensusState.SetPrivValidator(privValidator) } diff --git a/p2p/pex_reactor_test.go b/p2p/pex_reactor_test.go index 7e69ace35..76738c864 100644 --- a/p2p/pex_reactor_test.go +++ b/p2p/pex_reactor_test.go @@ -163,7 +163,7 @@ func TestPEXReactorAbuseFromPeer(t *testing.T) { func createRandomPeer(outbound bool) *Peer { addr := cmn.Fmt("%v.%v.%v.%v:46656", rand.Int()%256, rand.Int()%256, rand.Int()%256, rand.Int()%256) netAddr, _ := NewNetAddressString(addr) - return &Peer{ + p := &Peer{ Key: cmn.RandStr(12), NodeInfo: &NodeInfo{ ListenAddr: addr, @@ -171,4 +171,6 @@ func createRandomPeer(outbound bool) *Peer { outbound: outbound, mconn: &MConnection{RemoteAddress: netAddr}, } + p.SetLogger(log.TestingLogger().With("peer", addr)) + return p } diff --git a/p2p/switch.go b/p2p/switch.go index 9d778f4bd..18fa78837 100644 --- a/p2p/switch.go +++ b/p2p/switch.go @@ -321,6 +321,7 @@ func (sw *Switch) DialPeerWithAddress(addr *NetAddress, persistent bool) (*Peer, defer sw.dialing.Delete(addr.IP.String()) peer, err := newOutboundPeerWithConfig(addr, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey, sw.peerConfig) + peer.SetLogger(sw.Logger.With("peer", addr)) if err != nil { sw.Logger.Info("Failed dialing peer", "address", addr, "error", err) return nil, err @@ -547,11 +548,11 @@ func makeSwitch(cfg *cfg.P2PConfig, i int, network, version string, initSwitch f func (sw *Switch) addPeerWithConnection(conn net.Conn) error { peer, err := newInboundPeer(conn, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey) + peer.SetLogger(sw.Logger.With("peer", conn.RemoteAddr())) if err != nil { conn.Close() return err } - if err = sw.AddPeer(peer); err != nil { conn.Close() return err @@ -562,11 +563,11 @@ func (sw *Switch) addPeerWithConnection(conn net.Conn) error { func (sw *Switch) addPeerWithConnectionAndConfig(conn net.Conn, config *PeerConfig) error { peer, err := newInboundPeerWithConfig(conn, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey, config) + peer.SetLogger(sw.Logger.With("peer", conn.RemoteAddr())) if err != nil { conn.Close() return err } - if err = sw.AddPeer(peer); err != nil { conn.Close() return err From f8fdbe3dbc1e45a77cc4f38f7aed077979c8566b Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Fri, 12 May 2017 23:07:53 +0200 Subject: [PATCH 288/309] changes as per Bucky's review --- cmd/tendermint/commands/root.go | 15 +--- config/toml.go | 2 - consensus/common_test.go | 3 + consensus/reactor.go | 2 +- consensus/reactor_test.go | 3 +- consensus/replay.go | 4 +- consensus/replay_test.go | 5 +- consensus/state.go | 17 +++- consensus/ticker.go | 3 + consensus/wal.go | 3 +- glide.lock | 29 +++--- glide.yaml | 11 +-- mempool/mempool.go | 2 +- node/node.go | 21 ++++- p2p/glide.lock | 153 -------------------------------- p2p/peer.go | 4 +- p2p/switch.go | 6 +- p2p/types.go | 6 +- proxy/multi_app_conn.go | 4 +- rpc/lib/client/http_client.go | 5 +- state/execution.go | 2 +- state/state.go | 4 - types/block.go | 4 +- types/priv_validator.go | 2 +- 24 files changed, 83 insertions(+), 227 deletions(-) delete mode 100644 p2p/glide.lock diff --git a/cmd/tendermint/commands/root.go b/cmd/tendermint/commands/root.go index 23c792658..ffd013065 100644 --- a/cmd/tendermint/commands/root.go +++ b/cmd/tendermint/commands/root.go @@ -1,7 +1,6 @@ package commands import ( - "fmt" "os" "github.com/spf13/cobra" @@ -27,18 +26,10 @@ var RootCmd = &cobra.Command{ err := viper.Unmarshal(config) config.SetRoot(config.RootDir) cfg.EnsureRoot(config.RootDir) - var option log.Option - switch config.LogLevel { - case "info": - option = log.AllowInfo() - case "debug": - option = log.AllowDebug() - case "error": - option = log.AllowError() - default: - return fmt.Errorf("Expected either \"info\", \"debug\" or \"error\" log level, given %v", config.LogLevel) + logger, err = log.NewFilterByLevel(logger, config.LogLevel) + if err != nil { + return err } - logger = log.NewFilter(logger, option) return err }, } diff --git a/config/toml.go b/config/toml.go index 272577140..cf232fbf6 100644 --- a/config/toml.go +++ b/config/toml.go @@ -7,7 +7,6 @@ import ( "strings" cmn "github.com/tendermint/tmlibs/common" - "github.com/tendermint/tmlibs/logger" ) /****** these are for production settings ***********/ @@ -83,7 +82,6 @@ func ResetTestRoot(testName string) *Config { cmn.MustWriteFile(privFilePath, []byte(testPrivValidator), 0644) config := TestConfig().SetRoot(rootDir) - logger.SetLogLevel(config.LogLevel) return config } diff --git a/consensus/common_test.go b/consensus/common_test.go index 2872397e4..02bc8ba52 100644 --- a/consensus/common_test.go +++ b/consensus/common_test.go @@ -456,6 +456,9 @@ func (m *mockTicker) Chan() <-chan timeoutInfo { return m.c } +func (mockTicker) SetLogger(log.Logger) { +} + //------------------------------------ func newCounter() abci.Application { diff --git a/consensus/reactor.go b/consensus/reactor.go index 4285a2e08..3652697b5 100644 --- a/consensus/reactor.go +++ b/consensus/reactor.go @@ -207,7 +207,7 @@ func (conR *ConsensusReactor) Receive(chID byte, src *p2p.Peer, msgBytes []byte) case DataChannel: if conR.fastSync { - conR.Logger.Error("Ignoring message received during fastSync", "msg", msg) + conR.Logger.Info("Ignoring message received during fastSync", "msg", msg) return } switch msg := msg.(type) { diff --git a/consensus/reactor_test.go b/consensus/reactor_test.go index dec577ac0..03143360d 100644 --- a/consensus/reactor_test.go +++ b/consensus/reactor_test.go @@ -25,7 +25,7 @@ func startConsensusNet(t *testing.T, css []*ConsensusState, N int, subscribeEven eventChans := make([]chan interface{}, N) for i := 0; i < N; i++ { reactors[i] = NewConsensusReactor(css[i], true) // so we dont start the consensus states - reactors[i].SetLogger(log.TestingLogger()) + reactors[i].SetLogger(log.TestingLogger().With("reactor", i)) eventSwitch := events.NewEventSwitch() eventSwitch.SetLogger(log.TestingLogger().With("module", "events")) @@ -265,7 +265,6 @@ func waitForAndValidateBlock(t *testing.T, n int, activeVals map[string]struct{} eventChans[j] <- struct{}{} wg.Done() - t.Logf("[WARN] Done wait group height=%v validator=%v", newBlock.Height, j) }, css) } diff --git a/consensus/replay.go b/consensus/replay.go index 04852dba8..c45c4b80b 100644 --- a/consensus/replay.go +++ b/consensus/replay.go @@ -229,7 +229,7 @@ func (h *Handshaker) Handshake(proxyApp proxy.AppConns) error { blockHeight := int(res.LastBlockHeight) // XXX: beware overflow appHash := res.LastBlockAppHash - h.logger.Info("ABCI Handshake", "appHeight", blockHeight, "appHash", appHash) + h.logger.Info("ABCI Handshake", "appHeight", blockHeight, "appHash", fmt.Sprintf("%X", appHash)) // TODO: check version @@ -239,7 +239,7 @@ func (h *Handshaker) Handshake(proxyApp proxy.AppConns) error { return errors.New(cmn.Fmt("Error on replay: %v", err)) } - h.logger.Info("Completed ABCI Handshake - Tendermint and App are synced", "appHeight", blockHeight, "appHash", appHash) + h.logger.Info("Completed ABCI Handshake - Tendermint and App are synced", "appHeight", blockHeight, "appHash", fmt.Sprintf("%X", appHash)) // TODO: (on restart) replay mempool diff --git a/consensus/replay_test.go b/consensus/replay_test.go index 468149a3a..23290a7f5 100644 --- a/consensus/replay_test.go +++ b/consensus/replay_test.go @@ -323,10 +323,13 @@ func testHandshakeReplay(t *testing.T, nBlocks int, mode uint) { testPartSize = config.Consensus.BlockPartSize wal, err := NewWAL(walFile, false) - wal.SetLogger(log.TestingLogger()) if err != nil { t.Fatal(err) } + wal.SetLogger(log.TestingLogger()) + if _, err := wal.Start(); err != nil { + t.Fatal(err) + } chain, commits, err := makeBlockchainFromWAL(wal) if err != nil { t.Fatalf(err.Error()) diff --git a/consensus/state.go b/consensus/state.go index b0822c4ac..222f2f233 100644 --- a/consensus/state.go +++ b/consensus/state.go @@ -16,6 +16,7 @@ import ( sm "github.com/tendermint/tendermint/state" "github.com/tendermint/tendermint/types" cmn "github.com/tendermint/tmlibs/common" + "github.com/tendermint/tmlibs/log" ) //----------------------------------------------------------------------------- @@ -244,6 +245,12 @@ func NewConsensusState(config *cfg.ConsensusConfig, state *sm.State, proxyAppCon //---------------------------------------- // Public interface +// SetLogger implements Service. +func (cs *ConsensusState) SetLogger(l log.Logger) { + cs.BaseService.Logger = l + cs.timeoutTicker.SetLogger(l) +} + // SetEventSwitch implements events.Eventable func (cs *ConsensusState) SetEventSwitch(evsw types.EventSwitch) { cs.evsw = evsw @@ -371,6 +378,10 @@ func (cs *ConsensusState) OpenWAL(walFile string) (err error) { if err != nil { return err } + wal.SetLogger(cs.Logger.With("wal", walFile)) + if _, err := wal.Start(); err != nil { + return err + } cs.wal = wal return nil } @@ -576,7 +587,7 @@ func (cs *ConsensusState) receiveRoutine(maxSteps int) { for { if maxSteps > 0 { if cs.nSteps >= maxSteps { - cs.Logger.Error("reached max steps. exiting receive routine") + cs.Logger.Info("reached max steps. exiting receive routine") cs.nSteps = 0 return } @@ -904,7 +915,7 @@ func (cs *ConsensusState) defaultDoPrevote(height int, round int) { // If ProposalBlock is nil, prevote nil. if cs.ProposalBlock == nil { - cs.Logger.Error("enterPrevote: ProposalBlock is nil") + cs.Logger.Info("enterPrevote: ProposalBlock is nil") cs.signAddVote(types.VoteTypePrevote, nil, types.PartSetHeader{}) return } @@ -1293,7 +1304,7 @@ func (cs *ConsensusState) addProposalBlockPart(height int, part *types.Part, ver var err error cs.ProposalBlock = wire.ReadBinary(&types.Block{}, cs.ProposalBlockParts.GetReader(), types.MaxBlockSize, &n, &err).(*types.Block) // NOTE: it's possible to receive complete proposal blocks for future rounds without having the proposal - cs.Logger.Info("Received complete proposal block", "height", cs.ProposalBlock.Height, "hash", fmt.Sprintf("%X", cs.ProposalBlock.Hash())) + cs.Logger.Info("Received complete proposal block", "height", cs.ProposalBlock.Height, "hash", cs.ProposalBlock.Hash()) if cs.Step == RoundStepPropose && cs.isProposalComplete() { // Move onto the next step cs.enterPrevote(height, cs.Round) diff --git a/consensus/ticker.go b/consensus/ticker.go index 1abab8cf7..e869cdef1 100644 --- a/consensus/ticker.go +++ b/consensus/ticker.go @@ -4,6 +4,7 @@ import ( "time" . "github.com/tendermint/tmlibs/common" + "github.com/tendermint/tmlibs/log" ) var ( @@ -18,6 +19,8 @@ type TimeoutTicker interface { Stop() bool Chan() <-chan timeoutInfo // on which to receive a timeout ScheduleTimeout(ti timeoutInfo) // reset the timer + + SetLogger(log.Logger) } // timeoutTicker wraps time.Timer, diff --git a/consensus/wal.go b/consensus/wal.go index dde9b1b94..a2ac470a0 100644 --- a/consensus/wal.go +++ b/consensus/wal.go @@ -50,8 +50,7 @@ func NewWAL(walFile string, light bool) (*WAL, error) { light: light, } wal.BaseService = *NewBaseService(nil, "WAL", wal) - _, err = wal.Start() - return wal, err + return wal, nil } func (wal *WAL) OnStart() error { diff --git a/glide.lock b/glide.lock index d5bb37d79..7dfd94bd1 100644 --- a/glide.lock +++ b/glide.lock @@ -1,5 +1,5 @@ -hash: 9f0eb87d9c5ebe5d81759b20be7c626d081c0cfc6647b0dd586f4a682d796b58 -updated: 2017-05-12T16:57:05.086543617Z +hash: 9caff08aa026986b239e4aeb9d876bdddfacadc64a660ee8109e77a211e53436 +updated: 2017-05-13T14:12:48.997991788Z imports: - name: github.com/btcsuite/btcd version: 1ae306021e323ae11c71ffb8546fbd9019e6cb6f @@ -28,7 +28,7 @@ imports: subpackages: - proto - name: github.com/golang/protobuf - version: 157d9c53be5810dd5a0fac4a467f7d5f400042ea + version: fec3b39b059c0f88fa6b20f5ed012b1aa203a8b4 subpackages: - proto - ptypes/any @@ -55,10 +55,6 @@ imports: version: b84e30acd515aadc4b783ad4ff83aff3299bdfe0 - name: github.com/magiconair/properties version: 51463bfca2576e06c62a8504b5c0f06d61312647 -- name: github.com/mattn/go-colorable - version: ded68f7a9561c023e790de24279db7ebf473ea80 -- name: github.com/mattn/go-isatty - version: fc9e8d8ef48496124e79ae0df75490096eccf6fe - name: github.com/mitchellh/mapstructure version: cc8532a8e9a55ea36402aa21efdf403a60d34096 - name: github.com/pelletier/go-buffruneio @@ -78,7 +74,7 @@ imports: - name: github.com/spf13/cast version: acbeb36b902d72a7a4c18e8f3241075e7ab763e4 - name: github.com/spf13/cobra - version: 3454e0e28e69c1b8effa6b5123c8e4185e20d696 + version: 90687e7bfc7e1e5cd88eb1f513f32f01dc03dd7c - name: github.com/spf13/jwalterweatherman version: 8f07c835e5cc1450c082fe3a439cf87b0cbb2d99 - name: github.com/spf13/pflag @@ -106,7 +102,7 @@ imports: - leveldb/table - leveldb/util - name: github.com/tendermint/abci - version: 50a9967c79d89742151c7f1a981678df8c21f9dc + version: b662bc7d3439b3c2cce615e8c3502b762e133dbf subpackages: - client - example/counter @@ -121,14 +117,10 @@ imports: - name: github.com/tendermint/go-crypto version: e71bbb2509b586f0b24f120b6ba57f32aefa1579 - name: github.com/tendermint/go-wire - version: b53add0b622662731985485f3a19be7f684660b8 + version: 82d31b6afb3c438639bffc5e1c7318b9a55285b3 subpackages: - data - data/base58 -- name: github.com/tendermint/log15 - version: f91285dece9f4875421b481da3e613d83d44f29b - subpackages: - - term - name: github.com/tendermint/merkleeyes version: c722818b460381bc5b82e38c73ff6e22a9df624d subpackages: @@ -137,7 +129,7 @@ imports: - iavl - testutil - name: github.com/tendermint/tmlibs - version: 25a5bc2697d2c9aedb6594366e5269bbe8f6e6ee + version: 8f5a175ff4c869fedde710615a11f5745ff69bf3 subpackages: - autofile - cli @@ -147,7 +139,6 @@ imports: - events - flowrate - log - - logger - merkle - test - name: golang.org/x/crypto @@ -162,7 +153,7 @@ imports: - ripemd160 - salsa20/salsa - name: golang.org/x/net - version: c9b681d35165f1995d6f3034e61f8761d4b90c99 + version: 84f0e6f92b10139f986b1756e149a7d9de270cdc subpackages: - context - http2 @@ -172,7 +163,7 @@ imports: - lex/httplex - trace - name: golang.org/x/sys - version: 156c5a2da4a2085250f45d65e24fabe6ed437394 + version: f845067cf72a21fb4929b0e6a35273bd83b56396 subpackages: - unix - name: golang.org/x/text @@ -187,7 +178,7 @@ imports: subpackages: - googleapis/rpc/status - name: google.golang.org/grpc - version: a0c3e72252b6fbf4826bb143e450eb05588a9d6d + version: 1c69e4cae0f5180ce7d8b472bf0a55d2654fe31b subpackages: - codes - credentials diff --git a/glide.yaml b/glide.yaml index faaa1bee4..dd4993f59 100644 --- a/glide.yaml +++ b/glide.yaml @@ -11,8 +11,11 @@ import: - package: github.com/pkg/errors - package: github.com/spf13/cobra - package: github.com/spf13/viper +- package: github.com/stretchr/testify + subpackages: + - require - package: github.com/tendermint/abci - version: feature/new-logging + version: develop subpackages: - client - example/dummy @@ -23,7 +26,6 @@ import: version: develop subpackages: - data -- package: github.com/tendermint/log15 - package: github.com/tendermint/tmlibs version: develop subpackages: @@ -46,11 +48,6 @@ import: - context - package: google.golang.org/grpc testImport: -- package: github.com/stretchr/testify - version: ^1.1.4 - subpackages: - - assert - - require - package: github.com/tendermint/merkleeyes version: develop subpackages: diff --git a/mempool/mempool.go b/mempool/mempool.go index 81bcb483e..9e53108e5 100644 --- a/mempool/mempool.go +++ b/mempool/mempool.go @@ -13,11 +13,11 @@ import ( auto "github.com/tendermint/tmlibs/autofile" "github.com/tendermint/tmlibs/clist" cmn "github.com/tendermint/tmlibs/common" + "github.com/tendermint/tmlibs/log" cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tendermint/proxy" "github.com/tendermint/tendermint/types" - "github.com/tendermint/tmlibs/log" ) /* diff --git a/node/node.go b/node/node.go index 83f1577bd..ecfdef45a 100644 --- a/node/node.go +++ b/node/node.go @@ -75,9 +75,14 @@ func NewNode(config *cfg.Config, privValidator *types.PrivValidator, clientCreat state := sm.GetState(stateDB, config.GenesisFile()) state.SetLogger(logger.With("module", "state")) + consensusLogger := logger.With("module", "consensus") + // Create the proxyApp, which manages connections (consensus, mempool, query) // and sync tendermint and the app by replaying any necessary blocks - proxyApp := proxy.NewAppConns(clientCreator, consensus.NewHandshaker(state, blockStore)) + handshaker := consensus.NewHandshaker(state, blockStore) + handshaker.SetLogger(consensusLogger) + proxyApp := proxy.NewAppConns(clientCreator, handshaker) + proxyApp.SetLogger(logger.With("module", "proxy")) if _, err := proxyApp.Start(); err != nil { cmn.Exit(cmn.Fmt("Error starting proxy app connections: %v", err)) } @@ -102,6 +107,7 @@ func NewNode(config *cfg.Config, privValidator *types.PrivValidator, clientCreat // Make event switch eventSwitch := types.NewEventSwitch() + eventSwitch.SetLogger(logger.With("module", "types")) _, err := eventSwitch.Start() if err != nil { cmn.Exit(cmn.Fmt("Failed to start switch: %v", err)) @@ -119,21 +125,28 @@ func NewNode(config *cfg.Config, privValidator *types.PrivValidator, clientCreat // Make BlockchainReactor bcReactor := bc.NewBlockchainReactor(state.Copy(), proxyApp.Consensus(), blockStore, fastSync) + bcReactor.SetLogger(logger.With("module", "blockchain")) // Make MempoolReactor + mempoolLogger := logger.With("module", "consensus") mempool := mempl.NewMempool(config.Mempool, proxyApp.Mempool()) - mempool.SetLogger(logger.With("module", "mempool")) + mempool.SetLogger(mempoolLogger) mempoolReactor := mempl.NewMempoolReactor(config.Mempool, mempool) + mempoolReactor.SetLogger(mempoolLogger) // Make ConsensusReactor consensusState := consensus.NewConsensusState(config.Consensus, state.Copy(), proxyApp.Consensus(), blockStore, mempool) - consensusState.SetLogger(logger.With("module", "consensus")) + consensusState.SetLogger(consensusLogger) if privValidator != nil { consensusState.SetPrivValidator(privValidator) } consensusReactor := consensus.NewConsensusReactor(consensusState, fastSync) + consensusReactor.SetLogger(consensusLogger) + + p2pLogger := logger.With("module", "p2p") sw := p2p.NewSwitch(config.P2P) + sw.SetLogger(p2pLogger) sw.AddReactor("MEMPOOL", mempoolReactor) sw.AddReactor("BLOCKCHAIN", bcReactor) sw.AddReactor("CONSENSUS", consensusReactor) @@ -142,7 +155,9 @@ func NewNode(config *cfg.Config, privValidator *types.PrivValidator, clientCreat var addrBook *p2p.AddrBook if config.P2P.PexReactor { addrBook = p2p.NewAddrBook(config.P2P.AddrBookFile(), config.P2P.AddrBookStrict) + addrBook.SetLogger(p2pLogger.With("book", config.P2P.AddrBookFile())) pexReactor := p2p.NewPEXReactor(addrBook) + pexReactor.SetLogger(p2pLogger) sw.AddReactor("PEX", pexReactor) } diff --git a/p2p/glide.lock b/p2p/glide.lock deleted file mode 100644 index e396152cb..000000000 --- a/p2p/glide.lock +++ /dev/null @@ -1,153 +0,0 @@ -hash: 56a5590512e71b5bae4af7bd6c5e352008ad5725a8595c3e128cd18042f95b4c -updated: 2017-05-02T13:43:02.638937348Z -imports: -- name: github.com/btcsuite/btcd - version: 4b348c1d33373d672edd83fc576892d0e46686d2 - subpackages: - - btcec -- name: github.com/ebuchman/fail-test - version: 95f809107225be108efcf10a3509e4ea6ceef3c4 -- name: github.com/fsnotify/fsnotify - version: 4da3e2cfbabc9f751898f250b49f2439785783a1 -- name: github.com/go-kit/kit - version: 8a2988aa81f699fc1e647c3c9dddce0113ef1bfb - subpackages: - - log - - log/level - - log/term -- name: github.com/go-logfmt/logfmt - version: 390ab7935ee28ec6b286364bba9b4dd6410cb3d5 -- name: github.com/go-stack/stack - version: 100eb0c0a9c5b306ca2fb4f165df21d80ada4b82 -- name: github.com/gogo/protobuf - version: 100ba4e885062801d56799d78530b73b178a78f3 - subpackages: - - proto -- name: github.com/golang/protobuf - version: 2bba0603135d7d7f5cb73b2125beeda19c09f4ef - subpackages: - - proto -- name: github.com/gorilla/websocket - version: 3ab3a8b8831546bd18fd182c20687ca853b2bb13 -- name: github.com/hashicorp/hcl - version: 7fa7fff964d035e8a162cce3a164b3ad02ad651b - subpackages: - - hcl/ast - - hcl/parser - - hcl/scanner - - hcl/strconv - - hcl/token - - json/parser - - json/scanner - - json/token -- name: github.com/kr/logfmt - version: b84e30acd515aadc4b783ad4ff83aff3299bdfe0 -- name: github.com/magiconair/properties - version: 51463bfca2576e06c62a8504b5c0f06d61312647 -- name: github.com/mattn/go-colorable - version: ded68f7a9561c023e790de24279db7ebf473ea80 -- name: github.com/mattn/go-isatty - version: fc9e8d8ef48496124e79ae0df75490096eccf6fe -- name: github.com/mitchellh/mapstructure - version: cc8532a8e9a55ea36402aa21efdf403a60d34096 -- name: github.com/pelletier/go-buffruneio - version: c37440a7cf42ac63b919c752ca73a85067e05992 -- name: github.com/pelletier/go-toml - version: fe206efb84b2bc8e8cfafe6b4c1826622be969e3 -- name: github.com/pkg/errors - version: 645ef00459ed84a119197bfb8d8205042c6df63d -- name: github.com/spf13/afero - version: 9be650865eab0c12963d8753212f4f9c66cdcf12 - subpackages: - - mem -- name: github.com/spf13/cast - version: acbeb36b902d72a7a4c18e8f3241075e7ab763e4 -- name: github.com/spf13/cobra - version: 10f6b9d7e1631a54ad07c5c0fb71c28a1abfd3c2 -- name: github.com/spf13/jwalterweatherman - version: fa7ca7e836cf3a8bb4ebf799f472c12d7e903d66 -- name: github.com/spf13/pflag - version: 2300d0f8576fe575f71aaa5b9bbe4e1b0dc2eb51 -- name: github.com/spf13/viper - version: 0967fc9aceab2ce9da34061253ac10fb99bba5b2 -- name: github.com/stretchr/testify - version: 69483b4bd14f5845b5a1e55bca19e954e827f1d0 - subpackages: - - assert - - require -- name: github.com/tendermint/abci - version: 8d8e35ae537538c9cf6808be3ca9dd7dab81b7f6 - subpackages: - - client - - example/dummy - - types -- name: github.com/tendermint/ed25519 - version: 1f52c6f8b8a5c7908aff4497c186af344b428925 - subpackages: - - edwards25519 - - extra25519 -- name: github.com/tendermint/go-crypto - version: 197a2b270fd94ee03824b158e738fce62862d0b8 -- name: github.com/tendermint/go-wire - version: b53add0b622662731985485f3a19be7f684660b8 - subpackages: - - data -- name: github.com/tendermint/log15 - version: ae0f3d6450da9eac7074b439c8e1c3cabf0d5ce6 - subpackages: - - term -- name: github.com/tendermint/tmlibs - version: 9687e4202662c11add147906faf5503af519b4ef - subpackages: - - autofile - - clist - - common - - db - - events - - flowrate - - log - - logger - - merkle -- name: golang.org/x/crypto - version: 96846453c37f0876340a66a47f3f75b1f3a6cd2d - subpackages: - - curve25519 - - nacl/box - - nacl/secretbox - - openpgp/armor - - openpgp/errors - - poly1305 - - ripemd160 - - salsa20/salsa -- name: golang.org/x/net - version: c8c74377599bd978aee1cf3b9b63a8634051cec2 - subpackages: - - context -- name: golang.org/x/sys - version: ea9bcade75cb975a0b9738936568ab388b845617 - subpackages: - - unix -- name: golang.org/x/text - version: 19e3104b43db45fca0303f489a9536087b184802 - subpackages: - - transform - - unicode/norm -- name: google.golang.org/grpc - version: 6914ab1e338c92da4218a23d27fcd03d0ad78d46 -- name: gopkg.in/yaml.v2 - version: cd8b52f8269e0feb286dfeef29f8fe4d5b397e0b -testImports: -- name: github.com/davecgh/go-spew - version: 6d212800a42e8ab5c146b8ace3490ee17e5225f9 - subpackages: - - spew -- name: github.com/pmezard/go-difflib - version: d8ed2627bdf02c080bf22230dbb337003b7aba2d - subpackages: - - difflib -- name: github.com/tendermint/merkleeyes - version: d0aa363fd4e015e509038c3a0ec493bc62ee0b8a - subpackages: - - app - - iavl - - testutil diff --git a/p2p/peer.go b/p2p/peer.go index 51a4e1189..2602206c1 100644 --- a/p2p/peer.go +++ b/p2p/peer.go @@ -184,7 +184,7 @@ func (p *Peer) HandshakeTimeout(ourNodeInfo *NodeInfo, timeout time.Duration) er return nil } -// Addr returns peer's network address. +// Addr returns peer's remote network address. func (p *Peer) Addr() net.Addr { return p.conn.RemoteAddr() } @@ -279,10 +279,8 @@ func (p *Peer) Get(key string) interface{} { } func dial(addr *NetAddress, config *PeerConfig) (net.Conn, error) { - // log.Info("Dialing address", "address", addr) conn, err := addr.DialTimeout(config.DialTimeout * time.Second) if err != nil { - // log.Info("Failed dialing address", "address", addr, "error", err) return nil, err } return conn, nil diff --git a/p2p/switch.go b/p2p/switch.go index 18fa78837..ec157aca7 100644 --- a/p2p/switch.go +++ b/p2p/switch.go @@ -310,7 +310,6 @@ func (sw *Switch) dialSeed(addr *NetAddress) { peer, err := sw.DialPeerWithAddress(addr, true) if err != nil { sw.Logger.Error("Error dialing seed", "error", err) - return } else { sw.Logger.Info("Connected to seed", "peer", peer) } @@ -320,10 +319,11 @@ func (sw *Switch) DialPeerWithAddress(addr *NetAddress, persistent bool) (*Peer, sw.dialing.Set(addr.IP.String(), addr) defer sw.dialing.Delete(addr.IP.String()) + sw.Logger.Info("Dialing peer", "address", addr) peer, err := newOutboundPeerWithConfig(addr, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey, sw.peerConfig) peer.SetLogger(sw.Logger.With("peer", addr)) if err != nil { - sw.Logger.Info("Failed dialing peer", "address", addr, "error", err) + sw.Logger.Error("Failed to dial peer", "address", addr, "error", err) return nil, err } if persistent { @@ -331,7 +331,7 @@ func (sw *Switch) DialPeerWithAddress(addr *NetAddress, persistent bool) (*Peer, } err = sw.AddPeer(peer) if err != nil { - sw.Logger.Info("Failed adding peer", "address", addr, "error", err) + sw.Logger.Error("Failed to add peer", "address", addr, "error", err) peer.CloseConn() return nil, err } diff --git a/p2p/types.go b/p2p/types.go index 4f3e4c1d8..1d3770b57 100644 --- a/p2p/types.go +++ b/p2p/types.go @@ -6,7 +6,7 @@ import ( "strconv" "strings" - "github.com/tendermint/go-crypto" + crypto "github.com/tendermint/go-crypto" ) const maxNodeInfoSize = 10240 // 10Kb @@ -68,6 +68,10 @@ func (info *NodeInfo) ListenPort() int { return port_i } +func (info NodeInfo) String() string { + return fmt.Sprintf("NodeInfo{pk: %v, moniker: %v, network: %v [remote %v, listen %v], version: %v (%v)}", info.PubKey, info.Moniker, info.Network, info.RemoteAddr, info.ListenAddr, info.Version, info.Other) +} + func splitVersion(version string) (string, string, string, error) { spl := strings.Split(version, ".") if len(spl) != 3 { diff --git a/proxy/multi_app_conn.go b/proxy/multi_app_conn.go index 0556a824f..36286f340 100644 --- a/proxy/multi_app_conn.go +++ b/proxy/multi_app_conn.go @@ -68,9 +68,9 @@ func (app *multiAppConn) Query() AppConnQuery { } func (app *multiAppConn) OnStart() error { - // query connection querycli, err := app.clientCreator.NewABCIClient() + querycli.SetLogger(app.Logger.With("module", "abci-client", "connection", "query")) if err != nil { return err } @@ -78,6 +78,7 @@ func (app *multiAppConn) OnStart() error { // mempool connection memcli, err := app.clientCreator.NewABCIClient() + memcli.SetLogger(app.Logger.With("module", "abci-client", "connection", "mempool")) if err != nil { return err } @@ -85,6 +86,7 @@ func (app *multiAppConn) OnStart() error { // consensus connection concli, err := app.clientCreator.NewABCIClient() + concli.SetLogger(app.Logger.With("module", "abci-client", "connection", "consensus")) if err != nil { return err } diff --git a/rpc/lib/client/http_client.go b/rpc/lib/client/http_client.go index 33daf353a..12cf793a6 100644 --- a/rpc/lib/client/http_client.go +++ b/rpc/lib/client/http_client.go @@ -13,6 +13,7 @@ import ( "github.com/pkg/errors" types "github.com/tendermint/tendermint/rpc/lib/types" + cmn "github.com/tendermint/tmlibs/common" ) // HTTPClient is a common interface for JSONRPCClient and URIClient. @@ -26,9 +27,7 @@ func makeHTTPDialer(remoteAddr string) (string, func(string, string) (net.Conn, parts := strings.SplitN(remoteAddr, "://", 2) var protocol, address string if len(parts) != 2 { - // log.Warn("WARNING (tendermint/rpc/lib): Please use fully formed listening addresses, including the tcp:// or unix:// prefix") - protocol = types.SocketType(remoteAddr) - address = remoteAddr + cmn.PanicSanity(fmt.Sprintf("Expected fully formed listening address, including the tcp:// or unix:// prefix, given %s", remoteAddr)) } else { protocol, address = parts[0], parts[1] } diff --git a/state/execution.go b/state/execution.go index aefb66aeb..2dfdb1526 100644 --- a/state/execution.go +++ b/state/execution.go @@ -259,7 +259,7 @@ func (s *State) CommitStateUpdateMempool(proxyAppConn proxy.AppConnConsensus, bl s.logger.Debug("Commit.Log: " + res.Log) } - s.logger.Info("Committed state", "hash", fmt.Sprintf("%X", res.Data)) + s.logger.Info("Committed state", "hash", res.Data) // Set the state's new AppHash s.AppHash = res.Data diff --git a/state/state.go b/state/state.go index 6b4a46bd8..8f1a6a964 100644 --- a/state/state.go +++ b/state/state.go @@ -78,10 +78,6 @@ func (s *State) SetLogger(l log.Logger) { s.logger = l } -func (s *State) GetLogger() log.Logger { - return s.logger -} - func (s *State) Copy() *State { return &State{ db: s.db, diff --git a/types/block.go b/types/block.go index 0f0fc75b6..725f60bb9 100644 --- a/types/block.go +++ b/types/block.go @@ -8,7 +8,7 @@ import ( "strings" "time" - "github.com/tendermint/go-wire" + wire "github.com/tendermint/go-wire" "github.com/tendermint/go-wire/data" . "github.com/tendermint/tmlibs/common" "github.com/tendermint/tmlibs/merkle" @@ -98,7 +98,7 @@ func (b *Block) FillHeader() { // Computes and returns the block hash. // If the block is incomplete, block hash is nil for safety. -func (b *Block) Hash() []byte { +func (b *Block) Hash() data.Bytes { // fmt.Println(">>", b.Data) if b == nil || b.Header == nil || b.Data == nil || b.LastCommit == nil { return nil diff --git a/types/priv_validator.go b/types/priv_validator.go index 8d598ff1d..5fc081e42 100644 --- a/types/priv_validator.go +++ b/types/priv_validator.go @@ -181,7 +181,7 @@ func (privVal *PrivValidator) SignProposal(chainID string, proposal *Proposal) e defer privVal.mtx.Unlock() signature, err := privVal.signBytesHRS(proposal.Height, proposal.Round, stepPropose, SignBytes(chainID, proposal)) if err != nil { - return errors.New(Fmt("Error signing proposal: %v", err)) + return fmt.Errorf("Error signing proposal: %v", err) } proposal.Signature = signature return nil From c5bccc5474f6ecc2f083c7e34e9ccb1be2de5312 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Sat, 13 May 2017 17:05:44 +0200 Subject: [PATCH 289/309] set missing logger on switch ``` panic: runtime error: invalid memory address or nil pointer dereference [signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x882cec] goroutine 328 [running]: github.com/tendermint/tendermint/p2p.(*Switch).DialPeerWithAddress(0xc42000a500, 0xc4202088d0, 0xc420403500, 0x0, 0x0, 0x0) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/switch.go:324 +0x2fc github.com/tendermint/tendermint/p2p.(*PEXReactor).ensurePeers.func1(0xc4201663f0, 0xc4202088d0) /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/pex_reactor.go:280 +0x3e created by github.com/tendermint/tendermint/p2p.(*PEXReactor).ensurePeers /home/vagrant/go/src/github.com/tendermint/tendermint/p2p/pex_reactor.go:284 +0x5d4 ``` --- p2p/pex_reactor_test.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/p2p/pex_reactor_test.go b/p2p/pex_reactor_test.go index 76738c864..2ce131a05 100644 --- a/p2p/pex_reactor_test.go +++ b/p2p/pex_reactor_test.go @@ -75,6 +75,8 @@ func TestPEXReactorRunning(t *testing.T) { // create switches for i := 0; i < N; i++ { switches[i] = makeSwitch(config, i, "127.0.0.1", "123.123.123", func(i int, sw *Switch) *Switch { + sw.SetLogger(log.TestingLogger().With("switch", i)) + r := NewPEXReactor(book) r.SetLogger(log.TestingLogger()) r.SetEnsurePeersPeriod(250 * time.Millisecond) From 4fe67652ff1e10839096dcff81d2588cfbca7fb5 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Sun, 14 May 2017 00:24:58 +0200 Subject: [PATCH 290/309] move SetLogger down --- p2p/switch.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/p2p/switch.go b/p2p/switch.go index ec157aca7..5ccdc114e 100644 --- a/p2p/switch.go +++ b/p2p/switch.go @@ -321,11 +321,11 @@ func (sw *Switch) DialPeerWithAddress(addr *NetAddress, persistent bool) (*Peer, sw.Logger.Info("Dialing peer", "address", addr) peer, err := newOutboundPeerWithConfig(addr, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey, sw.peerConfig) - peer.SetLogger(sw.Logger.With("peer", addr)) if err != nil { sw.Logger.Error("Failed to dial peer", "address", addr, "error", err) return nil, err } + peer.SetLogger(sw.Logger.With("peer", addr)) if persistent { peer.makePersistent() } @@ -548,11 +548,11 @@ func makeSwitch(cfg *cfg.P2PConfig, i int, network, version string, initSwitch f func (sw *Switch) addPeerWithConnection(conn net.Conn) error { peer, err := newInboundPeer(conn, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey) - peer.SetLogger(sw.Logger.With("peer", conn.RemoteAddr())) if err != nil { conn.Close() return err } + peer.SetLogger(sw.Logger.With("peer", conn.RemoteAddr())) if err = sw.AddPeer(peer); err != nil { conn.Close() return err @@ -563,11 +563,11 @@ func (sw *Switch) addPeerWithConnection(conn net.Conn) error { func (sw *Switch) addPeerWithConnectionAndConfig(conn net.Conn, config *PeerConfig) error { peer, err := newInboundPeerWithConfig(conn, sw.reactorsByCh, sw.chDescs, sw.StopPeerForError, sw.nodePrivKey, config) - peer.SetLogger(sw.Logger.With("peer", conn.RemoteAddr())) if err != nil { conn.Close() return err } + peer.SetLogger(sw.Logger.With("peer", conn.RemoteAddr())) if err = sw.AddPeer(peer); err != nil { conn.Close() return err From 157ec8af2d6ea6d3182dc38cbab261be02e87eb8 Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Fri, 12 May 2017 22:22:22 +0200 Subject: [PATCH 291/309] Add json tags to validator set --- types/validator_set.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/types/validator_set.go b/types/validator_set.go index f6a8faf46..7d019e02e 100644 --- a/types/validator_set.go +++ b/types/validator_set.go @@ -6,9 +6,9 @@ import ( "sort" "strings" + "github.com/tendermint/go-wire" cmn "github.com/tendermint/tmlibs/common" "github.com/tendermint/tmlibs/merkle" - "github.com/tendermint/go-wire" ) // ValidatorSet represent a set of *Validator at a given height. @@ -23,8 +23,8 @@ import ( // TODO: consider validator Accum overflow // TODO: move valset into an iavl tree where key is 'blockbonded|pubkey' type ValidatorSet struct { - Validators []*Validator // NOTE: persisted via reflect, must be exported. - Proposer *Validator + Validators []*Validator `json:"validators"` + Proposer *Validator `json:"proposer"` // cached (unexported) totalVotingPower int64 From 2b324b7eb9267387c198b6dc942bfc9b95b33f59 Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Sat, 13 May 2017 11:33:35 +0200 Subject: [PATCH 292/309] RPC returns pretty formated json --- rpc/lib/server/handlers.go | 2 +- rpc/lib/server/http_server.go | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/rpc/lib/server/handlers.go b/rpc/lib/server/handlers.go index f35a5df8d..5745f6fa1 100644 --- a/rpc/lib/server/handlers.go +++ b/rpc/lib/server/handlers.go @@ -539,7 +539,7 @@ func (wsc *wsConnection) writeRoutine() { return } case msg := <-wsc.writeChan: - jsonBytes, err := json.Marshal(msg) + jsonBytes, err := json.MarshalIndent(msg, "", " ") if err != nil { wsc.Logger.Error("Failed to marshal RPCResponse to JSON", "error", err) } else { diff --git a/rpc/lib/server/http_server.go b/rpc/lib/server/http_server.go index 01b5b17d9..3b856b5db 100644 --- a/rpc/lib/server/http_server.go +++ b/rpc/lib/server/http_server.go @@ -48,7 +48,7 @@ func StartHTTPServer(listenAddr string, handler http.Handler, logger log.Logger) } func WriteRPCResponseHTTPError(w http.ResponseWriter, httpCode int, res types.RPCResponse) { - jsonBytes, err := json.Marshal(res) + jsonBytes, err := json.MarshalIndent(res, "", " ") if err != nil { panic(err) } @@ -59,7 +59,7 @@ func WriteRPCResponseHTTPError(w http.ResponseWriter, httpCode int, res types.RP } func WriteRPCResponseHTTP(w http.ResponseWriter, res types.RPCResponse) { - jsonBytes, err := json.Marshal(res) + jsonBytes, err := json.MarshalIndent(res, "", " ") if err != nil { panic(err) } From 926fb83e33d9910f4a31704b42b070e462248874 Mon Sep 17 00:00:00 2001 From: Ethan Frey Date: Sun, 14 May 2017 19:10:58 +0200 Subject: [PATCH 293/309] Re-added comment --- types/validator_set.go | 1 + 1 file changed, 1 insertion(+) diff --git a/types/validator_set.go b/types/validator_set.go index 7d019e02e..214e073d0 100644 --- a/types/validator_set.go +++ b/types/validator_set.go @@ -23,6 +23,7 @@ import ( // TODO: consider validator Accum overflow // TODO: move valset into an iavl tree where key is 'blockbonded|pubkey' type ValidatorSet struct { + // NOTE: persisted via reflect, must be exported. Validators []*Validator `json:"validators"` Proposer *Validator `json:"proposer"` From 1dfb95f7198ef3296912916b73ae7190e7ab919a Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Sun, 14 May 2017 21:44:01 +0200 Subject: [PATCH 294/309] [consensus] color code different consensus instances in consensus tests (Refs #492) --- consensus/byzantine_test.go | 11 ++++++----- consensus/common_test.go | 20 ++++++++++++++++++-- consensus/reactor_test.go | 6 +++--- glide.lock | 17 ++++++++++++----- 4 files changed, 39 insertions(+), 15 deletions(-) diff --git a/consensus/byzantine_test.go b/consensus/byzantine_test.go index 94bd82dae..56aeeeeaa 100644 --- a/consensus/byzantine_test.go +++ b/consensus/byzantine_test.go @@ -9,7 +9,6 @@ import ( "github.com/tendermint/tendermint/types" . "github.com/tendermint/tmlibs/common" "github.com/tendermint/tmlibs/events" - "github.com/tendermint/tmlibs/log" ) func init() { @@ -27,16 +26,17 @@ func init() { // Heal partition and ensure A sees the commit func TestByzantine(t *testing.T) { N := 4 + logger := consensusLogger() css := randConsensusNet(N, "consensus_byzantine_test", newMockTickerFunc(false), newCounter) // give the byzantine validator a normal ticker css[0].SetTimeoutTicker(NewTimeoutTicker()) switches := make([]*p2p.Switch, N) - p2pLogger := log.TestingLogger().With("module", "p2p") + p2pLogger := logger.With("module", "p2p") for i := 0; i < N; i++ { switches[i] = p2p.NewSwitch(config.P2P) - switches[i].SetLogger(p2pLogger) + switches[i].SetLogger(p2pLogger.With("validator", i)) } reactors := make([]p2p.Reactor, N) @@ -50,6 +50,7 @@ func TestByzantine(t *testing.T) { } }() eventChans := make([]chan interface{}, N) + eventLogger := logger.With("module", "events") for i := 0; i < N; i++ { if i == 0 { css[i].privValidator = NewByzantinePrivValidator(css[i].privValidator.(*types.PrivValidator)) @@ -63,7 +64,7 @@ func TestByzantine(t *testing.T) { } eventSwitch := events.NewEventSwitch() - eventSwitch.SetLogger(log.TestingLogger().With("module", "events")) + eventSwitch.SetLogger(eventLogger.With("validator", i)) _, err := eventSwitch.Start() if err != nil { t.Fatalf("Failed to start switch: %v", err) @@ -71,7 +72,7 @@ func TestByzantine(t *testing.T) { eventChans[i] = subscribeToEvent(eventSwitch, "tester", types.EventStringNewBlock(), 1) conR := NewConsensusReactor(css[i], true) // so we dont start the consensus states - conR.SetLogger(log.TestingLogger()) + conR.SetLogger(logger.With("validator", i)) conR.SetEventSwitch(eventSwitch) var conRI p2p.Reactor diff --git a/consensus/common_test.go b/consensus/common_test.go index 02bc8ba52..ae6e399d5 100644 --- a/consensus/common_test.go +++ b/consensus/common_test.go @@ -25,6 +25,8 @@ import ( "github.com/tendermint/abci/example/counter" "github.com/tendermint/abci/example/dummy" + + "github.com/go-kit/kit/log/term" ) // genesis, chain_id, priv_val @@ -325,18 +327,32 @@ func ensureNoNewStep(stepCh chan interface{}) { //------------------------------------------------------------------------------- // consensus nets +// consensusLogger is a TestingLogger which uses a different +// color for each validator ("validator" key must exist). +func consensusLogger() log.Logger { + return log.TestingLoggerWithColorFn(func(keyvals ...interface{}) term.FgBgColor { + for i := 0; i < len(keyvals)-1; i += 2 { + if keyvals[i] == "validator" { + return term.FgBgColor{Fg: term.Color(uint8(keyvals[i+1].(int) + 1))} + } + } + return term.FgBgColor{} + }) +} + func randConsensusNet(nValidators int, testName string, tickerFunc func() TimeoutTicker, appFunc func() abci.Application) []*ConsensusState { genDoc, privVals := randGenesisDoc(nValidators, false, 10) css := make([]*ConsensusState, nValidators) + logger := consensusLogger() for i := 0; i < nValidators; i++ { db := dbm.NewMemDB() // each state needs its own db state := sm.MakeGenesisState(db, genDoc) - state.SetLogger(log.TestingLogger().With("module", "state")) + state.SetLogger(logger.With("module", "state", "validator", i)) state.Save() thisConfig := ResetConfig(Fmt("%s_%d", testName, i)) ensureDir(path.Dir(thisConfig.Consensus.WalFile()), 0700) // dir for wal css[i] = newConsensusStateWithConfig(thisConfig, state, privVals[i], appFunc()) - css[i].SetLogger(log.TestingLogger()) + css[i].SetLogger(logger.With("validator", i)) css[i].SetTimeoutTicker(tickerFunc()) } return css diff --git a/consensus/reactor_test.go b/consensus/reactor_test.go index 03143360d..a1ab37026 100644 --- a/consensus/reactor_test.go +++ b/consensus/reactor_test.go @@ -10,7 +10,6 @@ import ( "github.com/tendermint/tendermint/p2p" "github.com/tendermint/tendermint/types" "github.com/tendermint/tmlibs/events" - "github.com/tendermint/tmlibs/log" ) func init() { @@ -23,12 +22,13 @@ func init() { func startConsensusNet(t *testing.T, css []*ConsensusState, N int, subscribeEventRespond bool) ([]*ConsensusReactor, []chan interface{}) { reactors := make([]*ConsensusReactor, N) eventChans := make([]chan interface{}, N) + logger := consensusLogger() for i := 0; i < N; i++ { reactors[i] = NewConsensusReactor(css[i], true) // so we dont start the consensus states - reactors[i].SetLogger(log.TestingLogger().With("reactor", i)) + reactors[i].SetLogger(logger.With("validator", i)) eventSwitch := events.NewEventSwitch() - eventSwitch.SetLogger(log.TestingLogger().With("module", "events")) + eventSwitch.SetLogger(logger.With("module", "events", "validator", i)) _, err := eventSwitch.Start() if err != nil { t.Fatalf("Failed to start switch: %v", err) diff --git a/glide.lock b/glide.lock index 7dfd94bd1..dcc1d6f17 100644 --- a/glide.lock +++ b/glide.lock @@ -1,10 +1,12 @@ hash: 9caff08aa026986b239e4aeb9d876bdddfacadc64a660ee8109e77a211e53436 -updated: 2017-05-13T14:12:48.997991788Z +updated: 2017-05-15T07:32:38.823266751Z imports: - name: github.com/btcsuite/btcd version: 1ae306021e323ae11c71ffb8546fbd9019e6cb6f subpackages: - btcec +- name: github.com/clipperhouse/typewriter + version: c1a48da378ebb7db1db9f35981b5cc24bf2e5b85 - name: github.com/davecgh/go-spew version: 04cdfd42973bb9c8589fd6a731800cf222fde1a9 subpackages: @@ -74,7 +76,7 @@ imports: - name: github.com/spf13/cast version: acbeb36b902d72a7a4c18e8f3241075e7ab763e4 - name: github.com/spf13/cobra - version: 90687e7bfc7e1e5cd88eb1f513f32f01dc03dd7c + version: e9078fccb8b1e6914310b96d5e1be43713f3a372 - name: github.com/spf13/jwalterweatherman version: 8f07c835e5cc1450c082fe3a439cf87b0cbb2d99 - name: github.com/spf13/pflag @@ -117,7 +119,7 @@ imports: - name: github.com/tendermint/go-crypto version: e71bbb2509b586f0b24f120b6ba57f32aefa1579 - name: github.com/tendermint/go-wire - version: 82d31b6afb3c438639bffc5e1c7318b9a55285b3 + version: 8b47d1a9dd4e94ee0e099216c382847342405ab9 subpackages: - data - data/base58 @@ -129,7 +131,7 @@ imports: - iavl - testutil - name: github.com/tendermint/tmlibs - version: 8f5a175ff4c869fedde710615a11f5745ff69bf3 + version: 4fdeaa70afa2556360a396faaa82e640b9912b0c subpackages: - autofile - cli @@ -163,7 +165,7 @@ imports: - lex/httplex - trace - name: golang.org/x/sys - version: f845067cf72a21fb4929b0e6a35273bd83b56396 + version: 1e99a4f9d247b28c670884b9a8d6801f39a47b77 subpackages: - unix - name: golang.org/x/text @@ -173,6 +175,11 @@ imports: - transform - unicode/bidi - unicode/norm +- name: golang.org/x/tools + version: 144c6642b5d832d6c44a53dad6ee61665dd432ce + subpackages: + - go/ast/astutil + - imports - name: google.golang.org/genproto version: 411e09b969b1170a9f0c467558eb4c4c110d9c77 subpackages: From 0a4ab7e38fe77f29a192bc772e427b2b081cb045 Mon Sep 17 00:00:00 2001 From: Adrian Brink Date: Tue, 16 May 2017 09:50:52 +0200 Subject: [PATCH 295/309] Update README.md --- docs/architecture/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/architecture/README.md b/docs/architecture/README.md index dd97a5b75..dc9c62a9e 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -1,6 +1,6 @@ # Architecture Decision Records -This is a location to record all high-level architecture decisions in the tendermin project. Not the implementation details, but the reasoning that happened. This should be refered to for guidance of the "right way" to extend the application. And if we notice that the original decisions were lacking, we should have another open discussion, record the new decisions here, and then modify the code to match. +This is a location to record all high-level architecture decisions in the tendermint project. Not the implementation details, but the reasoning that happened. This should be refered to for guidance of the "right way" to extend the application. And if we notice that the original decisions were lacking, we should have another open discussion, record the new decisions here, and then modify the code to match. This is like our guide and mentor when Jae and Bucky are offline.... The concept comes from a [blog post](https://product.reverb.com/documenting-architecture-decisions-the-reverb-way-a3563bb24bd0#.78xhdix6t) that resonated among the team when Anton shared it. From 05a82045089d99164aff92a9d2cac3c128a88f9c Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Mon, 15 May 2017 19:33:45 +0200 Subject: [PATCH 296/309] per module log levels (Refs #493) --- cmd/tendermint/commands/flags/log_level.go | 85 +++++++++++++++++++ .../commands/flags/log_level_test.go | 42 +++++++++ cmd/tendermint/commands/root.go | 20 ++++- cmd/tendermint/commands/run_node.go | 9 ++ glide.lock | 6 +- glide.yaml | 2 +- node/node.go | 13 +-- 7 files changed, 164 insertions(+), 13 deletions(-) create mode 100644 cmd/tendermint/commands/flags/log_level.go create mode 100644 cmd/tendermint/commands/flags/log_level_test.go diff --git a/cmd/tendermint/commands/flags/log_level.go b/cmd/tendermint/commands/flags/log_level.go new file mode 100644 index 000000000..361ec9d20 --- /dev/null +++ b/cmd/tendermint/commands/flags/log_level.go @@ -0,0 +1,85 @@ +package flags + +import ( + "fmt" + "strings" + + "github.com/pkg/errors" + + cfg "github.com/tendermint/tendermint/config" + "github.com/tendermint/tmlibs/log" +) + +const ( + defaultLogLevelKey = "*" +) + +// IsLogLevelSimple returns true if log level is a single word ("info", ...). +func IsLogLevelSimple(l string) bool { + return !strings.Contains(l, ":") +} + +// ParseComplexLogLevel parses complex log level - comma-separated +// list of module:level pairs with an optional *:level pair (* means +// all other modules). +// +// Example: +// ParseComplexLogLevel("consensus:debug,mempool:debug,*:error", log.NewTMLogger(os.Stdout)) +func ParseComplexLogLevel(l string, logger log.Logger) (log.Logger, error) { + if l == "" { + return nil, errors.New("Empty log level") + } + + options := make([]log.Option, 0) + + isDefaultLogLevelSet := false + var option log.Option + var err error + + list := strings.Split(l, ",") + for _, item := range list { + moduleAndLevel := strings.Split(item, ":") + + if len(moduleAndLevel) != 2 { + return nil, fmt.Errorf("Expected list in a form of \"module:level\" pairs, given pair %s, list %s", item, list) + } + + module := moduleAndLevel[0] + level := moduleAndLevel[1] + + if module == defaultLogLevelKey { + option, err = log.AllowLevel(level) + if err != nil { + return nil, errors.Wrap(err, fmt.Sprintf("Failed to parse default log level (pair %s, list %s)", item, l)) + } + options = append(options, option) + isDefaultLogLevelSet = true + } else { + switch level { + case "debug": + option = log.AllowDebugWith("module", module) + case "info": + option = log.AllowInfoWith("module", module) + case "error": + option = log.AllowErrorWith("module", module) + case "none": + option = log.AllowNoneWith("module", module) + default: + return nil, fmt.Errorf("Expected either \"info\", \"debug\", \"error\" or \"none\" log level, given %s (pair %s, list %s)", level, item, list) + } + options = append(options, option) + + } + } + + // if "*" is not provided, set default global level + if !isDefaultLogLevelSet { + option, err = log.AllowLevel(cfg.DefaultBaseConfig().LogLevel) + if err != nil { + return nil, err + } + options = append(options, option) + } + + return log.NewFilter(logger, options...), nil +} diff --git a/cmd/tendermint/commands/flags/log_level_test.go b/cmd/tendermint/commands/flags/log_level_test.go new file mode 100644 index 000000000..6ccd5c846 --- /dev/null +++ b/cmd/tendermint/commands/flags/log_level_test.go @@ -0,0 +1,42 @@ +package flags_test + +import ( + "testing" + + tmflags "github.com/tendermint/tendermint/cmd/tendermint/commands/flags" + "github.com/tendermint/tmlibs/log" +) + +func TestIsLogLevelSimple(t *testing.T) { + simpleFlags := []string{"info", "debug", "some"} + for _, f := range simpleFlags { + if !tmflags.IsLogLevelSimple(f) { + t.Fatalf("%s is a simple flag", f) + } + } + + complexFlags := []string{"mempool:error", "mempool:error,*:debug"} + for _, f := range complexFlags { + if tmflags.IsLogLevelSimple(f) { + t.Fatalf("%s is a complex flag", f) + } + } +} + +func TestParseComplexLogLevel(t *testing.T) { + logger := log.TestingLogger() + + correctLogLevels := []string{"mempool:error", "mempool:error,*:debug", "*:debug,wire:none"} + for _, lvl := range correctLogLevels { + if _, err := tmflags.ParseComplexLogLevel(lvl, logger); err != nil { + t.Fatal(err) + } + } + + incorrectLogLevel := []string{"some", "mempool:some", "*:some,mempool:error"} + for _, lvl := range incorrectLogLevel { + if _, err := tmflags.ParseComplexLogLevel(lvl, logger); err == nil { + t.Fatalf("Expected %s to produce error", lvl) + } + } +} diff --git a/cmd/tendermint/commands/root.go b/cmd/tendermint/commands/root.go index ffd013065..79448b987 100644 --- a/cmd/tendermint/commands/root.go +++ b/cmd/tendermint/commands/root.go @@ -1,11 +1,13 @@ package commands import ( + "fmt" "os" "github.com/spf13/cobra" "github.com/spf13/viper" + tmflags "github.com/tendermint/tendermint/cmd/tendermint/commands/flags" cfg "github.com/tendermint/tendermint/config" "github.com/tendermint/tmlibs/log" ) @@ -26,9 +28,21 @@ var RootCmd = &cobra.Command{ err := viper.Unmarshal(config) config.SetRoot(config.RootDir) cfg.EnsureRoot(config.RootDir) - logger, err = log.NewFilterByLevel(logger, config.LogLevel) - if err != nil { - return err + if tmflags.IsLogLevelSimple(config.LogLevel) { + var option log.Option + switch config.LogLevel { + case "info": + option = log.AllowInfo() + case "debug": + option = log.AllowDebug() + case "error": + option = log.AllowError() + case "none": + option = log.AllowNone() + default: + return fmt.Errorf("Expected log level to be either \"info\", \"debug\", \"error\" or \"none\", given %s", config.LogLevel) + } + logger = log.NewFilter(logger, option) } return err }, diff --git a/cmd/tendermint/commands/run_node.go b/cmd/tendermint/commands/run_node.go index 5e38f2b5f..5eb477f77 100644 --- a/cmd/tendermint/commands/run_node.go +++ b/cmd/tendermint/commands/run_node.go @@ -7,6 +7,7 @@ import ( "github.com/spf13/cobra" + tmflags "github.com/tendermint/tendermint/cmd/tendermint/commands/flags" "github.com/tendermint/tendermint/node" "github.com/tendermint/tendermint/types" cmn "github.com/tendermint/tmlibs/common" @@ -79,6 +80,14 @@ func runNode(cmd *cobra.Command, args []string) error { } } + if !tmflags.IsLogLevelSimple(config.LogLevel) { + var err error + logger, err = tmflags.ParseComplexLogLevel(config.LogLevel, logger) + if err != nil { + return err + } + } + // Create & start node n := node.NewNodeDefault(config, logger.With("module", "node")) if _, err := n.Start(); err != nil { diff --git a/glide.lock b/glide.lock index dcc1d6f17..da38ad3b2 100644 --- a/glide.lock +++ b/glide.lock @@ -1,5 +1,5 @@ -hash: 9caff08aa026986b239e4aeb9d876bdddfacadc64a660ee8109e77a211e53436 -updated: 2017-05-15T07:32:38.823266751Z +hash: aa1fd2f52c45db131460b9dedf558ce2d2119ae9f313424578c65cf8efbf38e3 +updated: 2017-05-16T10:38:37.077880616Z imports: - name: github.com/btcsuite/btcd version: 1ae306021e323ae11c71ffb8546fbd9019e6cb6f @@ -131,7 +131,7 @@ imports: - iavl - testutil - name: github.com/tendermint/tmlibs - version: 4fdeaa70afa2556360a396faaa82e640b9912b0c + version: d0cae7b6edb4896390fd5ff82aea1bac98994bd0 subpackages: - autofile - cli diff --git a/glide.yaml b/glide.yaml index dd4993f59..f0cbd00f6 100644 --- a/glide.yaml +++ b/glide.yaml @@ -27,7 +27,7 @@ import: subpackages: - data - package: github.com/tendermint/tmlibs - version: develop + version: feature/log-levels-per-key-in-filter subpackages: - autofile - cli diff --git a/node/node.go b/node/node.go index ecfdef45a..ac8908345 100644 --- a/node/node.go +++ b/node/node.go @@ -70,12 +70,13 @@ func NewNode(config *cfg.Config, privValidator *types.PrivValidator, clientCreat blockStoreDB := dbm.NewDB("blockstore", config.DBBackend, config.DBDir()) blockStore := bc.NewBlockStore(blockStoreDB) + consensusLogger := logger.With("module", "consensus") + stateLogger := logger.With("module", "state") + // Get State stateDB := dbm.NewDB("state", config.DBBackend, config.DBDir()) state := sm.GetState(stateDB, config.GenesisFile()) - state.SetLogger(logger.With("module", "state")) - - consensusLogger := logger.With("module", "consensus") + state.SetLogger(stateLogger) // Create the proxyApp, which manages connections (consensus, mempool, query) // and sync tendermint and the app by replaying any necessary blocks @@ -89,7 +90,7 @@ func NewNode(config *cfg.Config, privValidator *types.PrivValidator, clientCreat // reload the state (it may have been updated by the handshake) state = sm.LoadState(stateDB) - state.SetLogger(logger.With("module", "state")) + state.SetLogger(stateLogger) // Transaction indexing var txIndexer txindex.TxIndexer @@ -128,7 +129,7 @@ func NewNode(config *cfg.Config, privValidator *types.PrivValidator, clientCreat bcReactor.SetLogger(logger.With("module", "blockchain")) // Make MempoolReactor - mempoolLogger := logger.With("module", "consensus") + mempoolLogger := logger.With("module", "mempool") mempool := mempl.NewMempool(config.Mempool, proxyApp.Mempool()) mempool.SetLogger(mempoolLogger) mempoolReactor := mempl.NewMempoolReactor(config.Mempool, mempool) @@ -318,8 +319,8 @@ func (n *Node) startRPC() ([]net.Listener, error) { listeners := make([]net.Listener, len(listenAddrs)) for i, listenAddr := range listenAddrs { mux := http.NewServeMux() - rpcLogger := n.Logger.With("module", "rpcserver") wm := rpcserver.NewWebsocketManager(rpccore.Routes, n.evsw) + rpcLogger := n.Logger.With("module", "rpc-server") wm.SetLogger(rpcLogger) mux.HandleFunc("/websocket", wm.WebsocketHandler) rpcserver.RegisterRPCFuncs(mux, rpccore.Routes, rpcLogger) From eb9ca2325071035c33029e9e1ad883e08f1d7e3d Mon Sep 17 00:00:00 2001 From: Adrian Brink Date: Mon, 15 May 2017 11:02:40 +0200 Subject: [PATCH 297/309] log whether node is a validator in each round --- consensus/state.go | 11 +++++++++-- node/node.go | 7 +++++++ state/state.go | 1 + 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/consensus/state.go b/consensus/state.go index 222f2f233..b3bbbb2c4 100644 --- a/consensus/state.go +++ b/consensus/state.go @@ -775,15 +775,21 @@ func (cs *ConsensusState) enterPropose(height int, round int) { // Nothing more to do if we're not a validator if cs.privValidator == nil { + cs.Logger.Info("This node is not a validator") return } if !bytes.Equal(cs.Validators.GetProposer().Address, cs.privValidator.GetAddress()) { cs.Logger.Info("enterPropose: Not our turn to propose", "proposer", cs.Validators.GetProposer().Address, "privValidator", cs.privValidator) + if cs.Validators.HasAddress(cs.privValidator.GetAddress()) { + cs.Logger.Info("This node is a validator") + } else { + cs.Logger.Info("This node is not a validator") + } } else { cs.Logger.Info("enterPropose: Our turn to propose", "proposer", cs.Validators.GetProposer().Address, "privValidator", cs.privValidator) + cs.Logger.Info("This node is a validator") cs.decideProposal(height, round) - } } @@ -1141,6 +1147,7 @@ func (cs *ConsensusState) tryFinalizeCommit(height int) { cs.Logger.Error("Attempt to finalize failed. We don't have the commit block.", "height", height, "proposal-block", cs.ProposalBlock.Hash(), "commit-block", blockID.Hash) return } + // go cs.finalizeCommit(height) } @@ -1221,7 +1228,7 @@ func (cs *ConsensusState) finalizeCommit(height int) { // NOTE: If we fail before firing, these events will never fire // // TODO: Either - // * Fire before persisting state, in ApplyBlock + // * Fire before persisting state, in ApplyBlock // * Fire on start up if we haven't written any new WAL msgs // Both options mean we may fire more than once. Is that fine ? types.FireEventNewBlock(cs.evsw, types.EventDataNewBlock{block}) diff --git a/node/node.go b/node/node.go index ecfdef45a..d29892fbe 100644 --- a/node/node.go +++ b/node/node.go @@ -123,6 +123,13 @@ func NewNode(config *cfg.Config, privValidator *types.PrivValidator, clientCreat } } + // Log whether this node is a validator or an observer + if state.Validators.HasAddress(privValidator.Address) { + consensusLogger.Info("This node is a validator") + } else { + consensusLogger.Info("This node is not a validator") + } + // Make BlockchainReactor bcReactor := bc.NewBlockchainReactor(state.Copy(), proxyApp.Consensus(), blockStore, fastSync) bcReactor.SetLogger(logger.With("module", "blockchain")) diff --git a/state/state.go b/state/state.go index 8f1a6a964..808fcbe24 100644 --- a/state/state.go +++ b/state/state.go @@ -151,6 +151,7 @@ func (s *State) SetBlockAndValidators(header *types.Header, blockPartsHeader typ s.logger.Error("Error changing validator set", "error", err) // TODO: err or carry on? } + // Update validator accums and set state variables nextValSet.IncrementAccum(1) From d5113377e2ccceef1a7a9d7394f6f8d4fc18acb5 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Tue, 16 May 2017 14:00:54 +0200 Subject: [PATCH 298/309] fix tx string format --- types/tx.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/tx.go b/types/tx.go index 28b843971..b36d4440f 100644 --- a/types/tx.go +++ b/types/tx.go @@ -21,7 +21,7 @@ func (tx Tx) Hash() []byte { } func (tx Tx) String() string { - return fmt.Sprintf("Tx{%X}") + return fmt.Sprintf("Tx{%X}", tx) } type Txs []Tx From e1792c1ea521ff6c10f79d7865a027024978b629 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Tue, 16 May 2017 14:12:48 +0200 Subject: [PATCH 299/309] fix tx string format take 2 --- types/tx.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/types/tx.go b/types/tx.go index b36d4440f..0334452e1 100644 --- a/types/tx.go +++ b/types/tx.go @@ -21,7 +21,7 @@ func (tx Tx) Hash() []byte { } func (tx Tx) String() string { - return fmt.Sprintf("Tx{%X}", tx) + return fmt.Sprintf("Tx{%X}", []byte(tx)) } type Txs []Tx From fb0df75de097c2b92b4dfb5396db36e02e526bbe Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Tue, 16 May 2017 15:16:50 +0200 Subject: [PATCH 300/309] changes per Frey comments (Refs #493) --- cmd/tendermint/commands/flags/log_level.go | 20 +++--- .../commands/flags/log_level_test.go | 64 +++++++++++++------ cmd/tendermint/commands/root.go | 24 ++----- cmd/tendermint/commands/run_node.go | 9 --- 4 files changed, 61 insertions(+), 56 deletions(-) diff --git a/cmd/tendermint/commands/flags/log_level.go b/cmd/tendermint/commands/flags/log_level.go index 361ec9d20..acdd24ec2 100644 --- a/cmd/tendermint/commands/flags/log_level.go +++ b/cmd/tendermint/commands/flags/log_level.go @@ -14,22 +14,24 @@ const ( defaultLogLevelKey = "*" ) -// IsLogLevelSimple returns true if log level is a single word ("info", ...). -func IsLogLevelSimple(l string) bool { - return !strings.Contains(l, ":") -} - -// ParseComplexLogLevel parses complex log level - comma-separated +// ParseLogLevel parses complex log level - comma-separated // list of module:level pairs with an optional *:level pair (* means // all other modules). // // Example: -// ParseComplexLogLevel("consensus:debug,mempool:debug,*:error", log.NewTMLogger(os.Stdout)) -func ParseComplexLogLevel(l string, logger log.Logger) (log.Logger, error) { - if l == "" { +// ParseLogLevel("consensus:debug,mempool:debug,*:error", log.NewTMLogger(os.Stdout)) +func ParseLogLevel(lvl string, logger log.Logger) (log.Logger, error) { + if lvl == "" { return nil, errors.New("Empty log level") } + l := lvl + + // prefix simple one word levels (e.g. "info") with "*" + if !strings.Contains(l, ":") { + l = defaultLogLevelKey + ":" + l + } + options := make([]log.Option, 0) isDefaultLogLevelSet := false diff --git a/cmd/tendermint/commands/flags/log_level_test.go b/cmd/tendermint/commands/flags/log_level_test.go index 6ccd5c846..c89f3f880 100644 --- a/cmd/tendermint/commands/flags/log_level_test.go +++ b/cmd/tendermint/commands/flags/log_level_test.go @@ -1,41 +1,63 @@ package flags_test import ( + "bytes" + "strings" "testing" tmflags "github.com/tendermint/tendermint/cmd/tendermint/commands/flags" "github.com/tendermint/tmlibs/log" ) -func TestIsLogLevelSimple(t *testing.T) { - simpleFlags := []string{"info", "debug", "some"} - for _, f := range simpleFlags { - if !tmflags.IsLogLevelSimple(f) { - t.Fatalf("%s is a simple flag", f) - } +func TestParseLogLevel(t *testing.T) { + var buf bytes.Buffer + jsonLogger := log.NewTMJSONLogger(&buf) + + correctLogLevels := []struct { + lvl string + expectedLogLines []string + }{ + {"mempool:error", []string{``, ``, `{"_msg":"Mesmero","level":"error","module":"mempool"}`}}, + {"mempool:error,*:debug", []string{``, ``, `{"_msg":"Mesmero","level":"error","module":"mempool"}`}}, + {"*:debug,wire:none", []string{ + `{"_msg":"Kingpin","level":"debug","module":"mempool"}`, + `{"_msg":"Kitty Pryde","level":"info","module":"mempool"}`, + `{"_msg":"Mesmero","level":"error","module":"mempool"}`}}, } - complexFlags := []string{"mempool:error", "mempool:error,*:debug"} - for _, f := range complexFlags { - if tmflags.IsLogLevelSimple(f) { - t.Fatalf("%s is a complex flag", f) - } - } -} - -func TestParseComplexLogLevel(t *testing.T) { - logger := log.TestingLogger() - - correctLogLevels := []string{"mempool:error", "mempool:error,*:debug", "*:debug,wire:none"} - for _, lvl := range correctLogLevels { - if _, err := tmflags.ParseComplexLogLevel(lvl, logger); err != nil { + for _, c := range correctLogLevels { + logger, err := tmflags.ParseLogLevel(c.lvl, jsonLogger) + if err != nil { t.Fatal(err) } + + logger = logger.With("module", "mempool") + + buf.Reset() + + logger.Debug("Kingpin") + if have := strings.TrimSpace(buf.String()); c.expectedLogLines[0] != have { + t.Errorf("\nwant '%s'\nhave '%s'\nlevel '%s'", c.expectedLogLines[0], have, c.lvl) + } + + buf.Reset() + + logger.Info("Kitty Pryde") + if have := strings.TrimSpace(buf.String()); c.expectedLogLines[1] != have { + t.Errorf("\nwant '%s'\nhave '%s'\nlevel '%s'", c.expectedLogLines[1], have, c.lvl) + } + + buf.Reset() + + logger.Error("Mesmero") + if have := strings.TrimSpace(buf.String()); c.expectedLogLines[2] != have { + t.Errorf("\nwant '%s'\nhave '%s'\nlevel '%s'", c.expectedLogLines[2], have, c.lvl) + } } incorrectLogLevel := []string{"some", "mempool:some", "*:some,mempool:error"} for _, lvl := range incorrectLogLevel { - if _, err := tmflags.ParseComplexLogLevel(lvl, logger); err == nil { + if _, err := tmflags.ParseLogLevel(lvl, jsonLogger); err == nil { t.Fatalf("Expected %s to produce error", lvl) } } diff --git a/cmd/tendermint/commands/root.go b/cmd/tendermint/commands/root.go index 79448b987..3565f3bb8 100644 --- a/cmd/tendermint/commands/root.go +++ b/cmd/tendermint/commands/root.go @@ -1,7 +1,6 @@ package commands import ( - "fmt" "os" "github.com/spf13/cobra" @@ -26,24 +25,15 @@ var RootCmd = &cobra.Command{ Short: "Tendermint Core (BFT Consensus) in Go", PersistentPreRunE: func(cmd *cobra.Command, args []string) error { err := viper.Unmarshal(config) + if err != nil { + return err + } config.SetRoot(config.RootDir) cfg.EnsureRoot(config.RootDir) - if tmflags.IsLogLevelSimple(config.LogLevel) { - var option log.Option - switch config.LogLevel { - case "info": - option = log.AllowInfo() - case "debug": - option = log.AllowDebug() - case "error": - option = log.AllowError() - case "none": - option = log.AllowNone() - default: - return fmt.Errorf("Expected log level to be either \"info\", \"debug\", \"error\" or \"none\", given %s", config.LogLevel) - } - logger = log.NewFilter(logger, option) + logger, err = tmflags.ParseLogLevel(config.LogLevel, logger) + if err != nil { + return err } - return err + return nil }, } diff --git a/cmd/tendermint/commands/run_node.go b/cmd/tendermint/commands/run_node.go index 5eb477f77..5e38f2b5f 100644 --- a/cmd/tendermint/commands/run_node.go +++ b/cmd/tendermint/commands/run_node.go @@ -7,7 +7,6 @@ import ( "github.com/spf13/cobra" - tmflags "github.com/tendermint/tendermint/cmd/tendermint/commands/flags" "github.com/tendermint/tendermint/node" "github.com/tendermint/tendermint/types" cmn "github.com/tendermint/tmlibs/common" @@ -80,14 +79,6 @@ func runNode(cmd *cobra.Command, args []string) error { } } - if !tmflags.IsLogLevelSimple(config.LogLevel) { - var err error - logger, err = tmflags.ParseComplexLogLevel(config.LogLevel, logger) - if err != nil { - return err - } - } - // Create & start node n := node.NewNodeDefault(config, logger.With("module", "node")) if _, err := n.Start(); err != nil { From 91dc87e7c4310d343d50927416ec21500df46024 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Tue, 16 May 2017 19:06:35 +0200 Subject: [PATCH 301/309] update for a new ABCI API --- consensus/replay.go | 1 + glide.lock | 17 +++++---------- mempool/mempool_test.go | 8 +++++++ proxy/app_conn_test.go | 48 ++++++++++++++++++++++++++++++----------- proxy/client.go | 6 +++--- proxy/multi_app_conn.go | 24 +++++++++++++++------ 6 files changed, 71 insertions(+), 33 deletions(-) diff --git a/consensus/replay.go b/consensus/replay.go index c45c4b80b..af30b8894 100644 --- a/consensus/replay.go +++ b/consensus/replay.go @@ -388,6 +388,7 @@ func newMockProxyApp(appHash []byte, abciResponses *sm.ABCIResponses) proxy.AppC abciResponses: abciResponses, }) cli, _ := clientCreator.NewABCIClient() + cli.Start() return proxy.NewAppConnConsensus(cli) } diff --git a/glide.lock b/glide.lock index dcc1d6f17..f710cd9ba 100644 --- a/glide.lock +++ b/glide.lock @@ -1,12 +1,10 @@ hash: 9caff08aa026986b239e4aeb9d876bdddfacadc64a660ee8109e77a211e53436 -updated: 2017-05-15T07:32:38.823266751Z +updated: 2017-05-16T16:19:50.278000355Z imports: - name: github.com/btcsuite/btcd version: 1ae306021e323ae11c71ffb8546fbd9019e6cb6f subpackages: - btcec -- name: github.com/clipperhouse/typewriter - version: c1a48da378ebb7db1db9f35981b5cc24bf2e5b85 - name: github.com/davecgh/go-spew version: 04cdfd42973bb9c8589fd6a731800cf222fde1a9 subpackages: @@ -104,7 +102,7 @@ imports: - leveldb/table - leveldb/util - name: github.com/tendermint/abci - version: b662bc7d3439b3c2cce615e8c3502b762e133dbf + version: 5dabeffb35c027d7087a12149685daa68989168b subpackages: - client - example/counter @@ -117,9 +115,9 @@ imports: - edwards25519 - extra25519 - name: github.com/tendermint/go-crypto - version: e71bbb2509b586f0b24f120b6ba57f32aefa1579 + version: 438b16f1f84ef002d7408ecd6fc3a3974cbc9559 - name: github.com/tendermint/go-wire - version: 8b47d1a9dd4e94ee0e099216c382847342405ab9 + version: 97beaedf0f4dbc035309157c92be3b30cc6e5d74 subpackages: - data - data/base58 @@ -131,7 +129,7 @@ imports: - iavl - testutil - name: github.com/tendermint/tmlibs - version: 4fdeaa70afa2556360a396faaa82e640b9912b0c + version: 812d9f9b84d1dfe4cb46ce021b3a2d97b48d1292 subpackages: - autofile - cli @@ -175,11 +173,6 @@ imports: - transform - unicode/bidi - unicode/norm -- name: golang.org/x/tools - version: 144c6642b5d832d6c44a53dad6ee61665dd432ce - subpackages: - - go/ast/astutil - - imports - name: google.golang.org/genproto version: 411e09b969b1170a9f0c467558eb4c4c110d9c77 subpackages: diff --git a/mempool/mempool_test.go b/mempool/mempool_test.go index a4ae6679e..6451adb2d 100644 --- a/mempool/mempool_test.go +++ b/mempool/mempool_test.go @@ -18,7 +18,15 @@ func TestSerialReap(t *testing.T) { app.SetOption("serial", "on") cc := proxy.NewLocalClientCreator(app) appConnMem, _ := cc.NewABCIClient() + appConnMem.SetLogger(log.TestingLogger().With("module", "abci-client", "connection", "mempool")) + if _, err := appConnMem.Start(); err != nil { + t.Fatalf("Error starting ABCI client: %v", err.Error()) + } appConnCon, _ := cc.NewABCIClient() + appConnCon.SetLogger(log.TestingLogger().With("module", "abci-client", "connection", "consensus")) + if _, err := appConnCon.Start(); err != nil { + t.Fatalf("Error starting ABCI client: %v", err.Error()) + } mempool := NewMempool(config.Mempool, appConnMem) mempool.SetLogger(log.TestingLogger()) diff --git a/proxy/app_conn_test.go b/proxy/app_conn_test.go index f9c6afc98..159e0b3e1 100644 --- a/proxy/app_conn_test.go +++ b/proxy/app_conn_test.go @@ -9,6 +9,7 @@ import ( "github.com/tendermint/abci/server" "github.com/tendermint/abci/types" cmn "github.com/tendermint/tmlibs/common" + "github.com/tendermint/tmlibs/log" ) //---------------------------------------- @@ -48,16 +49,23 @@ func TestEcho(t *testing.T) { clientCreator := NewRemoteClientCreator(sockPath, SOCKET, true) // Start server - s, err := server.NewSocketServer(sockPath, dummy.NewDummyApplication()) - if err != nil { - cmn.Exit(err.Error()) + s := server.NewSocketServer(sockPath, dummy.NewDummyApplication()) + s.SetLogger(log.TestingLogger().With("module", "abci-server")) + if _, err := s.Start(); err != nil { + t.Fatalf("Error starting socket server: %v", err.Error()) } defer s.Stop() + // Start client cli, err := clientCreator.NewABCIClient() if err != nil { - cmn.Exit(err.Error()) + t.Fatalf("Error creating ABCI client: %v", err.Error()) } + cli.SetLogger(log.TestingLogger().With("module", "abci-client")) + if _, err := cli.Start(); err != nil { + t.Fatalf("Error starting ABCI client: %v", err.Error()) + } + proxy := NewAppConnTest(cli) t.Log("Connected") @@ -71,17 +79,25 @@ func BenchmarkEcho(b *testing.B) { b.StopTimer() // Initialize sockPath := cmn.Fmt("unix:///tmp/echo_%v.sock", cmn.RandStr(6)) clientCreator := NewRemoteClientCreator(sockPath, SOCKET, true) + // Start server - s, err := server.NewSocketServer(sockPath, dummy.NewDummyApplication()) - if err != nil { - cmn.Exit(err.Error()) + s := server.NewSocketServer(sockPath, dummy.NewDummyApplication()) + s.SetLogger(log.TestingLogger().With("module", "abci-server")) + if _, err := s.Start(); err != nil { + b.Fatalf("Error starting socket server: %v", err.Error()) } defer s.Stop() + // Start client cli, err := clientCreator.NewABCIClient() if err != nil { - cmn.Exit(err.Error()) + b.Fatalf("Error creating ABCI client: %v", err.Error()) } + cli.SetLogger(log.TestingLogger().With("module", "abci-client")) + if _, err := cli.Start(); err != nil { + b.Fatalf("Error starting ABCI client: %v", err.Error()) + } + proxy := NewAppConnTest(cli) b.Log("Connected") echoString := strings.Repeat(" ", 200) @@ -100,17 +116,25 @@ func BenchmarkEcho(b *testing.B) { func TestInfo(t *testing.T) { sockPath := cmn.Fmt("unix:///tmp/echo_%v.sock", cmn.RandStr(6)) clientCreator := NewRemoteClientCreator(sockPath, SOCKET, true) + // Start server - s, err := server.NewSocketServer(sockPath, dummy.NewDummyApplication()) - if err != nil { - cmn.Exit(err.Error()) + s := server.NewSocketServer(sockPath, dummy.NewDummyApplication()) + s.SetLogger(log.TestingLogger().With("module", "abci-server")) + if _, err := s.Start(); err != nil { + t.Fatalf("Error starting socket server: %v", err.Error()) } defer s.Stop() + // Start client cli, err := clientCreator.NewABCIClient() if err != nil { - cmn.Exit(err.Error()) + t.Fatalf("Error creating ABCI client: %v", err.Error()) } + cli.SetLogger(log.TestingLogger().With("module", "abci-client")) + if _, err := cli.Start(); err != nil { + t.Fatalf("Error starting ABCI client: %v", err.Error()) + } + proxy := NewAppConnTest(cli) t.Log("Connected") diff --git a/proxy/client.go b/proxy/client.go index 5720cce30..a70da1cae 100644 --- a/proxy/client.go +++ b/proxy/client.go @@ -1,9 +1,10 @@ package proxy import ( - "fmt" "sync" + "github.com/pkg/errors" + abcicli "github.com/tendermint/abci/client" "github.com/tendermint/abci/example/dummy" "github.com/tendermint/abci/types" @@ -51,10 +52,9 @@ func NewRemoteClientCreator(addr, transport string, mustConnect bool) ClientCrea } func (r *remoteClientCreator) NewABCIClient() (abcicli.Client, error) { - // Run forever in a loop remoteApp, err := abcicli.NewClient(r.addr, r.transport, r.mustConnect) if err != nil { - return nil, fmt.Errorf("Failed to connect to proxy: %v", err) + return nil, errors.Wrap(err, "Failed to connect to proxy") } return remoteApp, nil } diff --git a/proxy/multi_app_conn.go b/proxy/multi_app_conn.go index 36286f340..32c615202 100644 --- a/proxy/multi_app_conn.go +++ b/proxy/multi_app_conn.go @@ -1,6 +1,8 @@ package proxy import ( + "github.com/pkg/errors" + cmn "github.com/tendermint/tmlibs/common" ) @@ -70,25 +72,34 @@ func (app *multiAppConn) Query() AppConnQuery { func (app *multiAppConn) OnStart() error { // query connection querycli, err := app.clientCreator.NewABCIClient() - querycli.SetLogger(app.Logger.With("module", "abci-client", "connection", "query")) if err != nil { - return err + return errors.Wrap(err, "Error creating ABCI client (query connection)") + } + querycli.SetLogger(app.Logger.With("module", "abci-client", "connection", "query")) + if _, err := querycli.Start(); err != nil { + return errors.Wrap(err, "Error starting ABCI client (query connection)") } app.queryConn = NewAppConnQuery(querycli) // mempool connection memcli, err := app.clientCreator.NewABCIClient() - memcli.SetLogger(app.Logger.With("module", "abci-client", "connection", "mempool")) if err != nil { - return err + return errors.Wrap(err, "Error creating ABCI client (mempool connection)") + } + memcli.SetLogger(app.Logger.With("module", "abci-client", "connection", "mempool")) + if _, err := memcli.Start(); err != nil { + return errors.Wrap(err, "Error starting ABCI client (mempool connection)") } app.mempoolConn = NewAppConnMempool(memcli) // consensus connection concli, err := app.clientCreator.NewABCIClient() - concli.SetLogger(app.Logger.With("module", "abci-client", "connection", "consensus")) if err != nil { - return err + return errors.Wrap(err, "Error creating ABCI client (consensus connection)") + } + concli.SetLogger(app.Logger.With("module", "abci-client", "connection", "consensus")) + if _, err := concli.Start(); err != nil { + return errors.Wrap(err, "Error starting ABCI client (consensus connection)") } app.consensusConn = NewAppConnConsensus(concli) @@ -96,5 +107,6 @@ func (app *multiAppConn) OnStart() error { if app.handshaker != nil { return app.handshaker.Handshake(app) } + return nil } From cc2b430e689eb2fed016021e01fb0deed70af83e Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Wed, 17 May 2017 00:12:56 +0200 Subject: [PATCH 302/309] update glide and changelog --- CHANGELOG.md | 23 ++++++++++++++++++++++- glide.lock | 18 +++++++++--------- glide.yaml | 2 +- 3 files changed, 32 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 93fde7388..07165ada9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,15 +13,36 @@ BREAKING CHANGES: } ``` +- New config + - Isolate viper to cmd/tendermint/commands + - config structs: Base, P2P, Mempool, Consensus + - Remove config/tendermint and config/tendermint_test. Defaults are handled by viper and DefaultConfig() / TestConfig() functions. Tests do not read config from file +- New logging +- RPC serialization +- lowercase json names for ValidatorSet fields +- Send InitChain in handshake if appBlockHeight == 0 +- [types] `[]byte -> data.Bytes` +- Introduce EventDataInner for serializing events +- remove all use of go-wire around user interfaces +- rpc responses no longer have type information :) + + +FEATURES: + +- Log if a node is validator or not in every consensus round +- Use ldflags to set git hash as part of the version + IMPROVEMENTS: - Merge `tendermint/go-p2p -> tendermint/tendermint/p2p` and `tendermint/go-rpc -> tendermint/tendermint/rpc/lib` - Update paths for grand repo merge: - `go-common -> tmlibs/common` - `go-data -> go-wire/data` - - All other `go-*` libs, except `go-crypto`, merged under `tmlibs` + - All other `go-*` libs, except `go-crypto` and `go-wire`, merged under `tmlibs` - Return HTTP status codes with errors for RPC responses - Use `.Wrap()` and `.Unwarp()` instead of eg. `PubKeyS` for `go-crypto` types +- Color code different instances of the consensus for tests +- RPC JSON responses use pretty printing (json.MarshalIndent) ## 0.9.2 (April 26, 2017) diff --git a/glide.lock b/glide.lock index f710cd9ba..9fd20fd8c 100644 --- a/glide.lock +++ b/glide.lock @@ -1,8 +1,8 @@ hash: 9caff08aa026986b239e4aeb9d876bdddfacadc64a660ee8109e77a211e53436 -updated: 2017-05-16T16:19:50.278000355Z +updated: 2017-05-16T23:51:45.470827916+02:00 imports: - name: github.com/btcsuite/btcd - version: 1ae306021e323ae11c71ffb8546fbd9019e6cb6f + version: 40f4997b95ac18e20c5ffc54dc3c84036b1f1bf5 subpackages: - btcec - name: github.com/davecgh/go-spew @@ -24,7 +24,7 @@ imports: - name: github.com/go-stack/stack version: 7a2f19628aabfe68f0766b59e74d6315f8347d22 - name: github.com/gogo/protobuf - version: 30433562cfbf487fe1df7cd26c7bab168d2f14d0 + version: 9df9efe4c742f1a2bfdedf1c3b6902fc6e814c6b subpackages: - proto - name: github.com/golang/protobuf @@ -60,7 +60,7 @@ imports: - name: github.com/pelletier/go-buffruneio version: c37440a7cf42ac63b919c752ca73a85067e05992 - name: github.com/pelletier/go-toml - version: 685a1f1cb7a66b9cadbe8f1ac49d9f8f567d6a9d + version: 5c26a6ff6fd178719e15decac1c8196da0d7d6d1 - name: github.com/pkg/errors version: c605e284fe17294bda444b34710735b29d1a9d90 - name: github.com/pmezard/go-difflib @@ -74,7 +74,7 @@ imports: - name: github.com/spf13/cast version: acbeb36b902d72a7a4c18e8f3241075e7ab763e4 - name: github.com/spf13/cobra - version: e9078fccb8b1e6914310b96d5e1be43713f3a372 + version: 4cdb38c072b86bf795d2c81de50784d9fdd6eb77 - name: github.com/spf13/jwalterweatherman version: 8f07c835e5cc1450c082fe3a439cf87b0cbb2d99 - name: github.com/spf13/pflag @@ -129,7 +129,7 @@ imports: - iavl - testutil - name: github.com/tendermint/tmlibs - version: 812d9f9b84d1dfe4cb46ce021b3a2d97b48d1292 + version: 67f558cff0d3fc08eac951fcc39cf999101e36da subpackages: - autofile - cli @@ -142,7 +142,7 @@ imports: - merkle - test - name: golang.org/x/crypto - version: ab89591268e0c8b748cbe4047b00197516011af5 + version: 0fe963104e9d1877082f8fb38f816fcd97eb1d10 subpackages: - curve25519 - nacl/box @@ -153,7 +153,7 @@ imports: - ripemd160 - salsa20/salsa - name: golang.org/x/net - version: 84f0e6f92b10139f986b1756e149a7d9de270cdc + version: 34057069f4ab13dc4433c68d368737ebeafcccdc subpackages: - context - http2 @@ -178,7 +178,7 @@ imports: subpackages: - googleapis/rpc/status - name: google.golang.org/grpc - version: 1c69e4cae0f5180ce7d8b472bf0a55d2654fe31b + version: 3419b42955675df23457629c75f58eb8dcd56954 subpackages: - codes - credentials diff --git a/glide.yaml b/glide.yaml index f0cbd00f6..dd4993f59 100644 --- a/glide.yaml +++ b/glide.yaml @@ -27,7 +27,7 @@ import: subpackages: - data - package: github.com/tendermint/tmlibs - version: feature/log-levels-per-key-in-filter + version: develop subpackages: - autofile - cli From 6d83c60c407b6f5e72da4b33b768347f0999e616 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Tue, 16 May 2017 21:31:19 +0200 Subject: [PATCH 303/309] [types] dont hash validator.Accum --- CHANGELOG.md | 1 + types/validator.go | 19 +++++++++++++++---- types/validator_set.go | 1 - types/vote_set_test.go | 1 - 4 files changed, 16 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 07165ada9..5b1cd54e3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,6 +25,7 @@ BREAKING CHANGES: - Introduce EventDataInner for serializing events - remove all use of go-wire around user interfaces - rpc responses no longer have type information :) +- [types] Do not include the `Accum` field when computing the hash of a validator. This makes the ValidatorSetHash unique for a given validator set, rather than changing with every block (as the Accum changes) FEATURES: diff --git a/types/validator.go b/types/validator.go index 595c52ff1..0c782321e 100644 --- a/types/validator.go +++ b/types/validator.go @@ -12,13 +12,14 @@ import ( ) // Volatile state for each Validator -// TODO: make non-volatile identity -// - Remove Accum - it can be computed, and now valset becomes identifying +// NOTE: The Accum is not included in Validator.Hash(); +// make sure to update that method if changes are made here type Validator struct { Address data.Bytes `json:"address"` PubKey crypto.PubKey `json:"pub_key"` VotingPower int64 `json:"voting_power"` - Accum int64 `json:"accum"` + + Accum int64 `json:"accum"` } func NewValidator(pubKey crypto.PubKey, votingPower int64) *Validator { @@ -69,8 +70,18 @@ func (v *Validator) String() string { v.Accum) } +// Hash computes the unique ID of a validator with a given voting power. +// It exludes the Accum value, which changes with every round. func (v *Validator) Hash() []byte { - return wire.BinaryRipemd160(v) + return wire.BinaryRipemd160(struct { + Address data.Bytes + PubKey crypto.PubKey + VotingPower int64 + }{ + v.Address, + v.PubKey, + v.VotingPower, + }) } //------------------------------------- diff --git a/types/validator_set.go b/types/validator_set.go index 214e073d0..b374df576 100644 --- a/types/validator_set.go +++ b/types/validator_set.go @@ -21,7 +21,6 @@ import ( // NOTE: Not goroutine-safe. // NOTE: All get/set to validators should copy the value for safety. // TODO: consider validator Accum overflow -// TODO: move valset into an iavl tree where key is 'blockbonded|pubkey' type ValidatorSet struct { // NOTE: persisted via reflect, must be exported. Validators []*Validator `json:"validators"` diff --git a/types/vote_set_test.go b/types/vote_set_test.go index 6ef075927..84e13ac17 100644 --- a/types/vote_set_test.go +++ b/types/vote_set_test.go @@ -11,7 +11,6 @@ import ( ) // NOTE: privValidators are in order -// TODO: Move it out? func randVoteSet(height int, round int, type_ byte, numValidators int, votingPower int64) (*VoteSet, *ValidatorSet, []*PrivValidator) { valSet, privValidators := RandValidatorSet(numValidators, votingPower) return NewVoteSet("test_chain_id", height, round, type_, valSet), valSet, privValidators From 883b71ca700c034c968393669a1943e98d53b2a9 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Wed, 17 May 2017 00:27:03 +0200 Subject: [PATCH 304/309] update CHANGELOG --- CHANGELOG.md | 24 ++++++++++++++---------- 1 file changed, 14 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b1cd54e3..3591d13a2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## 0.10.0 (April 26, 2017) +## 0.10.0 (May 17, 2017) BREAKING CHANGES: @@ -15,19 +15,23 @@ BREAKING CHANGES: - New config - Isolate viper to cmd/tendermint/commands - - config structs: Base, P2P, Mempool, Consensus - - Remove config/tendermint and config/tendermint_test. Defaults are handled by viper and DefaultConfig() / TestConfig() functions. Tests do not read config from file -- New logging -- RPC serialization -- lowercase json names for ValidatorSet fields + - Remove config/tendermint and config/tendermint_test. Defaults are handled by viper and `DefaultConfig() / `TestConfig()` functions + - Tests do not read config from file + - New Config structs in `config/`: BaseConfig, P2PConfig, MempoolConfig, ConsensusConfig +- New logger + - Reduced to three levels: Error, Info, Debug + - Per-module log levels + - No global loggers (loggers are passed into constructors, or preferably set with a `SetLogger` method) +- RPC serialization cleanup: + - Lowercase json names for ValidatorSet fields + - No longer uses go-wire, so no more `[TypeByte, XXX]` madness + - Responses have no type information + - Introduce EventDataInner for serializing events +- Remove all use of go-wire (and `[TypeByte, XXX]`) in the `genesis.json` and `priv_validator.json` - Send InitChain in handshake if appBlockHeight == 0 - [types] `[]byte -> data.Bytes` -- Introduce EventDataInner for serializing events -- remove all use of go-wire around user interfaces -- rpc responses no longer have type information :) - [types] Do not include the `Accum` field when computing the hash of a validator. This makes the ValidatorSetHash unique for a given validator set, rather than changing with every block (as the Accum changes) - FEATURES: - Log if a node is validator or not in every consensus round From 6a30a902c91fd97b2d3d0b892657ff7750427ec0 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Wed, 17 May 2017 01:08:41 +0200 Subject: [PATCH 305/309] [types] more []byte->data.Bytes and some %X->%v --- types/block.go | 36 ++++++++++++++++++------------------ types/priv_validator.go | 2 +- types/validator.go | 2 +- 3 files changed, 20 insertions(+), 20 deletions(-) diff --git a/types/block.go b/types/block.go index 725f60bb9..b306d57d0 100644 --- a/types/block.go +++ b/types/block.go @@ -70,7 +70,7 @@ func (b *Block) ValidateBasic(chainID string, lastBlockHeight int, lastBlockID B return errors.New(Fmt("Wrong Block.Header.LastBlockID. Expected %v, got %v", lastBlockID, b.LastBlockID)) } if !bytes.Equal(b.LastCommitHash, b.LastCommit.Hash()) { - return errors.New(Fmt("Wrong Block.Header.LastCommitHash. Expected %X, got %X", b.LastCommitHash, b.LastCommit.Hash())) + return errors.New(Fmt("Wrong Block.Header.LastCommitHash. Expected %v, got %v", b.LastCommitHash, b.LastCommit.Hash())) } if b.Header.Height != 1 { if err := b.LastCommit.ValidateBasic(); err != nil { @@ -78,10 +78,10 @@ func (b *Block) ValidateBasic(chainID string, lastBlockHeight int, lastBlockID B } } if !bytes.Equal(b.DataHash, b.Data.Hash()) { - return errors.New(Fmt("Wrong Block.Header.DataHash. Expected %X, got %X", b.DataHash, b.Data.Hash())) + return errors.New(Fmt("Wrong Block.Header.DataHash. Expected %v, got %v", b.DataHash, b.Data.Hash())) } if !bytes.Equal(b.AppHash, appHash) { - return errors.New(Fmt("Wrong Block.Header.AppHash. Expected %X, got %X", appHash, b.AppHash)) + return errors.New(Fmt("Wrong Block.Header.AppHash. Expected %X, got %v", appHash, b.AppHash)) } // NOTE: the AppHash and ValidatorsHash are validated later. return nil @@ -136,7 +136,7 @@ func (b *Block) StringIndented(indent string) string { %s %v %s %v %s %v -%s}#%X`, +%s}#%v`, indent, b.Header.StringIndented(indent+" "), indent, b.Data.StringIndented(indent+" "), indent, b.LastCommit.StringIndented(indent+" "), @@ -147,7 +147,7 @@ func (b *Block) StringShort() string { if b == nil { return "nil-Block" } else { - return fmt.Sprintf("Block#%X", b.Hash()) + return fmt.Sprintf("Block#%v", b.Hash()) } } @@ -166,7 +166,7 @@ type Header struct { } // NOTE: hash is nil if required fields are missing. -func (h *Header) Hash() []byte { +func (h *Header) Hash() data.Bytes { if len(h.ValidatorsHash) == 0 { return nil } @@ -193,11 +193,11 @@ func (h *Header) StringIndented(indent string) string { %s Time: %v %s NumTxs: %v %s LastBlockID: %v -%s LastCommit: %X -%s Data: %X -%s Validators: %X -%s App: %X -%s}#%X`, +%s LastCommit: %v +%s Data: %v +%s Validators: %v +%s App: %v +%s}#%v`, indent, h.ChainID, indent, h.Height, indent, h.Time, @@ -222,7 +222,7 @@ type Commit struct { // Volatile firstPrecommit *Vote - hash []byte + hash data.Bytes bitArray *BitArray } @@ -322,7 +322,7 @@ func (commit *Commit) ValidateBasic() error { return nil } -func (commit *Commit) Hash() []byte { +func (commit *Commit) Hash() data.Bytes { if commit.hash == nil { bs := make([]interface{}, len(commit.Precommits)) for i, precommit := range commit.Precommits { @@ -344,7 +344,7 @@ func (commit *Commit) StringIndented(indent string) string { return fmt.Sprintf(`Commit{ %s BlockID: %v %s Precommits: %v -%s}#%X`, +%s}#%v`, indent, commit.BlockID, indent, strings.Join(precommitStrings, "\n"+indent+" "), indent, commit.hash) @@ -360,10 +360,10 @@ type Data struct { Txs Txs `json:"txs"` // Volatile - hash []byte + hash data.Bytes } -func (data *Data) Hash() []byte { +func (data *Data) Hash() data.Bytes { if data.hash == nil { data.hash = data.Txs.Hash() // NOTE: leaves of merkle tree are TxIDs } @@ -384,7 +384,7 @@ func (data *Data) StringIndented(indent string) string { } return fmt.Sprintf(`Data{ %s %v -%s}#%X`, +%s}#%v`, indent, strings.Join(txStrings, "\n"+indent+" "), indent, data.hash) } @@ -419,5 +419,5 @@ func (blockID BlockID) WriteSignBytes(w io.Writer, n *int, err *error) { } func (blockID BlockID) String() string { - return fmt.Sprintf(`%X:%v`, blockID.Hash, blockID.PartsHeader) + return fmt.Sprintf(`%v:%v`, blockID.Hash, blockID.PartsHeader) } diff --git a/types/priv_validator.go b/types/priv_validator.go index 5fc081e42..c3d59c9eb 100644 --- a/types/priv_validator.go +++ b/types/priv_validator.go @@ -238,7 +238,7 @@ func (privVal *PrivValidator) signBytesHRS(height, round int, step int8, signByt } func (privVal *PrivValidator) String() string { - return fmt.Sprintf("PrivValidator{%X LH:%v, LR:%v, LS:%v}", privVal.Address, privVal.LastHeight, privVal.LastRound, privVal.LastStep) + return fmt.Sprintf("PrivValidator{%v LH:%v, LR:%v, LS:%v}", privVal.Address, privVal.LastHeight, privVal.LastRound, privVal.LastStep) } //------------------------------------- diff --git a/types/validator.go b/types/validator.go index 0c782321e..24f8974f3 100644 --- a/types/validator.go +++ b/types/validator.go @@ -63,7 +63,7 @@ func (v *Validator) String() string { if v == nil { return "nil-Validator" } - return fmt.Sprintf("Validator{%X %v VP:%v A:%v}", + return fmt.Sprintf("Validator{%v %v VP:%v A:%v}", v.Address, v.PubKey, v.VotingPower, From 30a19fc8993fde824bd1116505f6dab9ebca2105 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Thu, 18 May 2017 11:26:15 +0200 Subject: [PATCH 306/309] [consensus] Info->Debug for is a validator log msg --- consensus/state.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/consensus/state.go b/consensus/state.go index b3bbbb2c4..d4056facf 100644 --- a/consensus/state.go +++ b/consensus/state.go @@ -775,20 +775,20 @@ func (cs *ConsensusState) enterPropose(height int, round int) { // Nothing more to do if we're not a validator if cs.privValidator == nil { - cs.Logger.Info("This node is not a validator") + cs.Logger.Debug("This node is not a validator") return } if !bytes.Equal(cs.Validators.GetProposer().Address, cs.privValidator.GetAddress()) { cs.Logger.Info("enterPropose: Not our turn to propose", "proposer", cs.Validators.GetProposer().Address, "privValidator", cs.privValidator) if cs.Validators.HasAddress(cs.privValidator.GetAddress()) { - cs.Logger.Info("This node is a validator") + cs.Logger.Debug("This node is a validator") } else { - cs.Logger.Info("This node is not a validator") + cs.Logger.Debug("This node is not a validator") } } else { cs.Logger.Info("enterPropose: Our turn to propose", "proposer", cs.Validators.GetProposer().Address, "privValidator", cs.privValidator) - cs.Logger.Info("This node is a validator") + cs.Logger.Debug("This node is a validator") cs.decideProposal(height, round) } } From 772306cac8cc2566b59750cd51df312e3ba5b502 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Thu, 18 May 2017 12:08:00 +0200 Subject: [PATCH 307/309] update changelog and glide --- CHANGELOG.md | 12 ++++++------ glide.lock | 26 +++++++++++++------------- glide.yaml | 8 ++++---- 3 files changed, 23 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3591d13a2..c1fedd6ba 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ # Changelog -## 0.10.0 (May 17, 2017) +## 0.10.0 (May 18, 2017) BREAKING CHANGES: @@ -14,11 +14,11 @@ BREAKING CHANGES: ``` - New config - - Isolate viper to cmd/tendermint/commands + - Isolate viper to `cmd/tendermint/commands` + - New Config structs in `config/`: `BaseConfig`, `P2PConfig`, `MempoolConfig`, `ConsensusConfig` - Remove config/tendermint and config/tendermint_test. Defaults are handled by viper and `DefaultConfig() / `TestConfig()` functions - Tests do not read config from file - - New Config structs in `config/`: BaseConfig, P2PConfig, MempoolConfig, ConsensusConfig -- New logger +- New logger (`github.com/tendermint/tmlibs/log`) - Reduced to three levels: Error, Info, Debug - Per-module log levels - No global loggers (loggers are passed into constructors, or preferably set with a `SetLogger` method) @@ -28,7 +28,7 @@ BREAKING CHANGES: - Responses have no type information - Introduce EventDataInner for serializing events - Remove all use of go-wire (and `[TypeByte, XXX]`) in the `genesis.json` and `priv_validator.json` -- Send InitChain in handshake if appBlockHeight == 0 +- [consensus/abci] Send InitChain message in handshake if `appBlockHeight == 0` - [types] `[]byte -> data.Bytes` - [types] Do not include the `Accum` field when computing the hash of a validator. This makes the ValidatorSetHash unique for a given validator set, rather than changing with every block (as the Accum changes) @@ -47,7 +47,7 @@ IMPROVEMENTS: - Return HTTP status codes with errors for RPC responses - Use `.Wrap()` and `.Unwarp()` instead of eg. `PubKeyS` for `go-crypto` types - Color code different instances of the consensus for tests -- RPC JSON responses use pretty printing (json.MarshalIndent) +- RPC JSON responses use pretty printing (via `json.MarshalIndent`) ## 0.9.2 (April 26, 2017) diff --git a/glide.lock b/glide.lock index 9fd20fd8c..195386500 100644 --- a/glide.lock +++ b/glide.lock @@ -1,8 +1,8 @@ -hash: 9caff08aa026986b239e4aeb9d876bdddfacadc64a660ee8109e77a211e53436 -updated: 2017-05-16T23:51:45.470827916+02:00 +hash: 93f15c9766ea826c29a91f545c42172eafd8c61e39c1d81617114ad1a9c9eaf2 +updated: 2017-05-18T06:13:24.295793122-04:00 imports: - name: github.com/btcsuite/btcd - version: 40f4997b95ac18e20c5ffc54dc3c84036b1f1bf5 + version: 53f55a46349aa8f44b90895047e843666991cf24 subpackages: - btcec - name: github.com/davecgh/go-spew @@ -14,7 +14,7 @@ imports: - name: github.com/fsnotify/fsnotify version: 4da3e2cfbabc9f751898f250b49f2439785783a1 - name: github.com/go-kit/kit - version: d67bb4c202e3b91377d1079b110a6c9ce23ab2f8 + version: 6964666de57c88f7d93da127e900d201b632f561 subpackages: - log - log/level @@ -102,7 +102,7 @@ imports: - leveldb/table - leveldb/util - name: github.com/tendermint/abci - version: 5dabeffb35c027d7087a12149685daa68989168b + version: 864d1f80b36b440bde030a5c18d8ac3aa8c2949d subpackages: - client - example/counter @@ -115,21 +115,21 @@ imports: - edwards25519 - extra25519 - name: github.com/tendermint/go-crypto - version: 438b16f1f84ef002d7408ecd6fc3a3974cbc9559 + version: 7dff40942a64cdeefefa9446b2d104750b349f8a - name: github.com/tendermint/go-wire - version: 97beaedf0f4dbc035309157c92be3b30cc6e5d74 + version: 5f88da3dbc1a72844e6dfaf274ce87f851d488eb subpackages: - data - data/base58 - name: github.com/tendermint/merkleeyes - version: c722818b460381bc5b82e38c73ff6e22a9df624d + version: a0e73e1ac3e18e12a007520a4ea2c9822256e307 subpackages: - app - client - iavl - testutil - name: github.com/tendermint/tmlibs - version: 67f558cff0d3fc08eac951fcc39cf999101e36da + version: 306795ae1d8e4f4a10dcc8bdb32a00455843c9d5 subpackages: - autofile - cli @@ -153,7 +153,7 @@ imports: - ripemd160 - salsa20/salsa - name: golang.org/x/net - version: 34057069f4ab13dc4433c68d368737ebeafcccdc + version: 513929065c19401a1c7b76ecd942f9f86a0c061b subpackages: - context - http2 @@ -163,7 +163,7 @@ imports: - lex/httplex - trace - name: golang.org/x/sys - version: 1e99a4f9d247b28c670884b9a8d6801f39a47b77 + version: e62c3de784db939836898e5c19ffd41bece347da subpackages: - unix - name: golang.org/x/text @@ -174,11 +174,11 @@ imports: - unicode/bidi - unicode/norm - name: google.golang.org/genproto - version: 411e09b969b1170a9f0c467558eb4c4c110d9c77 + version: bb3573be0c484136831138976d444b8754777aff subpackages: - googleapis/rpc/status - name: google.golang.org/grpc - version: 3419b42955675df23457629c75f58eb8dcd56954 + version: 11d93ecdb918872ee841ba3a2dc391aa6d4f57c3 subpackages: - codes - credentials diff --git a/glide.yaml b/glide.yaml index dd4993f59..63acdcbaa 100644 --- a/glide.yaml +++ b/glide.yaml @@ -15,19 +15,19 @@ import: subpackages: - require - package: github.com/tendermint/abci - version: develop + version: v0.5.0 subpackages: - client - example/dummy - types - package: github.com/tendermint/go-crypto - version: develop + version: v0.2.0 - package: github.com/tendermint/go-wire - version: develop + version: v0.6.2 subpackages: - data - package: github.com/tendermint/tmlibs - version: develop + version: v0.2.0 subpackages: - autofile - cli From 790e04ed3e78e43d75b60218925e2d9c4a3e1776 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Thu, 18 May 2017 12:32:34 +0200 Subject: [PATCH 308/309] add link to list of breaking funcs/methods --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index c1fedd6ba..724c31201 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,7 @@ BREAKING CHANGES: - [consensus/abci] Send InitChain message in handshake if `appBlockHeight == 0` - [types] `[]byte -> data.Bytes` - [types] Do not include the `Accum` field when computing the hash of a validator. This makes the ValidatorSetHash unique for a given validator set, rather than changing with every block (as the Accum changes) +- A number of functions and methods ahd their signatures modified to accomodate new config and logger. See https://gist.github.com/ebuchman/640d5fc6c2605f73497992fe107ebe0b for comprehensive list. Note many also had `[]byte` arguments changed to `data.Bytes`, but this is not actually breaking. FEATURES: From d4fa98de68b490f4854f4e08d86d1156418f92fb Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Thu, 18 May 2017 12:36:58 +0200 Subject: [PATCH 309/309] update version for rc1 --- scripts/dist.sh | 12 ++++++------ version/version.go | 8 +------- 2 files changed, 7 insertions(+), 13 deletions(-) diff --git a/scripts/dist.sh b/scripts/dist.sh index 14f0fef12..0f368de97 100755 --- a/scripts/dist.sh +++ b/scripts/dist.sh @@ -19,12 +19,12 @@ DIR="$( cd -P "$( dirname "$SOURCE" )/.." && pwd )" # Change into that dir because we expect that. cd "$DIR" -# Generate the tag. -if [ -z "$NOTAG" ]; then - echo "==> Tagging..." - git commit --allow-empty -a -m "Release v$VERSION" - git tag -a -m "Version $VERSION" "v${VERSION}" master -fi +## Generate the tag. +#if [ -z "$NOTAG" ]; then +# echo "==> Tagging..." +# git commit --allow-empty -a -m "Release v$VERSION" +# git tag -a -m "Version $VERSION" "v${VERSION}" master +#fi # Do a hermetic build inside a Docker container. docker build -t tendermint/tendermint-builder scripts/tendermint-builder/ diff --git a/version/version.go b/version/version.go index 8056ac708..60887d6f9 100644 --- a/version/version.go +++ b/version/version.go @@ -1,24 +1,18 @@ package version -import ( - "fmt" -) - const Maj = "0" const Min = "10" const Fix = "0" var ( // The full version string - Version = "0.10.0" + Version = "0.10.0-rc1" // GitCommit is set with --ldflags "-X main.gitCommit=$(git rev-parse HEAD)" GitCommit string ) func init() { - Version = fmt.Sprintf("%d.%d.%d", Maj, Min, Fix) - if GitCommit != "" { Version += "-" + GitCommit[:8] }