├── .gitignore ├── .travis.yml ├── Cargo.toml ├── LICENSE ├── README.md └── src ├── accumulator.rs ├── lib.rs └── tests.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock 4 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | rust: 3 | - stable 4 | - beta -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rhododendron" 3 | version = "0.7.0" 4 | authors = ["Parity Technologies "] 5 | description = "Asynchronously safe BFT protocol, futures-based implementation" 6 | license = "GPL-3.0" 7 | repository = "https://github.com/paritytech/rhododendron" 8 | edition = "2018" 9 | 10 | [dependencies] 11 | futures = "0.1.17" 12 | error-chain = "0.12" 13 | log = "0.4" 14 | parity-scale-codec = { version = "1.0.3", optional = true, features = ["derive"] } 15 | 16 | [dev-dependencies] 17 | tokio-core = "0.1.12" 18 | tokio-timer = "0.1.2" 19 | parity-scale-codec = { version = "1.0.3", features = ["derive"] } 20 | 21 | [features] 22 | codec = ['parity-scale-codec'] 23 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Rhododendron 2 | 3 | Futures-based BFT in Rust. Mostly works, but not ready for production. 4 | 5 | Most of the work is done with the `agree` function: 6 | ```rust 7 | pub fn agree(context: C, nodes: usize, max_faulty: usize, input: I, output: O) 8 | -> Agreement 9 | { 10 | // ... 11 | } 12 | ``` 13 | 14 | There are three parts to invoking `agree`: 15 | - A `Context`, encapsulating value type to be agreed upon, as well as generation, evaluation, and signatures on values. 16 | - An input stream of messages from other nodes. 17 | - An output sink of messages which will reach all other honest nodes. 18 | 19 | This yields an `Agreement` which can be run on an event loop to completion. -------------------------------------------------------------------------------- /src/accumulator.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 Parity Technologies (UK) Ltd. 2 | // This file is part of Rhododendron. 3 | 4 | // Rhododendron is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // Rhododendron is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | 14 | // You should have received a copy of the GNU General Public License 15 | // along with Rhododendron. If not, see . 16 | 17 | //! Vote accumulator for each round of BFT consensus. 18 | 19 | use std::collections::{HashMap, HashSet}; 20 | use std::collections::hash_map::Entry; 21 | use std::hash::Hash; 22 | 23 | use log::{debug, trace}; 24 | #[cfg(any(test, feature="codec"))] 25 | use parity_scale_codec::{Encode, Decode}; 26 | 27 | use crate::{Vote, LocalizedMessage, LocalizedProposal}; 28 | 29 | /// Justification for some state at a given round. 30 | #[derive(Debug, Clone, PartialEq, Eq)] 31 | #[cfg_attr(any(test, feature="codec"), derive(Encode, Decode))] 32 | pub struct UncheckedJustification { 33 | /// The round. 34 | pub round_number: u32, 35 | /// The digest prepared for. 36 | pub digest: D, 37 | /// Signatures for the prepare messages. 38 | pub signatures: Vec, 39 | } 40 | 41 | impl UncheckedJustification { 42 | /// Fails if there are duplicate signatures or invalid. 43 | /// 44 | /// Provide a closure for checking whether the signature is valid on a 45 | /// digest. 46 | /// 47 | /// The closure should returns a checked justification iff the round number, digest, and signature 48 | /// represent a valid message and the signer was authorized to issue 49 | /// it. 50 | /// 51 | /// The `check_message` closure may vary based on context. 52 | pub fn check(self, threshold: usize, mut check_message: F) 53 | -> Result, Self> 54 | where 55 | F: FnMut(u32, &D, &S) -> Option, 56 | V: Hash + Eq, 57 | { 58 | let checks_out = { 59 | let mut checks_out = || { 60 | let mut voted = HashSet::new(); 61 | 62 | for signature in &self.signatures { 63 | match check_message(self.round_number, &self.digest, signature) { 64 | None => return false, 65 | Some(v) => { 66 | if !voted.insert(v) { 67 | return false; 68 | } 69 | } 70 | } 71 | } 72 | 73 | voted.len() >= threshold 74 | }; 75 | 76 | checks_out() 77 | }; 78 | 79 | if checks_out { 80 | Ok(Justification(self)) 81 | } else { 82 | Err(self) 83 | } 84 | } 85 | } 86 | 87 | /// A checked justification. 88 | #[derive(Debug, Clone, PartialEq, Eq)] 89 | #[cfg_attr(any(test, feature="codec"), derive(Encode, Decode))] 90 | pub struct Justification(UncheckedJustification); 91 | 92 | impl Justification { 93 | /// Convert this justification back to unchecked. 94 | pub fn uncheck(self) -> UncheckedJustification { 95 | self.0 96 | } 97 | } 98 | 99 | impl ::std::ops::Deref for Justification { 100 | type Target = UncheckedJustification; 101 | 102 | fn deref(&self) -> &Self::Target { 103 | &self.0 104 | } 105 | } 106 | 107 | /// Type alias to represent a justification specifically for a prepare. 108 | pub type PrepareJustification = Justification; 109 | 110 | /// The round's state, based on imported messages. 111 | #[derive(PartialEq, Eq, Debug)] 112 | #[cfg_attr(any(test, feature="codec"), derive(Encode, Decode))] 113 | pub enum State { 114 | /// No proposal yet. 115 | Begin, 116 | /// Proposal received. 117 | Proposed(Candidate), 118 | /// Seen n - f prepares for this digest. 119 | Prepared(PrepareJustification), 120 | /// Seen n - f commits for a digest. 121 | Committed(Justification), 122 | /// Seen n - f round-advancement messages. 123 | Advanced(Option>), 124 | } 125 | 126 | #[derive(Debug, Default)] 127 | #[cfg_attr(any(test, feature="codec"), derive(Encode, Decode))] 128 | struct VoteCounts { 129 | prepared: u64, 130 | committed: u64, 131 | } 132 | 133 | #[derive(Debug)] 134 | #[cfg_attr(any(test, feature="codec"), derive(Encode, Decode))] 135 | struct Proposal { 136 | proposal: Candidate, 137 | digest: Digest, 138 | digest_signature: Signature, 139 | } 140 | 141 | /// Misbehavior which can occur. 142 | #[derive(Debug, Clone)] 143 | #[cfg_attr(any(test, feature="codec"), derive(Encode, Decode))] 144 | pub enum Misbehavior { 145 | /// Proposed out-of-turn. 146 | ProposeOutOfTurn(u32, Digest, Signature), 147 | /// Issued two conflicting proposals. 148 | DoublePropose(u32, (Digest, Signature), (Digest, Signature)), 149 | /// Issued two conflicting prepare messages. 150 | DoublePrepare(u32, (Digest, Signature), (Digest, Signature)), 151 | /// Issued two conflicting commit messages. 152 | DoubleCommit(u32, (Digest, Signature), (Digest, Signature)), 153 | } 154 | 155 | /// Accumulates messages for a given round of BFT consensus. 156 | /// 157 | /// This isn't tied to the "view" of a single authority. It 158 | /// keeps accurate track of the state of the BFT consensus based 159 | /// on all messages imported. 160 | #[derive(Debug)] 161 | pub struct Accumulator 162 | where 163 | Candidate: Eq + Clone, 164 | Digest: Hash + Eq + Clone, 165 | AuthorityId: Hash + Eq + Clone, 166 | Signature: Eq + Clone, 167 | { 168 | /// The round this accumulator is currently on 169 | pub round_number: u32, 170 | 171 | /// Threshold of prepare messages required to make progress 172 | pub threshold: usize, 173 | 174 | /// Current proposer/authority for this round 175 | pub round_proposer: AuthorityId, 176 | 177 | proposal: Option>, 178 | prepares: HashMap, 179 | commits: HashMap, 180 | vote_counts: HashMap, 181 | advance_round: HashSet, 182 | state: State, 183 | } 184 | 185 | impl Accumulator 186 | where 187 | Candidate: Eq + Clone, 188 | Digest: Hash + Eq + Clone, 189 | AuthorityId: Hash + Eq + Clone, 190 | Signature: Eq + Clone, 191 | { 192 | /// Create a new state accumulator. 193 | pub fn new(round_number: u32, threshold: usize, round_proposer: AuthorityId) -> Self { 194 | Accumulator { 195 | round_number, 196 | threshold, 197 | round_proposer, 198 | proposal: None, 199 | prepares: HashMap::new(), 200 | commits: HashMap::new(), 201 | vote_counts: HashMap::new(), 202 | advance_round: HashSet::new(), 203 | state: State::Begin, 204 | } 205 | } 206 | 207 | /// How advance votes we have seen. 208 | pub fn advance_votes(&self) -> usize { 209 | self.advance_round.len() 210 | } 211 | 212 | /// Get the round number. 213 | pub fn round_number(&self) -> u32 { 214 | self.round_number.clone() 215 | } 216 | 217 | /// Get the round proposer. 218 | pub fn round_proposer(&self) -> AuthorityId { 219 | self.round_proposer.clone() 220 | } 221 | 222 | pub fn proposal(&self) -> Option<&Candidate> { 223 | self.proposal.as_ref().map(|p| &p.proposal) 224 | } 225 | 226 | /// Returns a HashSet of AuthorityIds we've seen participating at any step in this round 227 | pub fn participants(&self) -> HashSet<&AuthorityId> { 228 | let mut participants = self.prepares.keys() 229 | .chain(self.commits.keys()) 230 | .chain(self.advance_round.iter()) 231 | .collect::>(); 232 | 233 | if self.proposal.is_some() { 234 | // we only accepted the proposals, if they were made by the proposer 235 | participants.insert(&self.round_proposer); 236 | } 237 | 238 | participants 239 | } 240 | 241 | /// Returns a HashSet of AuthorityIds we've seen voting at any step in this round. 242 | /// Does not include those who we've only seen broadcast `AdvanceRound`. 243 | pub fn voters(&self) -> HashSet<&AuthorityId> { 244 | let mut participants = self.prepares.keys() 245 | .chain(self.commits.keys()) 246 | .collect::>(); 247 | 248 | if self.proposal.is_some() { 249 | // we only accepted the proposals, if they were made by the proposer 250 | participants.insert(&self.round_proposer); 251 | } 252 | 253 | participants 254 | } 255 | 256 | /// Inspect the current consensus state. 257 | pub fn state(&self) -> &State { 258 | &self.state 259 | } 260 | 261 | /// Import a message. Importing duplicates is fine, but the signature 262 | /// and authorization should have already been checked. 263 | pub fn import_message( 264 | &mut self, 265 | message: LocalizedMessage, 266 | ) -> Result<(), Misbehavior> { 267 | // message from different round. 268 | if message.round_number() != self.round_number { 269 | return Ok(()); 270 | } 271 | 272 | match message { 273 | LocalizedMessage::Propose(proposal) => self.import_proposal(proposal), 274 | LocalizedMessage::Vote(vote) => { 275 | let (sender, signature) = (vote.sender, vote.signature); 276 | match vote.vote { 277 | Vote::Prepare(_, d) => self.import_prepare(d, sender, signature), 278 | Vote::Commit(_, d) => self.import_commit(d, sender, signature), 279 | Vote::AdvanceRound(_) => self.import_advance_round(sender), 280 | } 281 | } 282 | } 283 | } 284 | 285 | fn import_proposal( 286 | &mut self, 287 | proposal: LocalizedProposal, 288 | ) -> Result<(), Misbehavior> { 289 | let sender = proposal.sender; 290 | 291 | if sender != self.round_proposer { 292 | return Err(Misbehavior::ProposeOutOfTurn( 293 | self.round_number, 294 | proposal.digest, 295 | proposal.digest_signature) 296 | ); 297 | } 298 | 299 | match self.proposal { 300 | Some(ref p) if &p.digest != &proposal.digest => { 301 | return Err(Misbehavior::DoublePropose( 302 | self.round_number, 303 | { 304 | let old = self.proposal.as_ref().expect("just checked to be Some; qed"); 305 | (old.digest.clone(), old.digest_signature.clone()) 306 | }, 307 | (proposal.digest.clone(), proposal.digest_signature.clone()) 308 | )) 309 | } 310 | _ => {}, 311 | } 312 | 313 | debug!(target: "bft", "Importing proposal for round {}", self.round_number); 314 | 315 | self.proposal = Some(Proposal { 316 | proposal: proposal.proposal.clone(), 317 | digest: proposal.digest, 318 | digest_signature: proposal.digest_signature, 319 | }); 320 | 321 | if let State::Begin = self.state { 322 | self.state = State::Proposed(proposal.proposal); 323 | } 324 | 325 | Ok(()) 326 | } 327 | 328 | fn import_prepare( 329 | &mut self, 330 | digest: Digest, 331 | sender: AuthorityId, 332 | signature: Signature, 333 | ) -> Result<(), Misbehavior> { 334 | // ignore any subsequent prepares by the same sender. 335 | let threshold_prepared = match self.prepares.entry(sender.clone()) { 336 | Entry::Vacant(vacant) => { 337 | vacant.insert((digest.clone(), signature)); 338 | let count = self.vote_counts.entry(digest.clone()).or_insert_with(Default::default); 339 | count.prepared += 1; 340 | 341 | if count.prepared >= self.threshold as u64 { 342 | Some(digest) 343 | } else { 344 | None 345 | } 346 | } 347 | Entry::Occupied(occupied) => { 348 | // if digest is different, that's misbehavior. 349 | if occupied.get().0 != digest { 350 | return Err(Misbehavior::DoublePrepare( 351 | self.round_number, 352 | occupied.get().clone(), 353 | (digest, signature) 354 | )); 355 | } 356 | 357 | None 358 | } 359 | }; 360 | 361 | // only allow transition to prepare from begin or proposed state. 362 | let valid_transition = match self.state { 363 | State::Begin | State::Proposed(_) => true, 364 | _ => false, 365 | }; 366 | 367 | if let (true, Some(threshold_prepared)) = (valid_transition, threshold_prepared) { 368 | let signatures = self.prepares 369 | .values() 370 | .filter(|&&(ref d, _)| d == &threshold_prepared) 371 | .map(|&(_, ref s)| s.clone()) 372 | .collect(); 373 | 374 | trace!(target: "bft", "observed threshold-prepare for round {}", self.round_number); 375 | self.state = State::Prepared(Justification(UncheckedJustification { 376 | round_number: self.round_number, 377 | digest: threshold_prepared, 378 | signatures: signatures, 379 | })); 380 | } 381 | 382 | Ok(()) 383 | } 384 | 385 | fn import_commit( 386 | &mut self, 387 | digest: Digest, 388 | sender: AuthorityId, 389 | signature: Signature, 390 | ) -> Result<(), Misbehavior> { 391 | // ignore any subsequent commits by the same sender. 392 | let threshold_committed = match self.commits.entry(sender.clone()) { 393 | Entry::Vacant(vacant) => { 394 | vacant.insert((digest.clone(), signature)); 395 | let count = self.vote_counts.entry(digest.clone()).or_insert_with(Default::default); 396 | count.committed += 1; 397 | 398 | if count.committed >= self.threshold as u64 { 399 | Some(digest) 400 | } else { 401 | None 402 | } 403 | } 404 | Entry::Occupied(occupied) => { 405 | // if digest is different, that's misbehavior. 406 | if occupied.get().0 != digest { 407 | return Err(Misbehavior::DoubleCommit( 408 | self.round_number, 409 | occupied.get().clone(), 410 | (digest, signature) 411 | )); 412 | } 413 | 414 | None 415 | } 416 | }; 417 | 418 | // transition to concluded state always valid. 419 | // only weird case is if the prior state was "advanced", 420 | // but technically it's the same behavior as if the order of receiving 421 | // the last "advance round" and "commit" messages were reversed. 422 | if let Some(threshold_committed) = threshold_committed { 423 | let signatures = self.commits 424 | .values() 425 | .filter(|&&(ref d, _)| d == &threshold_committed) 426 | .map(|&(_, ref s)| s.clone()) 427 | .collect(); 428 | 429 | trace!(target: "bft", "observed threshold-commit for round {}", self.round_number); 430 | self.state = State::Committed(Justification(UncheckedJustification { 431 | round_number: self.round_number, 432 | digest: threshold_committed, 433 | signatures: signatures, 434 | })); 435 | } 436 | 437 | Ok(()) 438 | } 439 | 440 | fn import_advance_round( 441 | &mut self, 442 | sender: AuthorityId, 443 | ) -> Result<(), Misbehavior> { 444 | self.advance_round.insert(sender); 445 | 446 | if self.advance_round.len() < self.threshold { return Ok(()) } 447 | trace!(target: "bft", "Witnessed threshold advance-round messages for round {}", self.round_number); 448 | 449 | // allow transition to new round only if we haven't produced a justification 450 | // yet. 451 | self.state = match ::std::mem::replace(&mut self.state, State::Begin) { 452 | State::Committed(j) => State::Committed(j), 453 | State::Prepared(j) => State::Advanced(Some(j)), 454 | State::Advanced(j) => State::Advanced(j), 455 | State::Begin | State::Proposed(_) => State::Advanced(None), 456 | }; 457 | 458 | Ok(()) 459 | } 460 | } 461 | 462 | #[cfg(test)] 463 | mod tests { 464 | use super::*; 465 | use crate::{LocalizedMessage, LocalizedProposal, LocalizedVote}; 466 | 467 | #[derive(Clone, PartialEq, Eq, Debug, Encode, Decode)] 468 | pub struct Candidate(u64); 469 | 470 | #[derive(Hash, PartialEq, Eq, Clone, Debug, Encode, Decode)] 471 | pub struct Digest(u64); 472 | 473 | #[derive(Hash, PartialEq, Eq, Debug, Encode, Decode, Clone)] 474 | pub struct AuthorityId(u64); 475 | 476 | #[derive(PartialEq, Eq, Clone, Debug, Encode, Decode)] 477 | pub struct Signature(u64, u64); 478 | 479 | #[test] 480 | fn justification_checks_out() { 481 | let mut justification = UncheckedJustification { 482 | round_number: 2, 483 | digest: Digest(600), 484 | signatures: (0..10).map(|i| Signature(600, i)).collect(), 485 | }; 486 | 487 | let check_message = |r, d: &Digest, s: &Signature| { 488 | if r == 2 && d.0 == 600 && s.0 == 600 { 489 | Some(AuthorityId(s.1)) 490 | } else { 491 | None 492 | } 493 | }; 494 | 495 | assert!(justification.clone().check(7, &check_message).is_ok()); 496 | assert!(justification.clone().check(11, &check_message).is_err()); 497 | 498 | { 499 | // one bad signature is enough to spoil it. 500 | justification.signatures.push(Signature(1001, 255)); 501 | assert!(justification.clone().check(7, &check_message).is_err()); 502 | 503 | justification.signatures.pop(); 504 | } 505 | // duplicates not allowed. 506 | justification.signatures.extend((0..10).map(|i| Signature(600, i))); 507 | assert!(justification.clone().check(11, &check_message).is_err()); 508 | } 509 | 510 | #[test] 511 | fn accepts_proposal_from_proposer_only() { 512 | let mut accumulator = Accumulator::<_, Digest, _, _>::new(1, 7, AuthorityId(8)); 513 | assert_eq!(accumulator.state(), &State::Begin); 514 | 515 | let res = accumulator.import_message(LocalizedMessage::Propose(LocalizedProposal { 516 | sender: AuthorityId(5), 517 | full_signature: Signature(999, 5), 518 | digest_signature: Signature(999, 5), 519 | proposal: Candidate(999), 520 | digest: Digest(999), 521 | round_number: 1, 522 | })); 523 | 524 | assert!(res.is_err()); 525 | 526 | assert_eq!(accumulator.state(), &State::Begin); 527 | 528 | accumulator.import_message(LocalizedMessage::Propose(LocalizedProposal { 529 | sender: AuthorityId(8), 530 | full_signature: Signature(999, 8), 531 | digest_signature: Signature(999, 8), 532 | proposal: Candidate(999), 533 | digest: Digest(999), 534 | round_number: 1, 535 | })).unwrap(); 536 | 537 | assert_eq!(accumulator.state(), &State::Proposed(Candidate(999))); 538 | } 539 | 540 | #[test] 541 | fn reaches_prepare_phase() { 542 | let mut accumulator = Accumulator::new(1, 7, AuthorityId(8)); 543 | assert_eq!(accumulator.state(), &State::Begin); 544 | 545 | accumulator.import_message(LocalizedMessage::Propose(LocalizedProposal { 546 | sender: AuthorityId(8), 547 | full_signature: Signature(999, 8), 548 | digest_signature: Signature(999, 8), 549 | round_number: 1, 550 | proposal: Candidate(999), 551 | digest: Digest(999), 552 | })).unwrap(); 553 | 554 | assert_eq!(accumulator.state(), &State::Proposed(Candidate(999))); 555 | 556 | for i in 0..6 { 557 | accumulator.import_message(LocalizedVote { 558 | sender: AuthorityId(i), 559 | signature: Signature(999, i), 560 | vote: Vote::Prepare(1, Digest(999)), 561 | }.into()).unwrap(); 562 | 563 | assert_eq!(accumulator.state(), &State::Proposed(Candidate(999))); 564 | } 565 | 566 | accumulator.import_message(LocalizedVote { 567 | sender: AuthorityId(7), 568 | signature: Signature(999, 7), 569 | vote: Vote::Prepare(1, Digest(999)), 570 | }.into()).unwrap(); 571 | 572 | match accumulator.state() { 573 | &State::Prepared(ref j) => assert_eq!(j.digest, Digest(999)), 574 | s => panic!("wrong state: {:?}", s), 575 | } 576 | } 577 | 578 | #[test] 579 | fn prepare_to_commit() { 580 | let mut accumulator = Accumulator::new(1, 7, AuthorityId(8)); 581 | assert_eq!(accumulator.state(), &State::Begin); 582 | 583 | accumulator.import_message(LocalizedMessage::Propose(LocalizedProposal { 584 | sender: AuthorityId(8), 585 | full_signature: Signature(999, 8), 586 | digest_signature: Signature(999, 8), 587 | round_number: 1, 588 | proposal: Candidate(999), 589 | digest: Digest(999), 590 | })).unwrap(); 591 | 592 | assert_eq!(accumulator.state(), &State::Proposed(Candidate(999))); 593 | 594 | for i in 0..6 { 595 | accumulator.import_message(LocalizedVote { 596 | sender: AuthorityId(i), 597 | signature: Signature(999, i), 598 | vote: Vote::Prepare(1, Digest(999)), 599 | }.into()).unwrap(); 600 | 601 | assert_eq!(accumulator.state(), &State::Proposed(Candidate(999))); 602 | } 603 | 604 | accumulator.import_message(LocalizedVote { 605 | sender: AuthorityId(7), 606 | signature: Signature(999, 7), 607 | vote: Vote::Prepare(1, Digest(999)), 608 | }.into()).unwrap(); 609 | 610 | match accumulator.state() { 611 | &State::Prepared(ref j) => assert_eq!(j.digest, Digest(999)), 612 | s => panic!("wrong state: {:?}", s), 613 | } 614 | 615 | for i in 0..6 { 616 | accumulator.import_message(LocalizedVote { 617 | sender: AuthorityId(i), 618 | signature: Signature(999, i), 619 | vote: Vote::Commit(1, Digest(999)), 620 | }.into()).unwrap(); 621 | 622 | match accumulator.state() { 623 | &State::Prepared(_) => {}, 624 | s => panic!("wrong state: {:?}", s), 625 | } 626 | } 627 | 628 | accumulator.import_message(LocalizedVote { 629 | sender: AuthorityId(7), 630 | signature: Signature(999, 7), 631 | vote: Vote::Commit(1, Digest(999)), 632 | }.into()).unwrap(); 633 | 634 | match accumulator.state() { 635 | &State::Committed(ref j) => assert_eq!(j.digest, Digest(999)), 636 | s => panic!("wrong state: {:?}", s), 637 | } 638 | } 639 | 640 | #[test] 641 | fn prepare_to_advance() { 642 | let mut accumulator = Accumulator::new(1, 7, AuthorityId(8)); 643 | assert_eq!(accumulator.state(), &State::Begin); 644 | 645 | accumulator.import_message(LocalizedMessage::Propose(LocalizedProposal { 646 | sender: AuthorityId(8), 647 | full_signature: Signature(999, 8), 648 | digest_signature: Signature(999, 8), 649 | round_number: 1, 650 | proposal: Candidate(999), 651 | digest: Digest(999), 652 | })).unwrap(); 653 | 654 | assert_eq!(accumulator.state(), &State::Proposed(Candidate(999))); 655 | 656 | for i in 0..7 { 657 | accumulator.import_message(LocalizedVote { 658 | sender: AuthorityId(i), 659 | signature: Signature(999, i), 660 | vote: Vote::Prepare(1, Digest(999)), 661 | }.into()).unwrap(); 662 | } 663 | 664 | match accumulator.state() { 665 | &State::Prepared(ref j) => assert_eq!(j.digest, Digest(999)), 666 | s => panic!("wrong state: {:?}", s), 667 | } 668 | 669 | for i in 0..6 { 670 | accumulator.import_message(LocalizedVote { 671 | sender: AuthorityId(i), 672 | signature: Signature(999, i), 673 | vote: Vote::AdvanceRound(1), 674 | }.into()).unwrap(); 675 | 676 | match accumulator.state() { 677 | &State::Prepared(_) => {}, 678 | s => panic!("wrong state: {:?}", s), 679 | } 680 | } 681 | 682 | accumulator.import_message(LocalizedVote { 683 | sender: AuthorityId(7), 684 | signature: Signature(999, 7), 685 | vote: Vote::AdvanceRound(1), 686 | }.into()).unwrap(); 687 | 688 | match accumulator.state() { 689 | &State::Advanced(Some(_)) => {}, 690 | s => panic!("wrong state: {:?}", s), 691 | } 692 | } 693 | 694 | #[test] 695 | fn conclude_different_than_proposed() { 696 | let mut accumulator = Accumulator::::new(1, 7, AuthorityId(8)); 697 | assert_eq!(accumulator.state(), &State::Begin); 698 | 699 | for i in 0..7 { 700 | accumulator.import_message(LocalizedVote { 701 | sender: AuthorityId(i), 702 | signature: Signature(999, i), 703 | vote: Vote::Prepare(1, Digest(999)), 704 | }.into()).unwrap(); 705 | } 706 | 707 | match accumulator.state() { 708 | &State::Prepared(ref j) => assert_eq!(j.digest, Digest(999)), 709 | s => panic!("wrong state: {:?}", s), 710 | } 711 | 712 | for i in 0..7 { 713 | accumulator.import_message(LocalizedVote { 714 | sender: AuthorityId(i), 715 | signature: Signature(999, i), 716 | vote: Vote::Commit(1, Digest(999)), 717 | }.into()).unwrap(); 718 | } 719 | 720 | match accumulator.state() { 721 | &State::Committed(ref j) => assert_eq!(j.digest, Digest(999)), 722 | s => panic!("wrong state: {:?}", s), 723 | } 724 | } 725 | 726 | #[test] 727 | fn propose_after_prepared_does_not_clobber_state() { 728 | let mut accumulator = Accumulator::::new(1, 7, AuthorityId(8)); 729 | assert_eq!(accumulator.state(), &State::Begin); 730 | 731 | for i in 0..7 { 732 | accumulator.import_message(LocalizedVote { 733 | sender: AuthorityId(i), 734 | signature: Signature(999, i), 735 | vote: Vote::Prepare(1, Digest(999)), 736 | }.into()).unwrap(); 737 | } 738 | 739 | match accumulator.state() { 740 | &State::Prepared(ref j) => assert_eq!(j.digest, Digest(999)), 741 | s => panic!("wrong state: {:?}", s), 742 | } 743 | 744 | accumulator.import_message(LocalizedMessage::Propose(LocalizedProposal { 745 | sender: AuthorityId(8), 746 | full_signature: Signature(999, 8), 747 | digest_signature: Signature(999, 8), 748 | round_number: 1, 749 | proposal: Candidate(999), 750 | digest: Digest(999), 751 | })).unwrap(); 752 | 753 | match accumulator.state() { 754 | &State::Prepared(ref j) => assert_eq!(j.digest, Digest(999)), 755 | s => panic!("wrong state: {:?}", s), 756 | } 757 | } 758 | 759 | #[test] 760 | fn propose_after_committed_does_not_clobber_state() { 761 | let mut accumulator = Accumulator::::new(1, 7, AuthorityId(8)); 762 | assert_eq!(accumulator.state(), &State::Begin); 763 | 764 | for i in 0..7 { 765 | accumulator.import_message(LocalizedVote { 766 | sender: AuthorityId(i), 767 | signature: Signature(999, i), 768 | vote: Vote::Commit(1, Digest(999)), 769 | }.into()).unwrap(); 770 | } 771 | 772 | match accumulator.state() { 773 | &State::Committed(ref j) => assert_eq!(j.digest, Digest(999)), 774 | s => panic!("wrong state: {:?}", s), 775 | } 776 | 777 | accumulator.import_message(LocalizedMessage::Propose(LocalizedProposal { 778 | sender: AuthorityId(8), 779 | full_signature: Signature(999, 8), 780 | digest_signature: Signature(999, 8), 781 | round_number: 1, 782 | proposal: Candidate(999), 783 | digest: Digest(999), 784 | })).unwrap(); 785 | 786 | match accumulator.state() { 787 | &State::Committed(ref j) => assert_eq!(j.digest, Digest(999)), 788 | s => panic!("wrong state: {:?}", s), 789 | } 790 | } 791 | 792 | #[test] 793 | fn propose_after_advance_does_not_clobber_state() { 794 | let mut accumulator = Accumulator::::new(1, 7, AuthorityId(8)); 795 | assert_eq!(accumulator.state(), &State::Begin); 796 | 797 | for i in 0..7 { 798 | accumulator.import_message(LocalizedVote { 799 | sender: AuthorityId(i), 800 | signature: Signature(1, i), 801 | vote: Vote::AdvanceRound(1), 802 | }.into()).unwrap(); 803 | } 804 | 805 | match accumulator.state() { 806 | &State::Advanced(_) => {} 807 | s => panic!("wrong state: {:?}", s), 808 | } 809 | 810 | accumulator.import_message(LocalizedMessage::Propose(LocalizedProposal { 811 | sender: AuthorityId(8), 812 | full_signature: Signature(999, 8), 813 | digest_signature: Signature(999, 8), 814 | round_number: 1, 815 | proposal: Candidate(999), 816 | digest: Digest(999), 817 | })).unwrap(); 818 | 819 | match accumulator.state() { 820 | &State::Advanced(_) => {} 821 | s => panic!("wrong state: {:?}", s), 822 | } 823 | } 824 | 825 | #[test] 826 | fn begin_to_advance() { 827 | let mut accumulator = Accumulator::::new(1, 7, AuthorityId(8)); 828 | assert_eq!(accumulator.state(), &State::Begin); 829 | 830 | for i in 0..7 { 831 | accumulator.import_message(LocalizedVote { 832 | sender: AuthorityId(i), 833 | signature: Signature(1, i), 834 | vote: Vote::AdvanceRound(1), 835 | }.into()).unwrap(); 836 | } 837 | 838 | match accumulator.state() { 839 | &State::Advanced(ref j) => assert!(j.is_none()), 840 | s => panic!("wrong state: {:?}", s), 841 | } 842 | } 843 | 844 | #[test] 845 | fn conclude_without_prepare() { 846 | let mut accumulator = Accumulator::::new(1, 7, AuthorityId(8)); 847 | assert_eq!(accumulator.state(), &State::Begin); 848 | 849 | for i in 0..7 { 850 | accumulator.import_message(LocalizedVote { 851 | sender: AuthorityId(i), 852 | signature: Signature(999, i), 853 | vote: Vote::Commit(1, Digest(999)), 854 | }.into()).unwrap(); 855 | } 856 | 857 | match accumulator.state() { 858 | &State::Committed(ref j) => assert_eq!(j.digest, Digest(999)), 859 | s => panic!("wrong state: {:?}", s), 860 | } 861 | } 862 | 863 | #[test] 864 | fn double_prepare_is_misbehavior() { 865 | let mut accumulator = Accumulator::::new(1, 7, AuthorityId(8)); 866 | assert_eq!(accumulator.state(), &State::Begin); 867 | 868 | for i in 0..7 { 869 | accumulator.import_message(LocalizedVote { 870 | sender: AuthorityId(i), 871 | signature: Signature(999, i), 872 | vote: Vote::Prepare(1, Digest(999)), 873 | }.into()).unwrap(); 874 | 875 | let res = accumulator.import_message(LocalizedVote { 876 | sender: AuthorityId(i), 877 | signature: Signature(123, i), 878 | vote: Vote::Prepare(1, Digest(123)), 879 | }.into()); 880 | 881 | assert!(res.is_err()); 882 | 883 | } 884 | } 885 | 886 | #[test] 887 | fn double_commit_is_misbehavior() { 888 | let mut accumulator = Accumulator::::new(1, 7, AuthorityId(8)); 889 | assert_eq!(accumulator.state(), &State::Begin); 890 | 891 | for i in 0..7 { 892 | accumulator.import_message(LocalizedVote { 893 | sender: AuthorityId(i), 894 | signature: Signature(999, i), 895 | vote: Vote::Commit(1, Digest(999)), 896 | }.into()).unwrap(); 897 | 898 | let res = accumulator.import_message(LocalizedVote { 899 | sender: AuthorityId(i), 900 | signature: Signature(123, i), 901 | vote: Vote::Commit(1, Digest(123)), 902 | }.into()); 903 | 904 | assert!(res.is_err()); 905 | 906 | } 907 | } 908 | 909 | #[test] 910 | fn double_propose_is_misbehavior() { 911 | let mut accumulator = Accumulator::::new(1, 7, AuthorityId(8)); 912 | assert_eq!(accumulator.state(), &State::Begin); 913 | 914 | accumulator.import_message(LocalizedMessage::Propose(LocalizedProposal { 915 | sender: AuthorityId(8), 916 | full_signature: Signature(999, 8), 917 | digest_signature: Signature(999, 8), 918 | round_number: 1, 919 | proposal: Candidate(999), 920 | digest: Digest(999), 921 | })).unwrap(); 922 | 923 | let res = accumulator.import_message(LocalizedMessage::Propose(LocalizedProposal { 924 | sender: AuthorityId(8), 925 | full_signature: Signature(500, 8), 926 | digest_signature: Signature(500, 8), 927 | round_number: 1, 928 | proposal: Candidate(500), 929 | digest: Digest(500), 930 | })); 931 | 932 | assert!(res.is_err()); 933 | } 934 | } 935 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 Parity Technologies (UK) Ltd. 2 | // This file is part of Rhododendron 3 | 4 | // Rhododendron is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // Rhododendron is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | 14 | // You should have received a copy of the GNU General Public License 15 | // along with Rhododendron If not, see . 16 | 17 | //! BFT Agreement based on a rotating proposer in different rounds, generic futures-based implementation. 18 | //! 19 | //! Attempt to reach BFT agreement on a candidate. Not ready for production. 20 | //! 21 | //! Agreement is between `n` nodes, `max_faulty` of whom are faulty. 22 | //! `max_faulty` should be less than 1/3 of `nodes`, otherwise agreement may never be reached. 23 | //! 24 | //! Initiate agreement by calling `agree` with a generic `Context`, an input stream, and an 25 | //! output sink. The input should never logically conclude and contain messages from all other nodes, 26 | //! while the output sink 27 | //! 28 | //! Note that it is possible to witness agreement being reached without ever 29 | //! seeing the candidate. Any candidates seen will be checked for validity. 30 | //! 31 | //! Although technically the agreement will always complete (given the eventual 32 | //! delivery of messages), in practice it is possible for this future to 33 | //! conclude without having witnessed the conclusion. 34 | //! 35 | //! Users of the `Agreement` future should schedule it to be pre-empted 36 | //! by an external import of an agreed value. 37 | 38 | use std::collections::{HashMap, BTreeMap, VecDeque}; 39 | use std::collections::hash_map; 40 | use std::fmt::Debug; 41 | use std::hash::Hash; 42 | 43 | use futures::{future, Future, Stream, Sink, Poll, Async, AsyncSink}; 44 | use log::trace; 45 | #[cfg(any(test, feature="codec"))] 46 | use parity_scale_codec::{Encode, Decode}; 47 | 48 | use self::accumulator::State; 49 | 50 | pub use self::accumulator::{Accumulator, Justification, PrepareJustification, UncheckedJustification, Misbehavior}; 51 | 52 | pub mod accumulator; 53 | 54 | #[cfg(test)] 55 | mod tests; 56 | 57 | /// Votes during a round. 58 | #[derive(Debug, Clone, PartialEq, Eq)] 59 | #[cfg_attr(any(test, feature="codec"), derive(Encode, Decode))] 60 | pub enum Vote { 61 | /// Prepare to vote for proposal with digest D. 62 | Prepare(u32, D), 63 | /// Commit to proposal with digest D.. 64 | Commit(u32, D), 65 | /// Propose advancement to a new round. 66 | AdvanceRound(u32), 67 | } 68 | 69 | impl Vote { 70 | /// Extract the round number. 71 | pub fn round_number(&self) -> u32 { 72 | match *self { 73 | Vote::Prepare(round, _) => round, 74 | Vote::Commit(round, _) => round, 75 | Vote::AdvanceRound(round) => round, 76 | } 77 | } 78 | } 79 | 80 | /// Messages over the proposal. 81 | /// Each message carries an associated round number. 82 | #[derive(Debug, Clone, PartialEq, Eq)] 83 | #[cfg_attr(any(test, feature="codec"), derive(Encode, Decode))] 84 | pub enum Message { 85 | /// A proposal itself. 86 | Propose(u32, C), 87 | /// A vote of some kind, localized to a round number. 88 | Vote(Vote), 89 | } 90 | 91 | impl From> for Message { 92 | fn from(vote: Vote) -> Self { 93 | Message::Vote(vote) 94 | } 95 | } 96 | 97 | /// A localized proposal message. Contains two signed pieces of data. 98 | #[derive(Debug, Clone)] 99 | #[cfg_attr(any(test, feature="codec"), derive(Encode, Decode))] 100 | pub struct LocalizedProposal { 101 | /// The round number. 102 | pub round_number: u32, 103 | /// The proposal sent. 104 | pub proposal: C, 105 | /// The digest of the proposal. 106 | pub digest: D, 107 | /// The sender of the proposal 108 | pub sender: V, 109 | /// The signature on the message (propose, round number, digest) 110 | pub digest_signature: S, 111 | /// The signature on the message (propose, round number, proposal) 112 | pub full_signature: S, 113 | } 114 | 115 | /// A localized vote message, including the sender. 116 | #[derive(Debug, Clone)] 117 | #[cfg_attr(any(test, feature="codec"), derive(Encode, Decode))] 118 | pub struct LocalizedVote { 119 | /// The message sent. 120 | pub vote: Vote, 121 | /// The sender of the message 122 | pub sender: V, 123 | /// The signature of the message. 124 | pub signature: S, 125 | } 126 | 127 | /// A localized message. 128 | #[derive(Debug, Clone)] 129 | #[cfg_attr(any(test, feature="codec"), derive(Encode, Decode))] 130 | pub enum LocalizedMessage { 131 | /// A proposal. 132 | Propose(LocalizedProposal), 133 | /// A vote. 134 | Vote(LocalizedVote), 135 | } 136 | 137 | impl LocalizedMessage { 138 | /// Extract the sender. 139 | pub fn sender(&self) -> &V { 140 | match *self { 141 | LocalizedMessage::Propose(ref proposal) => &proposal.sender, 142 | LocalizedMessage::Vote(ref vote) => &vote.sender, 143 | } 144 | } 145 | 146 | /// Extract the round number. 147 | pub fn round_number(&self) -> u32 { 148 | match *self { 149 | LocalizedMessage::Propose(ref proposal) => proposal.round_number, 150 | LocalizedMessage::Vote(ref vote) => vote.vote.round_number(), 151 | } 152 | } 153 | } 154 | 155 | impl From> for LocalizedMessage { 156 | fn from(vote: LocalizedVote) -> Self { 157 | LocalizedMessage::Vote(vote) 158 | } 159 | } 160 | 161 | /// A reason why we are advancing round. 162 | #[derive(Debug, Clone, PartialEq, Eq)] 163 | #[cfg_attr(any(test, feature="codec"), derive(Encode, Decode))] 164 | pub enum AdvanceRoundReason { 165 | /// We received enough `AdvanceRound` messages to advance to the next round. 166 | Timeout, 167 | /// We got enough `Prepare` messages for a future round to fast-forward to it. 168 | WasBehind, 169 | } 170 | 171 | /// Context necessary for agreement. 172 | /// 173 | /// Provides necessary types for protocol messages, and functions necessary for a 174 | /// participant to evaluate and create those messages. 175 | pub trait Context { 176 | /// Errors which can occur from the futures in this context. 177 | type Error: From; 178 | /// Candidate proposed. 179 | type Candidate: Debug + Eq + Clone; 180 | /// Candidate digest. 181 | type Digest: Debug + Hash + Eq + Clone; 182 | /// Authority ID. 183 | type AuthorityId: Debug + Hash + Eq + Clone; 184 | /// Signature. 185 | type Signature: Debug + Eq + Clone; 186 | /// A future that resolves when a round timeout is concluded. 187 | type RoundTimeout: Future; 188 | /// A future that resolves when a proposal is ready. 189 | type CreateProposal: Future; 190 | /// A future that resolves when a proposal has been evaluated. 191 | type EvaluateProposal: Future; 192 | 193 | /// Get the local authority ID. 194 | fn local_id(&self) -> Self::AuthorityId; 195 | 196 | /// Get the best proposal. 197 | fn proposal(&self) -> Self::CreateProposal; 198 | 199 | /// Get the digest of a candidate. 200 | fn candidate_digest(&self, candidate: &Self::Candidate) -> Self::Digest; 201 | 202 | /// Sign a message using the local authority ID. 203 | /// In the case of a proposal message, it should sign on the hash and 204 | /// the bytes of the proposal. 205 | fn sign_local(&self, message: Message) 206 | -> LocalizedMessage; 207 | 208 | /// Get the proposer for a given round of consensus. 209 | fn round_proposer(&self, round: u32) -> Self::AuthorityId; 210 | 211 | /// Whether the proposal is valid. 212 | fn proposal_valid(&self, proposal: &Self::Candidate) -> Self::EvaluateProposal; 213 | 214 | /// Create a round timeout. The context will determine the correct timeout 215 | /// length, and create a future that will resolve when the timeout is 216 | /// concluded. 217 | fn begin_round_timeout(&self, round: u32) -> Self::RoundTimeout; 218 | 219 | /// This hook is called when we advance from current `round` to `next_round`. `proposal` is 220 | /// `Some` if there was one on the current `round`. 221 | fn on_advance_round( 222 | &self, 223 | accumulator: &Accumulator, 224 | round: u32, 225 | next_round: u32, 226 | reason: AdvanceRoundReason, 227 | ) { 228 | // The awkward let _ is used to suppress the unused variables 229 | // warning (https://github.com/rust-lang/rust/issues/26487) 230 | let _ = (accumulator, round, next_round, reason); 231 | } 232 | } 233 | 234 | /// Communication that can occur between participants in consensus. 235 | #[derive(Debug, Clone)] 236 | #[cfg_attr(any(test, feature="codec"), derive(Encode, Decode))] 237 | pub enum Communication { 238 | /// A consensus message (proposal or vote) 239 | Consensus(LocalizedMessage), 240 | /// Auxiliary communication (just proof-of-lock for now). 241 | Auxiliary(PrepareJustification), 242 | } 243 | 244 | /// Hack to get around type alias warning. 245 | pub trait TypeResolve { 246 | /// Communication type. 247 | type Communication; 248 | } 249 | 250 | impl TypeResolve for C { 251 | type Communication = Communication; 252 | } 253 | 254 | #[derive(Debug)] 255 | struct Sending { 256 | items: VecDeque, 257 | flushing: bool, 258 | } 259 | 260 | impl Sending { 261 | fn with_capacity(n: usize) -> Self { 262 | Sending { 263 | items: VecDeque::with_capacity(n), 264 | flushing: false, 265 | } 266 | } 267 | 268 | fn push(&mut self, item: T) { 269 | self.items.push_back(item); 270 | } 271 | 272 | // process all the sends into the sink. 273 | fn process_all>(&mut self, sink: &mut S) -> Poll<(), S::SinkError> { 274 | loop { 275 | while let Some(item) = self.items.pop_front() { 276 | match sink.start_send(item) { 277 | Err(e) => return Err(e), 278 | Ok(AsyncSink::NotReady(item)) => { 279 | self.items.push_front(item); 280 | break; 281 | } 282 | Ok(AsyncSink::Ready) => { 283 | // At least one item is buffered into the sink so we must ensure 284 | // that at some point we will call `poll_complete`. 285 | self.flushing = true; 286 | } 287 | } 288 | } 289 | 290 | if self.flushing { 291 | if let Async::Ready(()) = sink.poll_complete()? { 292 | self.flushing = false; 293 | } 294 | } 295 | 296 | match (self.flushing, self.items.len()) { 297 | // Still flushing, schedule to poll later. 298 | (true, _) => return Ok(Async::NotReady), 299 | // Return `Ready` only if all items have been sent and flushed. 300 | (false, pending) if pending == 0 => return Ok(Async::Ready(())), 301 | // Flushing is complete, however there are still pending items left. 302 | (false, _) => continue, 303 | } 304 | } 305 | } 306 | } 307 | 308 | /// Error returned when the input stream concludes. 309 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] 310 | pub struct InputStreamConcluded; 311 | 312 | impl ::std::fmt::Display for InputStreamConcluded { 313 | fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { 314 | write!(f, "{}", ::std::error::Error::description(self)) 315 | } 316 | } 317 | 318 | impl ::std::error::Error for InputStreamConcluded { 319 | fn description(&self) -> &str { 320 | "input stream of messages concluded prematurely" 321 | } 322 | } 323 | 324 | // get the "full BFT" threshold based on an amount of nodes and 325 | // a maximum faulty. if nodes == 3f + 1, then threshold == 2f + 1. 326 | fn bft_threshold(nodes: usize, max_faulty: usize) -> usize { 327 | nodes - max_faulty 328 | } 329 | 330 | /// Committed successfully. 331 | #[derive(Debug, Clone)] 332 | #[cfg_attr(any(test, feature="codec"), derive(Encode, Decode))] 333 | pub struct Committed { 334 | /// The candidate committed for. This will be unknown if 335 | /// we never witnessed the proposal of the last round. 336 | pub candidate: Option, 337 | /// The round number we saw the commit in. 338 | pub round_number: u32, 339 | /// A justification for the candidate. 340 | pub justification: Justification, 341 | } 342 | 343 | struct Locked { 344 | justification: PrepareJustification, 345 | } 346 | 347 | impl Locked { 348 | fn digest(&self) -> &D { 349 | &self.justification.digest 350 | } 351 | } 352 | 353 | // the state of the local node during the current state of consensus. 354 | // 355 | // behavior is different when locked on a proposal. 356 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] 357 | enum LocalState { 358 | Start, 359 | Proposed, 360 | Prepared(bool), // whether we thought it valid. 361 | Committed, 362 | VoteAdvance, 363 | } 364 | 365 | // This structure manages a single "view" of consensus. 366 | // 367 | // We maintain two message accumulators: one for the round we are currently in, 368 | // and one for a future round. 369 | // 370 | // We advance the round accumulators when one of two conditions is met: 371 | // - we witness consensus of advancement in the current round. in this case we 372 | // advance by one. 373 | // - a higher threshold-prepare is broadcast to us. in this case we can 374 | // advance to the round of the threshold-prepare. this is an indication 375 | // that we have experienced severe asynchrony/clock drift with the remainder 376 | // of the other authorities, and it is unlikely that we can assist in 377 | // consensus meaningfully. nevertheless we make an attempt. 378 | struct Strategy { 379 | nodes: usize, 380 | max_faulty: usize, 381 | fetching_proposal: Option, 382 | evaluating_proposal: Option, 383 | round_timeout: Option>, 384 | local_state: LocalState, 385 | locked: Option>, 386 | notable_candidates: HashMap, 387 | current_accumulator: Accumulator, 388 | future_accumulators: BTreeMap>, 389 | local_id: C::AuthorityId, 390 | misbehavior: HashMap>, 391 | earliest_lock_round: u32, 392 | } 393 | 394 | impl Strategy { 395 | fn create(context: &C, nodes: usize, max_faulty: usize) -> Self { 396 | let threshold = bft_threshold(nodes, max_faulty); 397 | 398 | let current_accumulator = Accumulator::new( 399 | 0, 400 | threshold, 401 | context.round_proposer(0), 402 | ); 403 | 404 | Strategy { 405 | nodes, 406 | max_faulty, 407 | current_accumulator, 408 | future_accumulators: BTreeMap::new(), 409 | fetching_proposal: None, 410 | evaluating_proposal: None, 411 | local_state: LocalState::Start, 412 | locked: None, 413 | notable_candidates: HashMap::new(), 414 | round_timeout: None, 415 | local_id: context.local_id(), 416 | misbehavior: HashMap::new(), 417 | earliest_lock_round: 0, 418 | } 419 | } 420 | 421 | fn current_round(&self) -> u32 { 422 | self.current_accumulator.round_number() 423 | } 424 | 425 | fn import_message( 426 | &mut self, 427 | context: &C, 428 | msg: LocalizedMessage 429 | ) { 430 | let round_number = msg.round_number(); 431 | 432 | let sender = msg.sender().clone(); 433 | let current_round = self.current_round(); 434 | let misbehavior = if round_number == current_round { 435 | self.current_accumulator.import_message(msg) 436 | } else if round_number > current_round { 437 | let threshold = bft_threshold(self.nodes, self.max_faulty); 438 | 439 | let future_acc = self.future_accumulators.entry(round_number).or_insert_with(|| { 440 | Accumulator::new( 441 | round_number, 442 | threshold, 443 | context.round_proposer(round_number), 444 | ) 445 | }); 446 | 447 | future_acc.import_message(msg) 448 | } else { 449 | Ok(()) 450 | }; 451 | 452 | if let Err(misbehavior) = misbehavior { 453 | self.misbehavior.insert(sender, misbehavior); 454 | } 455 | } 456 | 457 | fn import_lock_proof( 458 | &mut self, 459 | context: &C, 460 | justification: PrepareJustification, 461 | ) { 462 | // TODO: find a way to avoid processing of the signatures if the sender is 463 | // not the primary or the round number is low. 464 | if justification.round_number > self.current_round() { 465 | // jump ahead to the prior round as this is an indication of a supermajority 466 | // good nodes being at least on that round. 467 | self.advance_to_round(context, justification.round_number, AdvanceRoundReason::WasBehind); 468 | } 469 | 470 | let lock_to_new = justification.round_number >= self.earliest_lock_round; 471 | 472 | if lock_to_new { 473 | self.earliest_lock_round = justification.round_number; 474 | self.locked = Some(Locked { justification }) 475 | } 476 | } 477 | 478 | // poll the strategy: this will queue messages to be sent and advance 479 | // rounds if necessary. 480 | // 481 | // only call within the context of a `Task`. 482 | fn poll( 483 | &mut self, 484 | context: &C, 485 | sending: &mut Sending<::Communication> 486 | ) 487 | -> Poll, C::Error> 488 | { 489 | let mut last_watermark = (self.current_round(), self.local_state); 490 | 491 | // poll until either completion or state doesn't change. 492 | loop { 493 | trace!(target: "bft", "Polling BFT logic. State={:?}", last_watermark); 494 | match self.poll_once(context, sending)? { 495 | Async::Ready(x) => return Ok(Async::Ready(x)), 496 | Async::NotReady => { 497 | let new_watermark = (self.current_round(), self.local_state); 498 | 499 | if new_watermark == last_watermark { 500 | return Ok(Async::NotReady) 501 | } else { 502 | last_watermark = new_watermark; 503 | } 504 | } 505 | } 506 | } 507 | } 508 | 509 | // perform one round of polling: attempt to broadcast messages and change the state. 510 | // if the round or internal round-state changes, this should be called again. 511 | fn poll_once( 512 | &mut self, 513 | context: &C, 514 | sending: &mut Sending<::Communication> 515 | ) 516 | -> Poll, C::Error> 517 | { 518 | self.propose(context, sending)?; 519 | self.prepare(context, sending)?; 520 | self.commit(context, sending); 521 | self.vote_advance(context, sending)?; 522 | 523 | let advance = match self.current_accumulator.state() { 524 | &State::Advanced(ref p_just) => { 525 | // lock to any witnessed prepare justification. 526 | if let Some(p_just) = p_just.as_ref() { 527 | self.locked = Some(Locked { justification: p_just.clone() }); 528 | } 529 | 530 | let round_number = self.current_round(); 531 | Some(round_number + 1) 532 | } 533 | &State::Committed(ref just) => { 534 | // fetch the agreed-upon candidate: 535 | // - we may not have received the proposal in the first place 536 | // - there is no guarantee that the proposal we got was agreed upon 537 | // (can happen if faulty primary) 538 | // - look in the candidates of prior rounds just in case. 539 | let candidate = self.current_accumulator 540 | .proposal() 541 | .and_then(|c| if context.candidate_digest(c) == just.digest { 542 | Some(c.clone()) 543 | } else { 544 | None 545 | }) 546 | .or_else(|| self.notable_candidates.get(&just.digest).cloned()); 547 | 548 | let committed = Committed { 549 | candidate, 550 | round_number: self.current_accumulator.round_number(), 551 | justification: just.clone() 552 | }; 553 | 554 | return Ok(Async::Ready(committed)) 555 | } 556 | _ => None, 557 | }; 558 | 559 | if let Some(new_round) = advance { 560 | self.advance_to_round(context, new_round, AdvanceRoundReason::Timeout); 561 | } 562 | 563 | Ok(Async::NotReady) 564 | } 565 | 566 | fn propose( 567 | &mut self, 568 | context: &C, 569 | sending: &mut Sending<::Communication> 570 | ) 571 | -> Result<(), C::Error> 572 | { 573 | if let LocalState::Start = self.local_state { 574 | let mut propose = false; 575 | if let &State::Begin = self.current_accumulator.state() { 576 | let round_number = self.current_round(); 577 | let primary = context.round_proposer(round_number); 578 | propose = self.local_id == primary; 579 | }; 580 | 581 | if !propose { return Ok(()) } 582 | 583 | // obtain the proposal to broadcast. 584 | let proposal = match self.locked { 585 | Some(ref locked) => { 586 | // TODO: it's possible but very unlikely that we don't have the 587 | // corresponding proposal for what we are locked to. 588 | // 589 | // since this is an edge case on an edge case, it is fine 590 | // to eat the round timeout for now, but it can be optimized by 591 | // broadcasting an advance vote. 592 | self.notable_candidates.get(locked.digest()).cloned() 593 | } 594 | None => { 595 | let res = self.fetching_proposal 596 | .get_or_insert_with(|| context.proposal()) 597 | .poll()?; 598 | 599 | match res { 600 | Async::Ready(p) => Some(p), 601 | Async::NotReady => None, 602 | } 603 | } 604 | }; 605 | 606 | if let Some(proposal) = proposal { 607 | self.fetching_proposal = None; 608 | 609 | let message = Message::Propose( 610 | self.current_round(), 611 | proposal 612 | ); 613 | 614 | self.import_and_send_message(message, context, sending); 615 | 616 | // broadcast the justification along with the proposal if we are locked. 617 | if let Some(ref locked) = self.locked { 618 | sending.push( 619 | Communication::Auxiliary(locked.justification.clone()) 620 | ); 621 | } 622 | 623 | self.local_state = LocalState::Proposed; 624 | } 625 | } 626 | 627 | Ok(()) 628 | } 629 | 630 | fn prepare( 631 | &mut self, 632 | context: &C, 633 | sending: &mut Sending<::Communication> 634 | ) 635 | -> Result<(), C::Error> 636 | { 637 | // prepare only upon start or having proposed. 638 | match self.local_state { 639 | LocalState::Start | LocalState::Proposed => {}, 640 | _ => return Ok(()) 641 | }; 642 | 643 | let mut prepare_for = None; 644 | 645 | // we can't prepare until something was proposed. 646 | if let &State::Proposed(ref candidate) = self.current_accumulator.state() { 647 | let digest = context.candidate_digest(candidate); 648 | 649 | // vote to prepare only if we believe the candidate to be valid and 650 | // we are not locked on some other candidate. 651 | match &mut self.locked { 652 | &mut Some(ref locked) if locked.digest() != &digest => {} 653 | locked => { 654 | let res = self.evaluating_proposal 655 | .get_or_insert_with(|| context.proposal_valid(candidate)) 656 | .poll()?; 657 | 658 | if let Async::Ready(valid) = res { 659 | self.evaluating_proposal = None; 660 | self.local_state = LocalState::Prepared(valid); 661 | 662 | if valid { 663 | prepare_for = Some(digest); 664 | } else { 665 | // if the locked block is bad, unlock from it and 666 | // refuse to lock to anything prior to it. 667 | if locked.as_ref().map_or(false, |locked| locked.digest() == &digest) { 668 | *locked = None; 669 | self.earliest_lock_round = ::std::cmp::max( 670 | self.current_accumulator.round_number(), 671 | self.earliest_lock_round, 672 | ); 673 | } 674 | } 675 | } 676 | } 677 | } 678 | } 679 | 680 | if let Some(digest) = prepare_for { 681 | let message = Vote::Prepare( 682 | self.current_round(), 683 | digest 684 | ).into(); 685 | 686 | self.import_and_send_message(message, context, sending); 687 | } 688 | 689 | Ok(()) 690 | } 691 | 692 | fn commit( 693 | &mut self, 694 | context: &C, 695 | sending: &mut Sending<::Communication> 696 | ) { 697 | // commit only if we haven't voted to advance or committed already 698 | match self.local_state { 699 | LocalState::Committed | LocalState::VoteAdvance => return, 700 | _ => {} 701 | } 702 | 703 | let mut commit_for = None; 704 | 705 | let thought_good = match self.local_state { 706 | LocalState::Prepared(good) => good, 707 | _ => true, // assume true. 708 | }; 709 | 710 | if let &State::Prepared(ref p_just) = self.current_accumulator.state() { 711 | // we are now locked to this prepare justification. 712 | // refuse to lock if the thing is bad. 713 | self.earliest_lock_round = self.current_accumulator.round_number(); 714 | if thought_good { 715 | let digest = p_just.digest.clone(); 716 | self.locked = Some(Locked { justification: p_just.clone() }); 717 | commit_for = Some(digest); 718 | } 719 | } 720 | 721 | if let Some(digest) = commit_for { 722 | let message = Vote::Commit( 723 | self.current_round(), 724 | digest 725 | ).into(); 726 | 727 | self.import_and_send_message(message, context, sending); 728 | self.local_state = LocalState::Committed; 729 | } 730 | } 731 | 732 | fn vote_advance( 733 | &mut self, 734 | context: &C, 735 | sending: &mut Sending<::Communication> 736 | ) 737 | -> Result<(), C::Error> 738 | { 739 | // we can vote for advancement under all circumstances unless we have already. 740 | if let LocalState::VoteAdvance = self.local_state { return Ok(()) } 741 | 742 | // if we got f + 1 advance votes, or the timeout has fired, and we haven't 743 | // sent an AdvanceRound message yet, do so. 744 | let mut attempt_advance = self.current_accumulator.advance_votes() > self.max_faulty; 745 | 746 | // if we evaluated the proposal and it was bad, vote to advance round. 747 | if let LocalState::Prepared(false) = self.local_state { 748 | attempt_advance = true; 749 | } 750 | 751 | // if the timeout has fired, vote to advance round. 752 | let round_number = self.current_accumulator.round_number(); 753 | let timer_res = self.round_timeout 754 | .get_or_insert_with(|| context.begin_round_timeout(round_number).fuse()) 755 | .poll()?; 756 | 757 | if let Async::Ready(_) = timer_res { attempt_advance = true } 758 | 759 | if attempt_advance { 760 | let message = Vote::AdvanceRound( 761 | self.current_round(), 762 | ).into(); 763 | 764 | self.import_and_send_message(message, context, sending); 765 | self.local_state = LocalState::VoteAdvance; 766 | } 767 | 768 | Ok(()) 769 | } 770 | 771 | fn advance_to_round(&mut self, context: &C, round: u32, reason: AdvanceRoundReason) { 772 | assert!(round > self.current_round()); 773 | trace!(target: "bft", "advancing to round {}", round); 774 | 775 | self.fetching_proposal = None; 776 | self.evaluating_proposal = None; 777 | self.round_timeout = None; 778 | self.local_state = LocalState::Start; 779 | 780 | // notify the context that we are about to advance round. 781 | context.on_advance_round( 782 | &self.current_accumulator, 783 | self.current_round(), 784 | round, 785 | reason, 786 | ); 787 | 788 | // when advancing from a round, store away the witnessed proposal. 789 | // 790 | // if we or other participants end up locked on that candidate, 791 | // we will have it. 792 | if let Some(proposal) = self.current_accumulator.proposal() { 793 | let digest = context.candidate_digest(proposal); 794 | self.notable_candidates.entry(digest).or_insert_with(|| proposal.clone()); 795 | } 796 | 797 | // if we jump ahead more than one round, get rid of the ones in between. 798 | for irrelevant in (self.current_round() + 1)..round { 799 | self.future_accumulators.remove(&irrelevant); 800 | } 801 | 802 | // use stored future accumulator for given round or create if it doesn't exist. 803 | self.current_accumulator = match self.future_accumulators.remove(&round) { 804 | Some(x) => x, 805 | None => Accumulator::new( 806 | round, 807 | bft_threshold(self.nodes, self.max_faulty), 808 | context.round_proposer(round), 809 | ), 810 | }; 811 | } 812 | 813 | fn import_and_send_message( 814 | &mut self, 815 | message: Message, 816 | context: &C, 817 | sending: &mut Sending<::Communication> 818 | ) { 819 | let signed_message = context.sign_local(message); 820 | self.import_message(context, signed_message.clone()); 821 | sending.push(Communication::Consensus(signed_message)); 822 | } 823 | } 824 | 825 | /// Future that resolves upon BFT agreement for a candidate. 826 | #[must_use = "futures do nothing unless polled"] 827 | pub struct Agreement { 828 | context: C, 829 | input: I, 830 | output: O, 831 | concluded: Option>, 832 | sending: Sending<::Communication>, 833 | strategy: Strategy, 834 | } 835 | 836 | impl Future for Agreement 837 | where 838 | C: Context, 839 | I: Stream::Communication,Error=C::Error>, 840 | O: Sink::Communication,SinkError=C::Error>, 841 | { 842 | type Item = Committed; 843 | type Error = C::Error; 844 | 845 | fn poll(&mut self) -> Poll { 846 | // even if we've observed the conclusion, wait until all 847 | // pending outgoing messages are flushed. 848 | if let Some(just) = self.concluded.take() { 849 | return Ok(match self.sending.process_all(&mut self.output)? { 850 | Async::Ready(()) => Async::Ready(just), 851 | Async::NotReady => { 852 | self.concluded = Some(just); 853 | Async::NotReady 854 | } 855 | }) 856 | } 857 | 858 | // drive state machine as long as there are new messages. 859 | let mut driving = true; 860 | while driving { 861 | driving = match self.input.poll()? { 862 | Async::Ready(msg) => { 863 | match msg.ok_or(InputStreamConcluded)? { 864 | Communication::Consensus(message) => self.strategy.import_message(&self.context, message), 865 | Communication::Auxiliary(lock_proof) 866 | => self.strategy.import_lock_proof(&self.context, lock_proof), 867 | } 868 | 869 | true 870 | } 871 | Async::NotReady => false, 872 | }; 873 | 874 | // drive state machine after handling new input. 875 | if let Async::Ready(just) = self.strategy.poll(&self.context, &mut self.sending)? { 876 | self.concluded = Some(just); 877 | return self.poll(); 878 | } 879 | } 880 | 881 | // make progress on flushing all pending messages. 882 | let _ = self.sending.process_all(&mut self.output)?; 883 | Ok(Async::NotReady) 884 | } 885 | } 886 | 887 | impl Agreement { 888 | /// Get a reference to the underlying context. 889 | pub fn context(&self) -> &C { 890 | &self.context 891 | } 892 | 893 | /// Drain the misbehavior vector. 894 | pub fn drain_misbehavior(&mut self) -> hash_map::Drain> { 895 | self.strategy.misbehavior.drain() 896 | } 897 | 898 | /// Fast-foward the round to the given number. 899 | pub fn fast_forward(&mut self, round: u32) { 900 | if round > self.strategy.current_round() { 901 | self.strategy.advance_to_round(&self.context, round, AdvanceRoundReason::WasBehind); 902 | self.strategy.earliest_lock_round = round; 903 | } 904 | } 905 | } 906 | 907 | /// Attempt to reach BFT agreement on a candidate. 908 | /// 909 | /// `nodes` is the number of nodes in the system. 910 | /// `max_faulty` is the maximum number of faulty nodes. Should be less than 911 | /// 1/3 of `nodes`, otherwise agreement may never be reached. 912 | /// 913 | /// The input stream should never logically conclude. The logic here assumes 914 | /// that messages flushed to the output stream will eventually reach other nodes. 915 | /// 916 | /// Note that it is possible to witness agreement being reached without ever 917 | /// seeing the candidate. Any candidates seen will be checked for validity. 918 | /// 919 | /// Although technically the agreement will always complete (given the eventual 920 | /// delivery of messages), in practice it is possible for this future to 921 | /// conclude without having witnessed the conclusion. 922 | /// In general, this future should be pre-empted by the import of a justification 923 | /// set for this block height. 924 | pub fn agree(context: C, nodes: usize, max_faulty: usize, input: I, output: O) 925 | -> Agreement 926 | where 927 | C: Context, 928 | I: Stream::Communication,Error=C::Error>, 929 | O: Sink::Communication,SinkError=C::Error>, 930 | { 931 | let strategy = Strategy::create(&context, nodes, max_faulty); 932 | Agreement { 933 | context, 934 | input, 935 | output, 936 | concluded: None, 937 | sending: Sending::with_capacity(4), 938 | strategy: strategy, 939 | } 940 | } 941 | -------------------------------------------------------------------------------- /src/tests.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2017 Parity Technologies (UK) Ltd. 2 | // This file is part of Rhododendron 3 | 4 | // Rhododendron is free software: you can redistribute it and/or modify 5 | // it under the terms of the GNU General Public License as published by 6 | // the Free Software Foundation, either version 3 of the License, or 7 | // (at your option) any later version. 8 | 9 | // Rhododendron is distributed in the hope that it will be useful, 10 | // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 | // GNU General Public License for more details. 13 | 14 | // You should have received a copy of the GNU General Public License 15 | // along with Rhododendron. If not, see . 16 | 17 | //! Tests for the candidate agreement strategy. 18 | 19 | use super::*; 20 | 21 | use std::collections::BTreeSet; 22 | use std::sync::{Arc, Mutex}; 23 | use std::sync::atomic::{AtomicUsize, Ordering}; 24 | use std::time::Duration; 25 | 26 | use futures::try_ready; 27 | use futures::prelude::*; 28 | use futures::sync::{oneshot, mpsc}; 29 | use futures::future::FutureResult; 30 | 31 | use tokio_timer::{self, Timer}; 32 | 33 | const ROUND_DURATION: Duration = Duration::from_millis(50); 34 | 35 | struct Network { 36 | endpoints: Vec>, 37 | input: mpsc::UnboundedReceiver<(usize, T)>, 38 | } 39 | 40 | impl Network { 41 | fn new(nodes: usize) 42 | -> (Self, Vec>, Vec>) 43 | { 44 | let mut inputs = Vec::with_capacity(nodes); 45 | let mut outputs = Vec::with_capacity(nodes); 46 | let mut endpoints = Vec::with_capacity(nodes); 47 | 48 | let (in_tx, in_rx) = mpsc::unbounded(); 49 | for _ in 0..nodes { 50 | let (out_tx, out_rx) = mpsc::unbounded(); 51 | inputs.push(in_tx.clone()); 52 | outputs.push(out_rx); 53 | endpoints.push(out_tx); 54 | } 55 | 56 | let network = Network { 57 | endpoints, 58 | input: in_rx, 59 | }; 60 | 61 | (network, inputs, outputs) 62 | } 63 | 64 | fn route_on_thread(self) { 65 | ::std::thread::spawn(move || { let _ = self.wait(); }); 66 | } 67 | } 68 | 69 | impl Future for Network { 70 | type Item = (); 71 | type Error = (); 72 | 73 | fn poll(&mut self) -> Poll<(), Self::Error> { 74 | match try_ready!(self.input.poll()) { 75 | None => Ok(Async::Ready(())), 76 | Some((sender, item)) => { 77 | { 78 | let receiving_endpoints = self.endpoints 79 | .iter() 80 | .enumerate() 81 | .filter(|&(i, _)| i != sender) 82 | .map(|(_, x)| x); 83 | 84 | for endpoint in receiving_endpoints { 85 | let _ = endpoint.unbounded_send(item.clone()); 86 | } 87 | } 88 | 89 | self.poll() 90 | } 91 | } 92 | } 93 | } 94 | 95 | #[derive(Debug, PartialEq, Eq, Clone, Encode, Decode, Hash)] 96 | struct Candidate(u64); 97 | 98 | #[derive(Debug, PartialEq, Eq, Clone, Encode, Decode, Hash)] 99 | struct Digest(u64); 100 | 101 | #[derive(Debug, PartialEq, Eq, Clone, Encode, Decode, Hash)] 102 | struct AuthorityId(u64); 103 | 104 | #[derive(Debug, PartialEq, Eq, Clone, Encode, Decode)] 105 | struct Signature(Message, AuthorityId); 106 | 107 | #[derive(Debug)] 108 | struct Error; 109 | 110 | impl From for Error { 111 | fn from(_: InputStreamConcluded) -> Error { 112 | Error 113 | } 114 | } 115 | 116 | struct TestContext { 117 | local_id: AuthorityId, 118 | proposal: Mutex, 119 | node_count: usize, 120 | current_round: Arc, 121 | timer: Timer, 122 | evaluated: Mutex>, 123 | } 124 | 125 | impl Context for TestContext { 126 | type Error = Error; 127 | type Candidate = Candidate; 128 | type Digest = Digest; 129 | type AuthorityId = AuthorityId; 130 | type Signature = Signature; 131 | type RoundTimeout = Box>; 132 | type CreateProposal = FutureResult; 133 | type EvaluateProposal = FutureResult; 134 | 135 | fn local_id(&self) -> AuthorityId { 136 | self.local_id.clone() 137 | } 138 | 139 | fn proposal(&self) -> Self::CreateProposal { 140 | let proposal = { 141 | let mut p = self.proposal.lock().unwrap(); 142 | let x = *p; 143 | *p += self.node_count; 144 | x as u64 145 | }; 146 | 147 | Ok(Candidate(proposal)).into_future() 148 | } 149 | 150 | fn candidate_digest(&self, candidate: &Candidate) -> Digest { 151 | Digest(candidate.0) 152 | } 153 | 154 | fn sign_local(&self, message: Message) 155 | -> LocalizedMessage 156 | { 157 | let signature = Signature(message.clone(), self.local_id.clone()); 158 | 159 | match message { 160 | Message::Propose(r, proposal) => LocalizedMessage::Propose(LocalizedProposal { 161 | round_number: r, 162 | digest: Digest(proposal.0), 163 | proposal, 164 | digest_signature: signature.clone(), 165 | full_signature: signature, 166 | sender: self.local_id.clone(), 167 | }), 168 | Message::Vote(vote) => LocalizedMessage::Vote(LocalizedVote { 169 | vote, 170 | signature, 171 | sender: self.local_id.clone(), 172 | }), 173 | } 174 | } 175 | 176 | fn round_proposer(&self, round: u32) -> AuthorityId { 177 | AuthorityId((round as u64) % self.node_count as u64) 178 | } 179 | 180 | fn proposal_valid(&self, proposal: &Candidate) -> FutureResult { 181 | self.evaluated.lock().unwrap().insert(proposal.0); 182 | 183 | Ok(proposal.0 % 3 != 0).into_future() 184 | } 185 | 186 | fn begin_round_timeout(&self, round: u32) -> Self::RoundTimeout { 187 | if (round as usize) < self.current_round.load(Ordering::SeqCst) { 188 | Box::new(Ok(()).into_future()) 189 | } else { 190 | let mut round_duration = ROUND_DURATION; 191 | for _ in 0..round { 192 | round_duration *= 2; 193 | } 194 | 195 | let current_round = self.current_round.clone(); 196 | let timeout = self.timer.sleep(round_duration) 197 | .map(move |_| { 198 | current_round.compare_and_swap(round as usize, round as usize + 1, Ordering::SeqCst); 199 | }) 200 | .map_err(|_| Error); 201 | 202 | Box::new(timeout) 203 | } 204 | } 205 | 206 | fn on_advance_round( 207 | &self, 208 | _acc: &Accumulator, 209 | _round: u32, 210 | _next_round: u32, 211 | _reason: AdvanceRoundReason, 212 | ) { 213 | } 214 | } 215 | 216 | fn timeout_in(t: Duration) -> oneshot::Receiver<()> { 217 | let (tx, rx) = oneshot::channel(); 218 | ::std::thread::spawn(move || { 219 | ::std::thread::sleep(t); 220 | let _ = tx.send(()); 221 | }); 222 | 223 | rx 224 | } 225 | 226 | #[test] 227 | fn consensus_completes_with_minimum_good() { 228 | let node_count = 10; 229 | let max_faulty = 3; 230 | 231 | let timer = tokio_timer::wheel().tick_duration(ROUND_DURATION).build(); 232 | 233 | let (network, net_send, net_recv) = Network::new(node_count); 234 | network.route_on_thread(); 235 | 236 | let nodes = net_send 237 | .into_iter() 238 | .zip(net_recv) 239 | .take(node_count - max_faulty) 240 | .enumerate() 241 | .map(|(i, (tx, rx))| { 242 | let ctx = TestContext { 243 | local_id: AuthorityId(i as u64), 244 | proposal: Mutex::new(i), 245 | current_round: Arc::new(AtomicUsize::new(0)), 246 | timer: timer.clone(), 247 | evaluated: Mutex::new(BTreeSet::new()), 248 | node_count, 249 | }; 250 | 251 | agree( 252 | ctx, 253 | node_count, 254 | max_faulty, 255 | rx.map_err(|_| Error), 256 | tx.sink_map_err(|_| Error).with(move |t| Ok((i, t))), 257 | ) 258 | }) 259 | .collect::>(); 260 | 261 | let timeout = timeout_in(Duration::from_millis(500)).map_err(|_| Error); 262 | let results = ::futures::future::join_all(nodes) 263 | .map(Some) 264 | .select(timeout.map(|_| None)) 265 | .wait() 266 | .map(|(i, _)| i) 267 | .map_err(|(e, _)| e) 268 | .expect("to complete") 269 | .expect("to not time out"); 270 | 271 | for result in &results { 272 | assert_eq!(&result.justification.digest, &results[0].justification.digest); 273 | } 274 | } 275 | 276 | #[test] 277 | fn consensus_completes_with_minimum_good_all_initial_proposals_bad() { 278 | let node_count = 10; 279 | let max_faulty = 3; 280 | 281 | let timer = tokio_timer::wheel().tick_duration(ROUND_DURATION).build(); 282 | 283 | let (network, net_send, net_recv) = Network::new(node_count); 284 | network.route_on_thread(); 285 | 286 | let nodes = net_send 287 | .into_iter() 288 | .zip(net_recv) 289 | .take(node_count - max_faulty) 290 | .enumerate() 291 | .map(|(i, (tx, rx))| { 292 | // the first 5 proposals are going to be bad. 293 | let proposal = if i < 5 { 294 | i * 3 // proposals considered bad in the tests if they are % 3 295 | } else { 296 | (i * 3) + 1 297 | }; 298 | 299 | let ctx = TestContext { 300 | local_id: AuthorityId(i as u64), 301 | proposal: Mutex::new(proposal), 302 | current_round: Arc::new(AtomicUsize::new(0)), 303 | timer: timer.clone(), 304 | evaluated: Mutex::new(BTreeSet::new()), 305 | node_count, 306 | }; 307 | 308 | agree( 309 | ctx, 310 | node_count, 311 | max_faulty, 312 | rx.map_err(|_| Error), 313 | tx.sink_map_err(|_| Error).with(move |t| Ok((i, t))), 314 | ) 315 | }) 316 | .collect::>(); 317 | 318 | let timeout = timeout_in(Duration::from_millis(500)).map_err(|_| Error); 319 | let results = ::futures::future::join_all(nodes) 320 | .map(Some) 321 | .select(timeout.map(|_| None)) 322 | .wait() 323 | .map(|(i, _)| i) 324 | .map_err(|(e, _)| e) 325 | .expect("to complete") 326 | .expect("to not time out"); 327 | 328 | for result in &results { 329 | assert_eq!(&result.justification.digest, &results[0].justification.digest); 330 | } 331 | } 332 | 333 | #[test] 334 | fn consensus_does_not_complete_without_enough_nodes() { 335 | let node_count = 10; 336 | let max_faulty = 3; 337 | 338 | let timer = tokio_timer::wheel().tick_duration(ROUND_DURATION).build(); 339 | 340 | let (network, net_send, net_recv) = Network::new(node_count); 341 | network.route_on_thread(); 342 | 343 | let nodes = net_send 344 | .into_iter() 345 | .zip(net_recv) 346 | .take(node_count - max_faulty - 1) 347 | .enumerate() 348 | .map(|(i, (tx, rx))| { 349 | let ctx = TestContext { 350 | local_id: AuthorityId(i as u64), 351 | proposal: Mutex::new(i), 352 | current_round: Arc::new(AtomicUsize::new(0)), 353 | timer: timer.clone(), 354 | evaluated: Mutex::new(BTreeSet::new()), 355 | node_count, 356 | }; 357 | 358 | agree( 359 | ctx, 360 | node_count, 361 | max_faulty, 362 | rx.map_err(|_| Error), 363 | tx.sink_map_err(|_| Error).with(move |t| Ok((i, t))), 364 | ) 365 | }) 366 | .collect::>(); 367 | 368 | let timeout = timeout_in(Duration::from_millis(500)).map_err(|_| Error); 369 | let result = ::futures::future::join_all(nodes) 370 | .map(Some) 371 | .select(timeout.map(|_| None)) 372 | .wait() 373 | .map(|(i, _)| i) 374 | .map_err(|(e, _)| e) 375 | .expect("to complete"); 376 | 377 | assert!(result.is_none(), "not enough online nodes"); 378 | } 379 | 380 | #[test] 381 | fn threshold_plus_one_locked_on_proposal_only_one_with_candidate() { 382 | let node_count = 10; 383 | let max_faulty = 3; 384 | 385 | let locked_proposal = Candidate(999_999_998); 386 | let locked_digest = Digest(999_999_998); 387 | let locked_round = 1; 388 | let justification = UncheckedJustification { 389 | round_number: locked_round, 390 | digest: locked_digest.clone(), 391 | signatures: (0..7) 392 | .map(|i| Signature(Message::Vote(Vote::Prepare(locked_round, locked_digest.clone())), AuthorityId(i))) 393 | .collect() 394 | }.check(7, |_, _, s| Some(s.1.clone())).unwrap(); 395 | 396 | let timer = tokio_timer::wheel().tick_duration(ROUND_DURATION).build(); 397 | 398 | let (network, net_send, net_recv) = Network::new(node_count); 399 | network.route_on_thread(); 400 | 401 | let nodes = net_send 402 | .into_iter() 403 | .zip(net_recv) 404 | .enumerate() 405 | .map(|(i, (tx, rx))| { 406 | let ctx = TestContext { 407 | local_id: AuthorityId(i as u64), 408 | proposal: Mutex::new(i), 409 | current_round: Arc::new(AtomicUsize::new(locked_round as usize + 1)), 410 | timer: timer.clone(), 411 | evaluated: Mutex::new(BTreeSet::new()), 412 | node_count, 413 | }; 414 | let mut agreement = agree( 415 | ctx, 416 | node_count, 417 | max_faulty, 418 | rx.map_err(|_| Error), 419 | tx.sink_map_err(|_| Error).with(move |t| Ok((i, t))), 420 | ); 421 | 422 | agreement.strategy.advance_to_round( 423 | &agreement.context, 424 | locked_round + 1, 425 | AdvanceRoundReason::WasBehind, // doesn't really matter for this test. 426 | ); 427 | 428 | if i >= max_faulty { 429 | agreement.strategy.locked = Some(Locked { 430 | justification: justification.clone(), 431 | }) 432 | } 433 | 434 | if i == max_faulty { 435 | agreement.strategy.notable_candidates.insert( 436 | locked_digest.clone(), 437 | locked_proposal.clone(), 438 | ); 439 | } 440 | 441 | agreement 442 | }) 443 | .collect::>(); 444 | 445 | let timeout = timeout_in(Duration::from_millis(1000)).map_err(|_| Error); 446 | let results = ::futures::future::join_all(nodes) 447 | .map(Some) 448 | .select(timeout.map(|_| None)) 449 | .wait() 450 | .map(|(i, _)| i) 451 | .map_err(|(e, _)| e) 452 | .expect("to complete") 453 | .expect("to not time out"); 454 | 455 | for result in &results { 456 | assert_eq!(&result.justification.digest, &locked_digest); 457 | } 458 | } 459 | 460 | #[test] 461 | fn threshold_plus_one_locked_on_bad_proposal() { 462 | let node_count = 10; 463 | let max_faulty = 3; 464 | 465 | let locked_proposal = Candidate(999_999_999); 466 | let locked_digest = Digest(999_999_999); 467 | let locked_round = 1; 468 | let justification = UncheckedJustification { 469 | round_number: locked_round, 470 | digest: locked_digest.clone(), 471 | signatures: (0..7) 472 | .map(|i| Signature(Message::Vote(Vote::Prepare(locked_round, locked_digest.clone())), AuthorityId(i))) 473 | .collect() 474 | }.check(7, |_, _, s| Some(s.1.clone())).unwrap(); 475 | 476 | let timer = tokio_timer::wheel().tick_duration(ROUND_DURATION).build(); 477 | 478 | let (network, net_send, net_recv) = Network::new(node_count); 479 | network.route_on_thread(); 480 | 481 | let nodes = net_send 482 | .into_iter() 483 | .zip(net_recv) 484 | .enumerate() 485 | .map(|(i, (tx, rx))| { 486 | let ctx = TestContext { 487 | local_id: AuthorityId(i as u64), 488 | proposal: Mutex::new(i), 489 | current_round: Arc::new(AtomicUsize::new(locked_round as usize + 1)), 490 | timer: timer.clone(), 491 | evaluated: Mutex::new(BTreeSet::new()), 492 | node_count, 493 | }; 494 | let mut agreement = agree( 495 | ctx, 496 | node_count, 497 | max_faulty, 498 | rx.map_err(|_| Error), 499 | tx.sink_map_err(|_| Error).with(move |t| Ok((i, t))), 500 | ); 501 | 502 | agreement.strategy.advance_to_round( 503 | &agreement.context, 504 | locked_round + 1, 505 | AdvanceRoundReason::WasBehind, // doesn't really matter for this test. 506 | ); 507 | 508 | if i >= max_faulty { 509 | agreement.strategy.locked = Some(Locked { 510 | justification: justification.clone(), 511 | }); 512 | 513 | agreement.strategy.notable_candidates.insert( 514 | locked_digest.clone(), 515 | locked_proposal.clone(), 516 | ); 517 | } 518 | 519 | agreement 520 | }) 521 | .collect::>(); 522 | 523 | let timeout = timeout_in(Duration::from_millis(1000)).map_err(|_| Error); 524 | let results = ::futures::future::join_all(nodes) 525 | .map(Some) 526 | .select(timeout.map(|_| None)) 527 | .wait() 528 | .map(|(i, _)| i) 529 | .map_err(|(e, _)| e) 530 | .expect("to complete") 531 | .expect("to not time out"); 532 | 533 | for result in &results { 534 | assert!(&result.justification.digest != &locked_digest); 535 | } 536 | } 537 | 538 | #[test] 539 | fn consensus_completes_even_when_nodes_start_with_a_delay() { 540 | let node_count = 10; 541 | let max_faulty = 3; 542 | let base_sleep = Duration::from_millis(75); 543 | 544 | let timer = tokio_timer::wheel().tick_duration(ROUND_DURATION).build(); 545 | 546 | let (network, net_send, net_recv) = Network::new(node_count); 547 | network.route_on_thread(); 548 | 549 | let nodes = net_send 550 | .into_iter() 551 | .zip(net_recv) 552 | .take(node_count - max_faulty) 553 | .enumerate() 554 | .map(|(i, (tx, rx))| { 555 | let ctx = TestContext { 556 | local_id: AuthorityId(i as u64), 557 | proposal: Mutex::new(i), 558 | current_round: Arc::new(AtomicUsize::new(0)), 559 | timer: timer.clone(), 560 | evaluated: Mutex::new(BTreeSet::new()), 561 | node_count, 562 | }; 563 | 564 | let sleep_duration = base_sleep * i as u32; 565 | 566 | timer.sleep(sleep_duration).map_err(|_| Error).and_then(move |_| { 567 | agree( 568 | ctx, 569 | node_count, 570 | max_faulty, 571 | rx.map_err(|_| Error), 572 | tx.sink_map_err(|_| Error).with(move |t| Ok((i, t))), 573 | ) 574 | }) 575 | }) 576 | .collect::>(); 577 | 578 | let timeout = timeout_in(Duration::from_millis(7500)).map_err(|_| Error); 579 | let results = ::futures::future::join_all(nodes) 580 | .map(Some) 581 | .select(timeout.map(|_| None)) 582 | .wait() 583 | .map(|(i, _)| i) 584 | .map_err(|(e, _)| e) 585 | .expect("to complete") 586 | .expect("to not time out"); 587 | 588 | for result in &results { 589 | assert_eq!(&result.justification.digest, &results[0].justification.digest); 590 | } 591 | } 592 | --------------------------------------------------------------------------------