From abc3a2cc3c5ec777fecb5e0eac551ad17bdb1c6e Mon Sep 17 00:00:00 2001 From: Jae Kwon Date: Sun, 25 Oct 2015 18:21:51 -0700 Subject: [PATCH 001/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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 { + return newRPCFunc(f, args, true) } -func NewWSRPCFunc(f interface{}, args []string) *RPCFunc { +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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] add support for unix sockets --- client/http_client.go | 83 +++++++++++++++++++++--------- rpc_test.go | 114 ++++++++++++++++++++++++++++++++++++++++++ server/http_server.go | 9 ++-- types/types.go | 14 ++++++ 4 files changed, 194 insertions(+), 26 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" ) -// JSON rpc takes params as a slice -type ClientJSONRPC struct { - remote string +// 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 NewClientJSONRPC(remote string) *ClientJSONRPC { - return &ClientJSONRPC{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 (c *ClientJSONRPC) Call(method string, params []interface{}, result interface{}) (interface{}, error) { - return CallHTTP_JSONRPC(c.remote, method, params, result) +func socketTransport(remote string) *http.Transport { + if rpctypes.SocketType(remote) == "unix" { + return &http.Transport{ + Dial: unixDial(remote), + } + } else { + return &http.Transport{ + Dial: tcpDial(remote), + } + } } -// URI takes params as a map -type ClientURI struct { +//------------------------------------------------------------------------------------ + +// JSON rpc takes params as a slice +type ClientJSONRPC struct { remote string + client *http.Client } -func NewClientURI(remote string) *ClientURI { - if !strings.HasSuffix(remote, "/") { - remote = remote + "/" +func NewClientJSONRPC(remote string) *ClientJSONRPC { + return &ClientJSONRPC{ + remote: remote, + client: &http.Client{Transport: socketTransport(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 (c *ClientJSONRPC) Call(method string, params []interface{}, result interface{}) (interface{}, error) { + return c.call(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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] No global config --- config.go | 45 ++++++++++++++++++++------------------------- connection.go | 49 +++++++++++++++++++++---------------------------- peer.go | 5 +++-- switch.go | 27 +++++++++++++-------------- 4 files changed, 57 insertions(+), 69 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 - -func init() { - initConfigureable(dialTimeoutKey, 3) - initConfigureable(handshakeTimeoutKey, 20) - initConfigureable(maxNumPeersKey, 50) - initConfigureable(sendRateKey, 512000) // 500KB/s - initConfigureable(recvRateKey, 512000) // 500KB/s - initConfigureable(maxPayloadSizeKey, 1024) - - initConfigureable(authEncKey, 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) - } - }) -} +const ( + // Switch config keys + configKeyDialTimeoutSeconds = "p2p_dial_timeout_seconds" + configKeyHandshakeTimeoutSeconds = "p2p_handshake_timeout_seconds" + configKeyMaxNumPeers = "p2p_max_num_peers" + configKeyAuthEnc = "p2p_authenticated_encryption" + + // MConnection config keys + configKeySendRate = "p2p_send_rate" + configKeyRecvRate = "p2p_recv_rate" +) -// default config map -var defaultConfigValues = make(map[string]interface{}) +func setConfigDefaults(config cfg.Config) { + // Switch default config + config.SetDefault(configKeyDialTimeoutSeconds, 3) + config.SetDefault(configKeyHandshakeTimeoutSeconds, 20) + config.SetDefault(configKeyMaxNumPeers, 50) + config.SetDefault(configKeyAuthEnc, true) -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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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 | 31 +++++++++++++++++++++++++------ 4 files changed, 109 insertions(+), 8 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` +if [[ "$R1" != "$R2" ]]; then + echo "responses are not identical:" + echo "R1: $R1" + echo "R2: $R2" +else + echo "Success" +fi -kill -9 $PID +# 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" - exit 1 +else + echo "Success" fi -echo "Success" + +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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] more tests for AddrBook --- addrbook_test.go | 170 +++++++++++++++++++++-------------------------- 1 file changed, 77 insertions(+), 93 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,143 +22,129 @@ 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()) -func randIPv4Address(t *testing.T) *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, err := NewNetAddressString(fmt.Sprintf("%v:%v", ip, port)) - assert.Nil(t, err, "error generating rand network address") - if addr.Routable() { - return addr - } - } -} + // 100 addresses + randAddrs := randNetAddressPairs(t, 100) -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()) - } + + assert.Equal(t, 100, book.Size()) book.saveToFile(fname) - // Reload the book - book = NewAddrBook(fname, addrBookStrict) + book = NewAddrBook(fname, true) book.loadFromFile(fname) - // Test ... + assert.Equal(t, 100, book.Size()) +} - if book.Size() != 100 { - t.Errorf("Expected 100 addresses, found %v", 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()] - if ka == nil { - t.Fatalf("Expected to find KnownAddress %v but wasn't there.", addr) - } + 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 TestPromoteToOld(t *testing.T) { +func TestAddrBookPromoteToOld(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) + 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) } } - book.saveToFile(fname) - // Reload the book - book = NewAddrBook(fname, addrBookStrict) - book.loadFromFile(fname) + // TODO: do more testing :) - // Test ... + selection := book.GetSelection() + t.Logf("selection: %v", selection) - if book.Size() != 100 { - t.Errorf("Expected 100 addresses, found %v", book.Size()) + if len(selection) > book.Size() { + t.Errorf("selection could not be bigger than the book") } +} - // TODO: do more testing :) +func TestAddrBookHandlesDuplicates(t *testing.T) { + fname := createTempFileName("addrbook_test") - selection := book.GetSelection() - t.Logf("selection: %v", selection) + 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 { + 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, err := NewNetAddressString(fmt.Sprintf("%v:%v", ip, port)) + assert.Nil(t, err, "error generating rand network address") + if addr.Routable() { + return addr + } + } } From 65b1756978fb6fe1c247dd361e3ef56dbd4a5165 Mon Sep 17 00:00:00 2001 From: Anton Kaliaev Date: Mon, 16 Jan 2017 18:00:39 +0400 Subject: [PATCH 080/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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 | 103 ++++++++++++++++---------- test/data.json | 11 ++- test/{test.sh => integration_test.sh} | 31 ++++---- test/main.go | 6 +- types/types.go | 14 ++-- 10 files changed, 147 insertions(+), 112 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 } +// 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 []interface{}, wsCtx WSRPCContext) ([]reflect.Value, error) { +func jsonParamsToArgsWS(rpcFunc *RPCFunc, params map[string]interface{}, wsCtx types.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)) + 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,17 +1,13 @@ -#! /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/... +#!/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 )" -# integration tests -cd test -set -e +# Change into that dir because we expect that. +pushd "$DIR" go build -o server main.go ./server > /dev/null & @@ -19,8 +15,8 @@ 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/190] 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/190] "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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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) + + if "" == arg { + continue + } - v, err, ok := nonJsonToArg(ty, arg) + 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/190] 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/190] 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/190] 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/190] 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) - } - - 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 + values, err := jsonParamsToArgs(rpcFunc, params) + if err != nil { + return nil, err } - - 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] refactor tests --- rpc_test.go | 83 +++++++++++++++++------------------------------------ 1 file changed, 27 insertions(+), 56 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) + if _, err := cl.Call("status", params, &result); err != nil { + return "", err + } + return result.(*ResultStatus).Value, nil } -func testJSONRPC(t *testing.T, cl *client.JSONRPCClient) { +func testWithHTTPClient(t *testing.T, cl client.HTTPClient) { val := "acbd" - 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) } -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 TestURI_UNIX(t *testing.T) { - cl := client.NewURIClient(unixAddr) - testURI(t, cl) -} - -func TestJSONRPC_TCP(t *testing.T) { - cl := client.NewJSONRPCClient(tcpAddr) - testJSONRPC(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 TestJSONRPC_UNIX(t *testing.T) { - cl := client.NewJSONRPCClient(unixAddr) - testJSONRPC(t, cl) -} + cl2 := client.NewJSONRPCClient(tcpAddr) + fmt.Printf("=== testing server on %s using %v client", addr, cl2) + testWithHTTPClient(t, cl2) -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/190] 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/190] WSClient failed to "echo_bytes" Error: ``` Expected nil, but got: encoding/hex: invalid byte: U+0078 'x' ``` --- rpc_test.go | 112 ++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 77 insertions(+), 35 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 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 testWithHTTPClient(t *testing.T, cl client.HTTPClient) { val := "acbd" - got, err := echo(cl, val) + 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 testWithWSClient(t *testing.T, cl *client.WSClient) { - val := "acbd" +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/190] 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/190] 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/190] 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/190] [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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] persistent peers (Refs #13) --- peer.go | 204 +++++++++++++++++++++++++++++++++++++++---------- pex_reactor.go | 4 +- switch.go | 173 +++++++++++++++++++++-------------------- switch_test.go | 131 ++++++++++++++++++++++++++++--- 4 files changed, 377 insertions(+), 135 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)), + + // 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() } - mconn := NewMConnectionWithConfig(conn, chDescs, onReceive, onError, mconnConfig) - p = &Peer{ - outbound: outbound, - mconn: mconn, - NodeInfo: peerNodeInfo, - Key: peerNodeInfo.PubKey.KeyString(), - Data: NewCMap(), + if p.NodeInfo == nil { + panic("Attempt to get peer's PubKey before calling Handshake") } - p.BaseService = *NewBaseService(log, "Peer", p) - return p + 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") + if sw.nodeInfo.PubKey.Equals(peer.PubKey()) { + return errors.New("Ignoring connection from self") } + // Check version, chain id - if err := sw.nodeInfo.CompatibleWith(peerNodeInfo); err != nil { - sconn.Close() - return nil, err + if err := sw.nodeInfo.CompatibleWith(peer.NodeInfo); err != nil { + return err } - 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 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.peers.Remove(peer) - peer.Stop() - sw.removePeerFromReactors(peer, nil) + sw.stopAndRemovePeer(peer, nil) } -func (sw *Switch) addPeerToReactors(peer *Peer) { - for _, reactor := range sw.reactors { - reactor.AddPeer(peer) - } -} - -func (sw *Switch) removePeerFromReactors(peer *Peer, reason interface{}) { +func (sw *Switch) stopAndRemovePeer(peer *Peer, reason interface{}) { + sw.peers.Remove(peer) + peer.Stop() 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] test peer --- config.go | 2 - connection.go | 20 ++++--- fuzz.go | 143 +++++++++++++++++++++++++++++++++---------------- peer.go | 85 ++++++++++++++++++----------- peer_test.go | 120 +++++++++++++++++++++++++++++++++++++++++ switch.go | 45 +++++++++++++--- switch_test.go | 71 ++++-------------------- 7 files changed, 331 insertions(+), 155 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 { +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(time.Second * 10), // so we have time to do peer handshakes and get set up - params: config, + 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()) -} - -func (fc *FuzzedConnection) Active() bool { - return fc.params.GetBool(configFuzzActive) + maxDelayMillis := int(fc.maxDelay.Nanoseconds() / 1000) + return time.Millisecond * time.Duration(rand.Int()%maxDelayMillis) } -func (fc *FuzzedConnection) Mode() string { - return fc.params.GetString(configFuzzMode) +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) ProbDropRW() float64 { - return fc.params.GetFloat64(configFuzzProbDropRW) +func (fc *FuzzedConnection) SetProbDropRW(prob float64) { + fc.probDropRW = prob } -func (fc *FuzzedConnection) ProbDropConn() float64 { - return fc.params.GetFloat64(configFuzzProbDropConn) +func (fc *FuzzedConnection) SetProbDropConn(prob float64) { + fc.probDropConn = prob } -func (fc *FuzzedConnection) ProbSleep() float64 { - return fc.params.GetFloat64(configFuzzProbSleep) +func (fc *FuzzedConnection) SetProbSleep(prob float64) { + fc.probSleep = prob } -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/190] 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/190] 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/190] 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/190] [fuzz] only one way to set config variables --- fuzz.go | 157 +++++++++++++++++++++++++------------------------------- peer.go | 2 +- 2 files changed, 71 insertions(+), 88 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,6 +14,19 @@ const ( FuzzModeDelay ) +// 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 + start <-chan time.Time + active bool + + config *FuzzConnConfig +} + +// FuzzConnConfig is a FuzzedConnection configuration. type FuzzConnConfig struct { Mode int MaxDelay time.Duration @@ -23,7 +35,8 @@ type FuzzConnConfig struct { ProbSleep float64 } -func defaultFuzzConnConfig() *FuzzConnConfig { +// DefaultFuzzConnConfig returns the default config. +func DefaultFuzzConnConfig() *FuzzConnConfig { return &FuzzConnConfig{ Mode: FuzzModeDrop, MaxDelay: 3 * time.Second, @@ -33,86 +46,85 @@ func defaultFuzzConnConfig() *FuzzConnConfig { } } +// FuzzConn creates a new FuzzedConnection. Fuzzing starts immediately. func FuzzConn(conn net.Conn) net.Conn { - return FuzzConnFromConfig(conn, defaultFuzzConnConfig()) + return FuzzConnFromConfig(conn, DefaultFuzzConnConfig()) } +// 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, - mode: config.Mode, - maxDelay: config.MaxDelay, - probDropRW: config.ProbDropRW, - probDropConn: config.ProbDropConn, - probSleep: config.ProbSleep, + conn: conn, + start: make(<-chan time.Time), + active: true, + config: config, } } +// 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()) + return FuzzConnAfterFromConfig(conn, d, DefaultFuzzConnConfig()) } +// 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, - mode: config.Mode, - maxDelay: config.MaxDelay, - probDropRW: config.ProbDropRW, - probDropConn: config.ProbDropConn, - probSleep: config.ProbSleep, + conn: conn, + start: time.After(d), + active: false, + config: config, } } -// 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 - start <-chan time.Time - active bool - - mode int - maxDelay time.Duration - probDropRW float64 - probDropConn float64 - probSleep float64 +// Config returns the connection's config. +func (fc *FuzzedConnection) Config() *FuzzConnConfig { + return fc.config } -func (fc *FuzzedConnection) randomDuration() time.Duration { - maxDelayMillis := int(fc.maxDelay.Nanoseconds() / 1000) - return time.Millisecond * time.Duration(rand.Int()%maxDelayMillis) +// 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) } -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)) +// 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) } -func (fc *FuzzedConnection) SetProbDropRW(prob float64) { - fc.probDropRW = prob -} +// 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) } -func (fc *FuzzedConnection) SetProbDropConn(prob float64) { - fc.probDropConn = prob +// SetReadDeadline implements net.Conn. +func (fc *FuzzedConnection) SetReadDeadline(t time.Time) error { + return fc.conn.SetReadDeadline(t) } -func (fc *FuzzedConnection) SetProbSleep(prob float64) { - fc.probSleep = prob +// SetWriteDeadline implements net.Conn. +func (fc *FuzzedConnection) SetWriteDeadline(t time.Time) error { + return fc.conn.SetWriteDeadline(t) } -func (fc *FuzzedConnection) SetMaxDelay(d time.Duration) { - fc.maxDelay = d +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/190] 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/190] 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/190] 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/190] 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,30 +12,56 @@ 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 createPeerAndPerformHandshake(addr *NetAddress) (*Peer, error) { +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() + defer p.Stop() + + assert.True(p.IsRunning()) +} + +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/190] 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/190] [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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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/190] 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 0017fb7ffe947ddbcd9eff0ffc5089600296b119 Mon Sep 17 00:00:00 2001 From: Ethan Buchman Date: Fri, 21 Apr 2017 17:38:40 -0400 Subject: [PATCH 170/190] 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 171/190] 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 172/190] 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 173/190] 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 174/190] 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 175/190] 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 176/190] 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 177/190] 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 178/190] 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 179/190] 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 180/190] 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 181/190] 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 182/190] 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 183/190] 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 184/190] 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 185/190] 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 186/190] glide update --- glide.lock | 56 +++++++++++++------------------------- glide.yaml | 80 +++++++++++++++++++++++++++--------------------------- 2 files changed, 59 insertions(+), 77 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/merkleeyes +- package: github.com/tendermint/tmlibs 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 + - 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/stretchr/testify - version: ^1.1.4 +- package: github.com/tendermint/merkleeyes + version: develop subpackages: - - assert - - require + - app + - 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 187/190] 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 188/190] 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 189/190] 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 190/190] 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 }