├── .gitignore ├── LICENSE ├── README.md ├── consensus ├── checkpoint.go ├── client.go ├── normallog.go ├── state.go └── viewchange.go ├── correct-new-view.jpg ├── correct-view-cahnge.jpg ├── garbage_collection.jpg ├── main.go ├── message ├── concensus_msg.go └── service_msg.go ├── new_view.jpg ├── node └── node.go ├── normal_case_operation.jpg ├── overview.jpg ├── p2pnetwork ├── p2p.go ├── p2p_http.go └── p2p_tcp.go ├── pbft-consensus-behavior.jpg ├── prepared.jpg ├── safe_prove.jpg ├── service └── service.go ├── test └── client.go ├── view_change.jpg ├── view_change2.jpg └── view_change3.jpg /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | -------------------------------------------------------------------------------- /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 | 635 | Copyright (C) 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 | Copyright (C) 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 | # PBFT 2 | ## Practical Byzantine Fault Tolerance 3 | 4 | ### Thus, the paper makes the following contributions: 5 | 6 | 7 | 1. It describes the first state-machine replication protocol that correctly survives Byzantine faults in asynchronous networks. 8 | 9 | 2. It describes a number of important optimizations that allow the algorithm to perform well so that it can be used in real systems. 10 | 3. It describes the implementation of a Byzantine-fault- tolerant distributed file system. 11 | 4. It provides experimental results that quantify the cost of the replication technique. 12 | 13 | We use a Byzantine failure model, i.e., faulty nodes may behave arbitrarily, subject only to the restriction mentioned below. 14 | We assume independent node failures. For this assumption to be true in the presence of malicious attacks, some steps need to 15 | be taken, e.g., each node should run different implementations of the service code and operating system and should have a 16 | different root password and a different administrator. It is possible to obtain different implementations from the same code 17 | base and for low degrees of replication one can buy operating systems from different vendors. N-version programming, i.e., 18 | different teams of programmers produce different implementations, is another option for some services. 19 | 20 | ![](./safe_prove.jpg) 21 | 22 | ![](./normal_case_operation.jpg) 23 | 24 | ![](./pbft--behavior.jpg) -------------------------------------------------------------------------------- /consensus/checkpoint.go: -------------------------------------------------------------------------------- 1 | package consensus 2 | 3 | import ( 4 | "fmt" 5 | "github.com/didchain/PBFT/message" 6 | ) 7 | 8 | /* 9 | Generating these proofs after executing every operation would be expensive. Instead, they are generated periodically, 10 | when a Request with a sequence number di- visible by some constant (e.g., 100) is executed. We will refer to the states 11 | produced by the execution of these re- quests as checkpoints and we will say that a checkpoint with a proof is a stable checkpoint. 12 | 13 | A replica maintains several logical copies of the service state: the last stable checkpoint, zero or more 14 | checkpoints that are not stable, and a current state. Copy-on-write techniques can be used to reduce the space overhead 15 | to store the extra copies of the state, as discussed in Section 6.3. 16 | The proof of correctness for a checkpoint is generated as follows. When a replica produces a checkpoint, it 17 | multicasts a message to the other replicas, where n is the sequence number of the last Request 18 | whose execution is reflected in the state and d is the digest of the state. Each replica collects checkpoint messages 19 | in its log until it has 2f + 1 of them for sequence number n with the same digest signed by different replicas 20 | (including possibly its own such message). These 2f + 1 messages are the proof of correctness for the checkpoint. 21 | A checkpoint with a proof becomes stable and the replica discards all pre-Prepare, Prepare, and Commit messages 22 | with sequence number less than or equal to n from its log; it also discards all earlier checkpoints and checkpoint messages. 23 | Computing the proofs is efficient because the digest can be computed using incremental cryptography [1] as 24 | discussed in Section 6.3, and proofs are generated rarely. 25 | The checkpoint protocol is used to advance the low and high water marks (which limit what messages will be accepted). 26 | The low-water mark h is equal to the sequence number of the last stable checkpoint. The high water mark H = h + k, where 27 | k is big enough so that replicas do not stall waiting for a checkpoint to become stable. For example, if checkpoints 28 | are taken every 100 requests, k might be 200. 29 | */ 30 | type CheckPoint struct { 31 | Seq int64 `json:"sequence"` 32 | Digest string `json:"digest"` 33 | IsStable bool `json:"isStable"` 34 | ViewID int64 `json:"viewID"` 35 | CPMsg map[int64]*message.CheckPoint `json:"checks"` 36 | } 37 | 38 | func NewCheckPoint(sq, vi int64) *CheckPoint { 39 | cp := &CheckPoint{ 40 | Seq: sq, 41 | IsStable: false, 42 | ViewID: vi, 43 | CPMsg: make(map[int64]*message.CheckPoint), 44 | } 45 | return cp 46 | } 47 | 48 | func (s *StateEngine) ResetState(reply *message.Reply) { 49 | s.msgLogs[reply.SeqID].Stage = Idle 50 | s.LasExeSeq = reply.SeqID 51 | 52 | if s.CurSequence%CheckPointInterval == 0 { 53 | fmt.Printf("======>[ResetState]Need to create check points(%d)\n", s.CurSequence) 54 | go s.createCheckPoint(s.CurSequence) 55 | } 56 | s.cliRecord[reply.ClientID].saveReply(reply) 57 | } 58 | 59 | func (s *StateEngine) createCheckPoint(sequence int64) { 60 | msg := &message.CheckPoint{ 61 | SequenceID: sequence, 62 | NodeID: s.NodeID, 63 | ViewID: s.CurViewID, 64 | Digest: fmt.Sprintf("checkpoint message for [seq(%d)]", sequence), 65 | } 66 | 67 | cp := NewCheckPoint(sequence, s.CurViewID) 68 | cp.Digest = fmt.Sprintf("check point message<%d, %d>", s.NodeID, sequence) 69 | cp.CPMsg[s.NodeID] = msg 70 | s.checks[sequence] = cp 71 | 72 | fmt.Printf("======>[createCheckPoint] Broadcast check point message<%d, %d>\n", s.NodeID, sequence) 73 | consMsg := message.CreateConMsg(message.MTCommit, msg) 74 | err := s.p2pWire.BroadCast(consMsg) 75 | if err != nil { 76 | fmt.Println(err) 77 | } 78 | } 79 | 80 | func (s *StateEngine) checkingPoint(msg *message.CheckPoint) error { 81 | cp, ok := s.checks[msg.SequenceID] 82 | if !ok { 83 | cp = NewCheckPoint(msg.SequenceID, s.CurViewID) 84 | s.checks[msg.SequenceID] = cp 85 | } 86 | cp.CPMsg[msg.NodeID] = msg 87 | s.runCheckPoint(msg.SequenceID) 88 | return nil 89 | } 90 | 91 | func (s *StateEngine) runCheckPoint(seq int64) { 92 | cp, ok := s.checks[seq] 93 | if !ok { 94 | return 95 | 96 | } 97 | if len(cp.CPMsg) < 2*message.MaxFaultyNode+1 { 98 | fmt.Printf("======>[checkingPoint] message counter:[%d]\n", len(cp.CPMsg)) 99 | return 100 | } 101 | if cp.IsStable { 102 | fmt.Printf("======>[checkingPoint] Check Point for [%d] has confirmed\n", cp.Seq) 103 | return 104 | } 105 | 106 | fmt.Println("======>[checkingPoint] Start to clean the old message data......") 107 | cp.IsStable = true 108 | for id, log := range s.msgLogs { 109 | if id > cp.Seq { 110 | continue 111 | } 112 | log.PrePrepare = nil 113 | log.Commit = nil 114 | delete(s.msgLogs, id) 115 | fmt.Printf("======>[checkingPoint] Delete log message:CPseq=%d clientID=%s\n", id, log.clientID) 116 | } 117 | 118 | for id, cps := range s.checks { 119 | if id >= cp.Seq { 120 | continue 121 | } 122 | cps.CPMsg = nil 123 | delete(s.checks, id) 124 | fmt.Printf("======>[checkingPoint] Delete Checkpoint:seq=%d stable=%t\n", id, cps.IsStable) 125 | } 126 | 127 | s.MiniSeq = cp.Seq 128 | s.MaxSeq = s.MiniSeq + CheckPointK 129 | s.lastCP = cp 130 | fmt.Printf("======>[checkingPoint] Success in Checkpoint forwarding[(%d, %d)]......\n", s.MiniSeq, s.MaxSeq) 131 | } 132 | -------------------------------------------------------------------------------- /consensus/client.go: -------------------------------------------------------------------------------- 1 | package consensus 2 | 3 | import ( 4 | "github.com/didchain/PBFT/message" 5 | "time" 6 | ) 7 | 8 | type ClientRecord struct { 9 | LastReplyTime int64 `json:"lastReply"` 10 | Request map[int64]*message.Request `json:"Request"` 11 | Reply map[int64]*message.Reply `json:"Reply"` 12 | } 13 | 14 | func NewClientRecord() *ClientRecord { 15 | cr := &ClientRecord{ 16 | LastReplyTime: -1, 17 | Request: make(map[int64]*message.Request), 18 | Reply: make(map[int64]*message.Reply), 19 | } 20 | 21 | return cr 22 | } 23 | 24 | func (cr *ClientRecord) getRequest(seq int64) (*message.Request, bool) { 25 | r, ok := cr.Request[seq] 26 | return r, ok 27 | } 28 | 29 | func (cr *ClientRecord) saveRequest(r *message.Request) { 30 | cr.Request[r.SeqID] = r 31 | } 32 | 33 | func (cr *ClientRecord) getReply(time int64) (*message.Reply, bool) { 34 | r, ok := cr.Reply[time] 35 | return r, ok 36 | } 37 | 38 | func (cr *ClientRecord) saveReply(reply *message.Reply) { 39 | cr.Reply[reply.Timestamp] = reply 40 | cr.LastReplyTime = time.Now().Unix() 41 | } 42 | -------------------------------------------------------------------------------- /consensus/normallog.go: -------------------------------------------------------------------------------- 1 | package consensus 2 | 3 | import "github.com/didchain/PBFT/message" 4 | 5 | type NormalLog struct { 6 | clientID string `json:"clientID"` 7 | Stage Stage `json:"Stage"` 8 | PrePrepare *message.PrePrepare `json:"PrePrepare"` 9 | Prepare message.PrepareMsg `json:"Prepare"` 10 | Commit map[int64]*message.Commit `json:"Commit"` 11 | } 12 | 13 | func NewNormalLog() *NormalLog { 14 | nl := &NormalLog{ 15 | Stage: Idle, 16 | PrePrepare: nil, 17 | Prepare: make(message.PrepareMsg), 18 | Commit: make(map[int64]*message.Commit), 19 | } 20 | return nl 21 | } 22 | -------------------------------------------------------------------------------- /consensus/state.go: -------------------------------------------------------------------------------- 1 | package consensus 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "github.com/didchain/PBFT/message" 7 | "github.com/didchain/PBFT/p2pnetwork" 8 | "time" 9 | ) 10 | 11 | type Consensus interface { 12 | StartConsensus() 13 | PrePrepare() 14 | Prepare() 15 | Commit() 16 | } 17 | type Stage int 18 | 19 | const ( 20 | Idle Stage = iota 21 | PrePrepared 22 | Prepared 23 | Committed 24 | ) 25 | 26 | func (s Stage) String() string { 27 | switch s { 28 | case Idle: 29 | return "Idle" 30 | case PrePrepared: 31 | return "PrePrepared" 32 | case Prepared: 33 | return "Prepared" 34 | case Committed: 35 | return "Committed" 36 | } 37 | return "Unknown" 38 | } 39 | 40 | const StateTimerOut = 5 * time.Second 41 | const MaxStateMsgNO = 100 42 | const CheckPointInterval = 1 << 5 //32 43 | const CheckPointK = 2 * CheckPointInterval //64 44 | 45 | type RequestTimer struct { 46 | *time.Ticker 47 | IsOk bool 48 | } 49 | 50 | func newRequestTimer() *RequestTimer { 51 | tick := time.NewTicker(StateTimerOut) 52 | tick.Stop() 53 | return &RequestTimer{ 54 | Ticker: tick, 55 | IsOk: false, 56 | } 57 | } 58 | 59 | func (rt *RequestTimer) isRunning() bool { 60 | return rt.IsOk 61 | } 62 | 63 | func (rt *RequestTimer) tick() { 64 | if rt.IsOk { 65 | return 66 | } 67 | rt.Reset(StateTimerOut) 68 | rt.IsOk = true 69 | } 70 | 71 | func (rt *RequestTimer) tack() { 72 | rt.IsOk = false 73 | rt.Stop() 74 | } 75 | 76 | type EngineStatus int8 77 | 78 | const ( 79 | Syncing EngineStatus = iota 80 | Serving 81 | ViewChanging 82 | ) 83 | 84 | func (es EngineStatus) String() string { 85 | switch es { 86 | case Syncing: 87 | return "Syncing block chain......" 88 | case Serving: 89 | return "Server consensus......" 90 | case ViewChanging: 91 | return "Changing views......" 92 | } 93 | 94 | return "Unknown" 95 | } 96 | 97 | type StateEngine struct { 98 | NodeID int64 `json:"nodeID"` 99 | CurViewID int64 `json:"viewID"` 100 | CurSequence int64 `json:"curSeq"` 101 | LasExeSeq int64 `json:"lastExeSeq"` 102 | PrimaryID int64 `json:"primaryID"` 103 | nodeStatus EngineStatus 104 | 105 | Timer *RequestTimer 106 | p2pWire p2pnetwork.P2pNetwork 107 | MsgChan <-chan *message.ConMessage 108 | nodeChan chan<- *message.RequestRecord 109 | directReplyChan chan<- *message.Reply 110 | 111 | MiniSeq int64 `json:"miniSeq"` 112 | MaxSeq int64 `json:"maxSeq"` 113 | msgLogs map[int64]*NormalLog 114 | checks map[int64]*CheckPoint 115 | lastCP *CheckPoint 116 | cliRecord map[string]*ClientRecord 117 | sCache *VCCache 118 | } 119 | 120 | func InitConsensus(id int64, cChan chan<- *message.RequestRecord, rChan chan<- *message.Reply) *StateEngine { 121 | ch := make(chan *message.ConMessage, MaxStateMsgNO) 122 | p2p := p2pnetwork.NewSimpleP2pLib(id, ch) 123 | se := &StateEngine{ 124 | NodeID: id, 125 | CurViewID: 0, 126 | CurSequence: 0, 127 | LasExeSeq: 0, 128 | MiniSeq: 0, 129 | MaxSeq: 0 + CheckPointK, 130 | Timer: newRequestTimer(), 131 | p2pWire: p2p, 132 | MsgChan: ch, 133 | nodeChan: cChan, 134 | directReplyChan: rChan, 135 | msgLogs: make(map[int64]*NormalLog), 136 | checks: make(map[int64]*CheckPoint), 137 | cliRecord: make(map[string]*ClientRecord), 138 | sCache: NewVCCache(), 139 | } 140 | se.PrimaryID = se.CurViewID % message.TotalNodeNO 141 | return se 142 | } 143 | 144 | func (s *StateEngine) StartConsensus(sig chan interface{}) { 145 | s.nodeStatus = Serving 146 | //defer func() { 147 | // if r := recover(); r != nil { 148 | // sig <- r 149 | // } 150 | //}() 151 | 152 | for { 153 | select { 154 | case <-s.Timer.C: 155 | s.ViewChange() 156 | case conMsg := <-s.MsgChan: 157 | switch conMsg.Typ { 158 | case message.MTRequest, 159 | message.MTPrePrepare, 160 | message.MTPrepare, 161 | message.MTCommit: 162 | if s.nodeStatus != Serving { 163 | fmt.Println("node is not in service status now......") 164 | continue 165 | } 166 | if err := s.procConsensusMsg(conMsg); err != nil { 167 | fmt.Print(err) 168 | } 169 | case message.MTCheckpoint, 170 | message.MTViewChange, 171 | message.MTNewView: 172 | if err := s.procManageMsg(conMsg); err != nil { 173 | fmt.Print(err) 174 | } 175 | } 176 | } 177 | } 178 | } 179 | 180 | /* 181 | In the pre-Prepare phase, the primary assigns a sequence number, n, to the Request, multicasts a pre- Prepare 182 | message with piggybacked to all the backups, and appends the message to its log. The message has the 183 | form <, m> where v indicates the view in which the message is being sent, m is client’s Request 184 | message, and d ism’s digest. 185 | Requests are not included in pre-Prepare messages to keep them small. This is important because pre-Prepare 186 | messages are used as a proof that the Request was assigned sequence number in view in view changes. Additionally, 187 | it decouples the protocol to totally order requests from the protocol to transmit the Request to the replicas; 188 | allowing us to use a transport optimized for small messages for protocol messages and a transport optimized for 189 | large messages for large requests. 190 | */ 191 | 192 | func (s *StateEngine) checkClientRecord(request *message.Request) (*ClientRecord, error) { 193 | client, ok := s.cliRecord[request.ClientID] 194 | if !ok { 195 | client = NewClientRecord() 196 | s.cliRecord[request.ClientID] = client 197 | fmt.Printf("======>[Primary] New Client ID:%s\n", request.ClientID) 198 | } 199 | 200 | if request.TimeStamp < client.LastReplyTime { 201 | rp, ok := client.Reply[request.TimeStamp] 202 | if ok { 203 | fmt.Printf("======>[Primary] direct reply:%d\n", rp.SeqID) 204 | s.directReplyChan <- rp 205 | return nil, nil 206 | } 207 | return nil, fmt.Errorf("======>[Primary] it's a old operation Request") 208 | } 209 | return client, nil 210 | } 211 | 212 | func (s *StateEngine) getOrCreateLog(seq int64) *NormalLog { 213 | log, ok := s.msgLogs[seq] 214 | if !ok { 215 | log = NewNormalLog() 216 | s.msgLogs[seq] = log 217 | } 218 | return log 219 | } 220 | 221 | func (s *StateEngine) InspireConsensus(request *message.Request) error { 222 | s.CurSequence++ 223 | newSeq := s.CurSequence 224 | request.SeqID = newSeq 225 | client, err := s.checkClientRecord(request) 226 | if err != nil || client == nil { 227 | return err 228 | } 229 | client.saveRequest(request) 230 | cMsg := message.CreateConMsg(message.MTRequest, request) 231 | if err := s.p2pWire.BroadCast(cMsg); err != nil { 232 | return err 233 | } 234 | dig := message.Digest(request) 235 | ppMsg := &message.PrePrepare{ 236 | ViewID: s.CurViewID, 237 | SequenceID: newSeq, 238 | Digest: dig, 239 | } 240 | 241 | log := s.getOrCreateLog(newSeq) 242 | log.PrePrepare = ppMsg 243 | log.clientID = request.ClientID 244 | cMsg = message.CreateConMsg(message.MTPrePrepare, ppMsg) 245 | if err := s.p2pWire.BroadCast(cMsg); err != nil { 246 | return err 247 | } 248 | log.Stage = PrePrepared 249 | fmt.Printf("======>[Primary]Consensus broadcast message(%d)\n", newSeq) 250 | return nil 251 | } 252 | 253 | /* 254 | A backup accepts a pre-Prepare message provided: 255 | 1. the signatures in the Request and the pre-Prepare message are correct and d is the digest for m ; 256 | 2. it is in view v; 257 | 3. it has not accepted a pre-Prepare message for view v and sequence number n containing a different digest; 258 | 4. the sequence number in the pre-Prepare message is between a low water mark, h, and a high water mark H, 259 | 260 | The last condition prevents a faulty primary from exhausting the space of sequence numbers by selecting a very large one. 261 | 262 | If backup i accepts the <, m> message, it enters the Prepare phase by multicasting a 263 | message to all other replicas and adds both messages to its log. Otherwise, it does nothing. 264 | */ 265 | 266 | func (s *StateEngine) rawRequest(request *message.Request) (err error) { 267 | //TODO:: check signature of Request 268 | client, err := s.checkClientRecord(request) 269 | if err != nil || client == nil { 270 | return err 271 | } 272 | log := s.getOrCreateLog(request.SeqID) 273 | log.clientID = request.ClientID 274 | client.saveRequest(request) 275 | s.Timer.tick() 276 | return nil 277 | } 278 | 279 | /* 280 | 281 | Like PRE-PREPAREs, the PREPARE and COMMIT messages sent in the other phases also contain n and v. A replica 282 | only accepts one of these messages provided that it is in view v; that it can verify the authenticity of the message; 283 | and that n is between a low water mark h and a high water mark H. 284 | A backup i accepts the PRE-PREPARE message provided (in addition to the conditions above) it has not accepted 285 | a PRE-PREPARE for view v and sequence number n containing a different digest.If a backup i accepts the PRE-PREPARE and 286 | it has request m in its log, it enters the prepare phase by multicasting a PREPARE message with m’s digest to all other 287 | replicas; in addition, it adds both the PRE-PREPARE and PREPARE messages to its log. 288 | */ 289 | func (s *StateEngine) idle2PrePrepare(ppMsg *message.PrePrepare) (err error) { 290 | 291 | fmt.Printf("======>[idle2PrePrepare]Current sequence[%d]\n", ppMsg.SequenceID) 292 | 293 | //TODO:: check signature of of pre-Prepare message 294 | //TODO:: check digest of pre-Prepare message 295 | 296 | if ppMsg.ViewID != s.CurViewID { 297 | return fmt.Errorf("======>[idle2PrePrepare] invalid view id Msg=%d state=%d\n", ppMsg.ViewID, s.CurViewID) 298 | } 299 | 300 | if ppMsg.SequenceID > s.MaxSeq || ppMsg.SequenceID < s.MiniSeq { 301 | return fmt.Errorf("======>[idle2PrePrepare] sequence no[%d] invalid[%d~%d]\n", ppMsg.SequenceID, s.MiniSeq, s.MaxSeq) 302 | } 303 | 304 | log := s.getOrCreateLog(ppMsg.SequenceID) 305 | 306 | if log.Stage != Idle { 307 | return fmt.Errorf("invalid stage[current %s] when to prePrepared", log.Stage) 308 | } 309 | if log.PrePrepare != nil { 310 | if log.PrePrepare.Digest != ppMsg.Digest { 311 | return fmt.Errorf("pre-Prepare message in same v-n but not same digest") 312 | } else { 313 | fmt.Println("======>[idle2PrePrepare] duplicate pre-Prepare message") 314 | return 315 | } 316 | } 317 | prepare := &message.Prepare{ 318 | ViewID: s.CurViewID, 319 | SequenceID: ppMsg.SequenceID, 320 | Digest: ppMsg.Digest, 321 | NodeID: s.NodeID, 322 | } 323 | cMsg := message.CreateConMsg(message.MTPrepare, ppMsg) 324 | if err := s.p2pWire.BroadCast(cMsg); err != nil { 325 | return err 326 | } 327 | log.PrePrepare = ppMsg 328 | log.Prepare[s.NodeID] = prepare 329 | log.Stage = PrePrepared 330 | fmt.Printf("======>[idle2PrePrepare] Consensus status is [%s] seq=%d\n", log.Stage, ppMsg.SequenceID) 331 | return nil 332 | } 333 | 334 | /* 335 | A replica (including the primary) accepts Prepare messages and adds them to its log provided their signatures 336 | are correct, their view number equals the replica’s current view, and their sequence number is between h and H. 337 | 338 | We define the predicate prepared (m, v, n, i) to be true if and only if replica i has inserted in its log: 339 | 1. the Request m, a pre-Prepare for m in view v with sequence number n, 340 | 2. 2f prepares from different backups that match the pre-Prepare. 341 | 342 | The replicas verify whether the prepares match the pre-Prepare by checking that they have the same : 343 | 1. view, 344 | 2. sequence number, 345 | 3. and digest. 346 | */ 347 | 348 | func (s *StateEngine) prePrepare2Prepare(prepare *message.Prepare) (err error) { 349 | 350 | fmt.Printf("======>[prePrepare2Prepare]Current sequence[%d]\n", prepare.SequenceID) 351 | 352 | //TODO::signature check 353 | //fmt.Printf("Verify Prepare message digest:%s\n", Prepare.Digest) 354 | if prepare.ViewID != s.CurViewID { 355 | return fmt.Errorf("======>[prePrepare2Prepare]:=>invalid view id Msg=%d state=%d\n", prepare.ViewID, s.CurViewID) 356 | } 357 | 358 | if prepare.SequenceID > s.MaxSeq || prepare.SequenceID < s.MiniSeq { 359 | return fmt.Errorf("======>[prePrepare2Prepare]:=>sequence no[%d] invalid[%d~%d]\n", prepare.SequenceID, s.MiniSeq, s.MaxSeq) 360 | } 361 | 362 | log, ok := s.msgLogs[prepare.SequenceID] 363 | if !ok { 364 | return fmt.Errorf("======>[prePrepare2Prepare]:=>havn't got log for message(%d) yet", prepare.SequenceID) 365 | } 366 | if log.Stage != PrePrepared { 367 | return fmt.Errorf("======>[prePrepare2Prepare] current[seq=%d] state isn't PrePrepared:[%s]\n", prepare.SequenceID, log.Stage) 368 | } 369 | 370 | ppMsg := log.PrePrepare 371 | if ppMsg == nil { 372 | return fmt.Errorf("======>[prePrepare2Prepare]:=>havn't got pre-Prepare message(%d) yet", prepare.SequenceID) 373 | } 374 | 375 | if ppMsg.ViewID != prepare.ViewID || 376 | ppMsg.SequenceID != prepare.SequenceID || 377 | ppMsg.Digest != prepare.Digest { 378 | return fmt.Errorf("[Prepare]:=>not same with pre-Prepare message") 379 | } 380 | log.Prepare[prepare.NodeID] = prepare 381 | if len(log.Prepare) < 2*message.MaxFaultyNode { //not different replica, just simple no 382 | return nil 383 | } 384 | 385 | fmt.Printf("======>[prePrepare2Prepare] Consensus status is [%s] seq=%d\n", log.Stage, prepare.SequenceID) 386 | 387 | commit := &message.Commit{ 388 | ViewID: s.CurViewID, 389 | SequenceID: prepare.SequenceID, 390 | Digest: prepare.Digest, 391 | NodeID: s.NodeID, 392 | } 393 | cMsg := message.CreateConMsg(message.MTCommit, commit) 394 | if err := s.p2pWire.BroadCast(cMsg); err != nil { 395 | return err 396 | } 397 | log.Commit[s.NodeID] = commit 398 | log.Stage = Prepared 399 | return 400 | } 401 | 402 | /* 403 | Replica i multicasts a to the other replicas when prepared (m, v, n, i) become true. 404 | This starts the Commit phase. Replicas accept Commit messages and insert them in their log provided they are properly 405 | signed, the view number in the message is equal to the replica’s current view, and the sequence number is between h and H 406 | 407 | We define the committed and committed-local predicates as follows: committed(m, v, n) is true if and only 408 | if prepared(m, v, n, i) is true for all i in some set of f + 1 non-faulty replicas; and committed-local(m, v, n, i) is 409 | true if and only if prepared(m, v, n, i) is true and i has accepted 2f + 1 commits (possibly including its own) from 410 | different replicas that match the pre-Prepare for m; a Commit matches a pre-Prepare if they have the same view, sequence 411 | number, and digest. 412 | The Commit phase ensures the following invariant: if committed-local(m, v, n, i) is true for some non-faulty i 413 | then committed(m, v, n, i) is true. This invariant and the view-change protocol described in Section 4.4 ensure that 414 | non-faulty replicas agree on the sequence numbers of requests that Commit locally even if they Commit in different views 415 | at each replica. Furthermore, it ensures that any Request that commits locally at a non-faulty replica will Commit at 416 | f + 1 or more non-faulty replicas eventually. 417 | We do not rely on ordered message delivery, and therefore it is possible for a replica to Commit requests out 418 | of order. This does not matter since it keeps the pre- Prepare, Prepare, and Commit messages logged until the 419 | corresponding Request can be executed. 420 | */ 421 | 422 | func (s *StateEngine) prepare2Commit(commit *message.Commit) (err error) { 423 | fmt.Printf("======>[prepare2Commit] Current sequence[%d]\n", commit.SequenceID) 424 | 425 | //TODO:: Commit is properly signed 426 | //fmt.Printf("Verify Commit message digest:%s\n", Commit.Digest) 427 | if commit.ViewID != s.CurViewID { 428 | return fmt.Errorf("======>[prepare2Commit] invalid view id Msg=%d state=%d\n", commit.ViewID, s.CurViewID) 429 | } 430 | 431 | if commit.SequenceID > s.MaxSeq || commit.SequenceID < s.MiniSeq { 432 | return fmt.Errorf("======>[prepare2Commit] sequence no[%d] invalid[%d~%d]\n", 433 | commit.SequenceID, s.MiniSeq, s.MaxSeq) 434 | } 435 | 436 | log, ok := s.msgLogs[commit.SequenceID] 437 | if !ok { 438 | return fmt.Errorf("======>[prePrepare2Prepare]:=>havn't got log for message(%d) yet", commit.SequenceID) 439 | } 440 | if log.Stage != Prepared { 441 | return fmt.Errorf("======>[prePrepare2Prepare] current[seq=%d] state isn't PrePrepared:[%s]\n", commit.SequenceID, log.Stage) 442 | } 443 | 444 | ppMsg := log.PrePrepare 445 | if ppMsg == nil { 446 | return fmt.Errorf("======>[prePrepare2Prepare]:=>havn't got pre-Prepare message(%d) yet", commit.SequenceID) 447 | } 448 | 449 | if ppMsg.ViewID != commit.ViewID || 450 | ppMsg.SequenceID != commit.SequenceID || 451 | ppMsg.Digest != commit.Digest { 452 | return fmt.Errorf("[Prepare]:=>not same with pre-Prepare message") 453 | } 454 | log.Commit[commit.NodeID] = commit 455 | if len(log.Commit) < 2*message.MaxFaultyNode+1 { 456 | return nil 457 | } 458 | log.Stage = Committed 459 | s.Timer.tack() 460 | fmt.Printf("======>[prepare2Commit] Consensus status is [%s] seq=%d and timer stop\n", log.Stage, commit.SequenceID) 461 | 462 | //TODO::should execute request with smallest sequence no, current committed sequence may not be the smallest one. 463 | request, ok := s.cliRecord[log.clientID].Request[commit.SequenceID] 464 | if !ok { 465 | return fmt.Errorf("no raw request for such seq[%d]", commit.SequenceID) 466 | } 467 | exeParam := &message.RequestRecord{ 468 | Request: request, 469 | PrePrepare: ppMsg, 470 | } 471 | //TODO::Check the reply whose sequence is smaller than current sequence. 472 | s.nodeChan <- exeParam 473 | return 474 | } 475 | 476 | func (s *StateEngine) procConsensusMsg(msg *message.ConMessage) (err error) { 477 | s.Timer.Reset(StateTimerOut) 478 | 479 | fmt.Printf("\n======>[procConsensusMsg] Consesus message signature:(%s)\n", msg.Sig) 480 | 481 | switch msg.Typ { 482 | 483 | case message.MTRequest: 484 | request := &message.Request{} 485 | if err := json.Unmarshal(msg.Payload, request); err != nil { 486 | return fmt.Errorf("======>[procConsensusMsg] Invalid[%s] request message[%s]\n", err, msg) 487 | } 488 | return s.rawRequest(request) 489 | case message.MTPrePrepare: 490 | prePrepare := &message.PrePrepare{} 491 | if err := json.Unmarshal(msg.Payload, prePrepare); err != nil { 492 | return fmt.Errorf("======>[procConsensusMsg] Invalid[%s] pre-Prepare message[%s]\n", err, msg) 493 | } 494 | return s.idle2PrePrepare(prePrepare) 495 | 496 | case message.MTPrepare: 497 | prepare := &message.Prepare{} 498 | if err := json.Unmarshal(msg.Payload, prepare); err != nil { 499 | return fmt.Errorf("======>[procConsensusMsg]invalid[%s] Prepare message[%s]\n", err, msg) 500 | } 501 | return s.prePrepare2Prepare(prepare) 502 | 503 | case message.MTCommit: 504 | commit := &message.Commit{} 505 | if err := json.Unmarshal(msg.Payload, commit); err != nil { 506 | return fmt.Errorf("======>[procConsensusMsg] invalid[%s] Commit message[%s]\n", err, msg) 507 | } 508 | return s.prepare2Commit(commit) 509 | } 510 | return 511 | } 512 | 513 | func (s *StateEngine) procManageMsg(msg *message.ConMessage) (err error) { 514 | switch msg.Typ { 515 | 516 | case message.MTCheckpoint: 517 | checkpoint := &message.CheckPoint{} 518 | if err := json.Unmarshal(msg.Payload, checkpoint); err != nil { 519 | return fmt.Errorf("======>[procConsensusMsg] invalid[%s]checkpoint message[%s]\n", err, msg) 520 | } 521 | return s.checkingPoint(checkpoint) 522 | 523 | case message.MTViewChange: 524 | vc := &message.ViewChange{} 525 | if err := json.Unmarshal(msg.Payload, vc); err != nil { 526 | return fmt.Errorf("======>[procConsensusMsg] invalid[%s]ViewChange message[%s]\n", err, msg) 527 | } 528 | return s.procViewChange(vc) 529 | 530 | case message.MTNewView: 531 | vc := &message.NewView{} 532 | if err := json.Unmarshal(msg.Payload, vc); err != nil { 533 | return fmt.Errorf("======>[procConsensusMsg] invalid[%s] didiViewChange message[%s]\n", err, msg) 534 | } 535 | return s.didChangeView(vc) 536 | } 537 | return nil 538 | } 539 | -------------------------------------------------------------------------------- /consensus/viewchange.go: -------------------------------------------------------------------------------- 1 | package consensus 2 | 3 | import ( 4 | "fmt" 5 | "github.com/didchain/PBFT/message" 6 | ) 7 | 8 | type VCCache struct { 9 | vcMsg message.VMessage 10 | nvMsg map[int64]*message.NewView 11 | } 12 | 13 | func NewVCCache() *VCCache { 14 | return &VCCache{ 15 | vcMsg: make(message.VMessage), 16 | nvMsg: make(map[int64]*message.NewView), 17 | } 18 | } 19 | 20 | func (vcc *VCCache) pushVC(vc *message.ViewChange) { 21 | vcc.vcMsg[vc.NodeID] = vc 22 | } 23 | 24 | func (vcc *VCCache) hasNewViewYet(vid int64) bool { 25 | if _, ok := vcc.nvMsg[vid]; ok { 26 | return true 27 | } 28 | return false 29 | } 30 | 31 | func (vcc *VCCache) addNewView(nv *message.NewView) { 32 | vcc.nvMsg[nv.NewViewID] = nv 33 | } 34 | 35 | /* 36 | The view-change protocol provides Aliveness by allowing the system to make progress when the primary fails. View 37 | changes are triggered by timeouts that prevent backups from waiting indefinitely for requests to execute. A backup is 38 | waiting for a Request if it received a valid Request and has not executed it. A backup starts a timer when it receives a 39 | Request and the timer is not already running. It stops the timer when it is no longer waiting to execute the Request, 40 | but restarts it if at that point it is waiting to execute some other Request. 41 | 42 | If the timer of backup i expires in view , the backup starts a view change to move the system to view v + 1. 43 | It stops accepting messages (other than checkpoint, view-change, and new-view messages) and multicasts a 44 | message to all replicas. Here n is the sequence number of the last stable 45 | checkpoint s known to i, C is a set of 2f + 1 valid checkpoint messages proving the correctness of s and P is a set 46 | containing a set Pm for each Request m that prepared at i with a sequence number higher than n. Each set Pm contains a 47 | valid pre-Prepare message(without the corresponding client message) and 2f matching, valid Prepare message signed by 48 | different backups with same view, sequence number, and the digest of m. 49 | */ 50 | 51 | /* 52 | Data Structures 53 | Replicas record information about what happened in earlier views. This information is maintained in two sets, P 54 | and Q. These sets only contain information for sequence numbers between the current low and high water marks in the log. 55 | The sets allow the view change protocol to work properly even when more than one view change occurs before the system is 56 | able to continue normal operation; the sets are empty while the system is running normally. Replicas also store the 57 | requests corresponding to entries in these sets. 58 | P at replica i stores information about requests that have prepared at i in previous views. Its entries are 59 | tuples ⟨n, d , v⟩, meaning that i collected a prepared certificate for a request with digest d with number n in view v 60 | and no request prepared at i in a later view with the same number. 61 | Q stores information about requests that have pre-prepared at i in previous views (i.e., requests for which i 62 | has sent a PRE-PREPARE or PREPARE message). Its entries are tuples ⟨n, d , v⟩, meaning that i pre-prepared a request 63 | with digest d with number n in view v and that request did not pre-prepare at i in a later view with the same number. 64 | */ 65 | 66 | func (s *StateEngine) computePMsg() map[int64]*message.PTuple { 67 | P := make(map[int64]*message.PTuple) 68 | for seq := s.MiniSeq; seq < s.MaxSeq; seq++ { 69 | log, ok := s.msgLogs[seq] 70 | if !ok || log.Stage < Prepared { 71 | continue 72 | } 73 | 74 | tuple := &message.PTuple{ 75 | PPMsg: log.PrePrepare, 76 | PMsg: log.Prepare, 77 | } 78 | P[seq] = tuple 79 | } 80 | 81 | return P 82 | } 83 | 84 | /* 85 | View-Change Messages 86 | When a backup i suspects the primary for view v is faulty, it enters view v + 1 and multicasts a 87 | ⟨VIEW-CHANGE, v + 1, h, C, P, Q, i⟩αi message to all replicas. Here h is the sequence number of the latest stable 88 | checkpoint known to i, C is a set of pairs with the sequence number and digest of each checkpoint stored at i, 89 | and P and Q are the sets described above. These sets are updated before sending the VIEW-CHANGE message using 90 | the information in the log, as explained in Figure 3. Once the VIEW-CHANGE message has been sent, i removes PRE-PREPARE, 91 | PREPARE, and COMMIT messages from its log. The number of tuples in Q may grow without bound if the algorithm changes 92 | views repeatedly without making progress. In Castro [2001], we describe a modification to the algorithm that bounds 93 | the size of the Q by a constant. It is interesting to note that VIEW-CHANGE messages do not include PRE-PREPARE, PREPARE, 94 | or CHECKPOINT messages. 95 | */ 96 | func (s *StateEngine) ViewChange() { 97 | 98 | fmt.Printf("======>[ViewChange] (%d, %d).....\n", s.CurViewID, s.lastCP.Seq) 99 | s.nodeStatus = ViewChanging 100 | s.Timer.tack() 101 | 102 | pMsg := s.computePMsg() 103 | 104 | vc := &message.ViewChange{ 105 | NewViewID: s.CurViewID + 1, 106 | LastCPSeq: s.lastCP.Seq, 107 | NodeID: s.NodeID, 108 | CMsg: s.lastCP.CPMsg, 109 | PMsg: pMsg, 110 | } 111 | 112 | nextPrimaryID := vc.NewViewID % message.TotalNodeNO 113 | if s.NodeID == nextPrimaryID { 114 | s.sCache.pushVC(vc) //[vc.NodeID] = vc 115 | } 116 | 117 | consMsg := message.CreateConMsg(message.MTViewChange, vc) 118 | if err := s.p2pWire.BroadCast(consMsg); err != nil { 119 | fmt.Println(err) 120 | return 121 | } 122 | s.CurViewID++ 123 | s.msgLogs = make(map[int64]*NormalLog) 124 | } 125 | 126 | /* 127 | View-Change-Ack Messages 128 | Replicas collect VIEW-CHANGE messages for v+1 and send acknowledgments for them to v + 1’s primary, p. Replicas 129 | only accept these VIEW-CHANGE messages if all the information in their P and Q components is for view numbers less than 130 | or equal to v. The acknowledgments have the form ⟨VIEW-CHANGE-ACK,v+1,i, j,d⟩μip, where i is the identifier of the 131 | sender, d is the digest of the VIEW-CHANGE message being acknowledged, and j is the replica that sent that VIEW-CHANGE 132 | message. These acknowledgments allow the primary to prove authenticity of VIEW-CHANGE messages sent by faulty replicas. 133 | */ 134 | 135 | type Set map[interface{}]bool 136 | 137 | func (s Set) put(key interface{}) { 138 | s[key] = true 139 | } 140 | func (s *StateEngine) checkViewChange(vc *message.ViewChange) error { 141 | if s.CurViewID > vc.NewViewID { 142 | return fmt.Errorf("it's[%d] not for me[%d] view change", vc.NewViewID, s.CurViewID) 143 | } 144 | if len(vc.CMsg) <= message.MaxFaultyNode { 145 | return fmt.Errorf("view message checking C message failed") 146 | } 147 | var counter = make(map[int64]Set) 148 | for id, cp := range vc.CMsg { 149 | if cp.ViewID >= vc.NewViewID { 150 | continue 151 | } 152 | 153 | if cp.SequenceID != vc.LastCPSeq { 154 | return fmt.Errorf("view change message C msg's n[]%d is different from vc's"+ 155 | " h[%d]", cp.SequenceID, vc.LastCPSeq) 156 | } 157 | 158 | //TODO:: digest test 159 | //if cp.Digest != message.Digest(vc.LastCPSeq){ 160 | // 161 | //} 162 | 163 | if counter[cp.ViewID] == nil { 164 | counter[cp.ViewID] = make(Set) 165 | } 166 | 167 | counter[cp.ViewID].put(id) 168 | } 169 | 170 | CMsgIsOK := false 171 | for vid, set := range counter { 172 | if len(set) > message.MaxFaultyNode { 173 | fmt.Printf("view change check C message success[%d]:\n", vid) 174 | CMsgIsOK = true 175 | break 176 | } 177 | } 178 | if !CMsgIsOK { 179 | return fmt.Errorf("no valid C message in view change msg") 180 | } 181 | 182 | counter = make(map[int64]Set) 183 | for seq, pt := range vc.PMsg { 184 | 185 | ppView := pt.PPMsg.ViewID 186 | //prePrimaryID := ppView % message.TotalNodeNO 187 | 188 | if seq <= vc.LastCPSeq || seq > vc.LastCPSeq+CheckPointK { 189 | return fmt.Errorf("view change message checking P message faild pre-prepare n=%d,"+ 190 | " checkpoint h=%d", seq, vc.LastCPSeq) 191 | } 192 | if ppView >= vc.NewViewID { 193 | return fmt.Errorf("view change message checking P message faild pre-prepare view=%d,"+ 194 | " new view id=%d", pt.PPMsg.ViewID, vc.NewViewID) 195 | } 196 | 197 | for nid, prepare := range pt.PMsg { 198 | if ppView != prepare.ViewID { 199 | return fmt.Errorf("view change message checking view id[%d] in pre-prepare is not "+ 200 | "same as prepare's[%d]", ppView, prepare.ViewID) 201 | } 202 | if seq != prepare.SequenceID { 203 | return fmt.Errorf("view change message checking seq id[%d] in pre-prepare"+ 204 | "is different from prepare's[%d]", seq, prepare.SequenceID) 205 | } 206 | counter[ppView].put(nid) 207 | } 208 | } 209 | 210 | PMsgIsOk := false 211 | for vid, set := range counter { 212 | if len(set) >= 2*message.MaxFaultyNode { 213 | fmt.Printf("view change check P message success[%d]:\n", vid) 214 | PMsgIsOk = true 215 | break 216 | } 217 | } 218 | if !PMsgIsOk { 219 | return fmt.Errorf("view change check p message failed") 220 | } 221 | 222 | return nil 223 | } 224 | 225 | func (s *StateEngine) procViewChange(vc *message.ViewChange) error { 226 | nextPrimaryID := vc.NewViewID % message.TotalNodeNO 227 | if s.NodeID != nextPrimaryID { 228 | fmt.Printf("im[%d] not the new[%d] primary node\n", s.NodeID, nextPrimaryID) 229 | return nil 230 | } 231 | if err := s.checkViewChange(vc); err != nil { 232 | return err 233 | } 234 | 235 | s.sCache.pushVC(vc) 236 | if len(s.sCache.vcMsg) < message.MaxFaultyNode*2 { 237 | return nil 238 | } 239 | if s.sCache.hasNewViewYet(vc.NewViewID) { 240 | fmt.Printf("view change[%d] is in processing......\n", vc.NewViewID) 241 | return nil 242 | } 243 | 244 | return s.createNewViewMsg(vc.NewViewID) 245 | } 246 | 247 | /* 248 | New-View Message Construction 249 | The new primary p collects VIEW-CHANGE and VIEW-CHANGE-ACK messages (including messages from itself). It stores 250 | VIEW-CHANGE messages in a set S. It adds a VIEW-CHANGE message received from replica i to S after receiving 2 f − 1 251 | VIEW-CHANGE-ACKs for i’s VIEW-CHANGE message from other replicas. These VIEW-CHANGE-ACK messages together with the 252 | VIEW-CHANGE message it received and the VIEW-CHANGE-ACK it could have sent form a quorum certificate. We call it the 253 | view-change certificate. Each entry in S is for a different replica. 254 | The new primary uses the information in S and the decision procedure sketched in Figure 4 to choose a checkpoint 255 | and a set of requests. This procedure runs each time the primary receives new information, for example, when it adds a 256 | new message to S. We use the notation m.x to indicate component x of message m where x is the name we used for the 257 | component when defining the format for m’s message type. 258 | The primary starts by selecting the checkpoint that is going to be the starting state for request processing in 259 | the new view. It picks the checkpoint with the highest number h from the set of checkpoints that are known to be correct 260 | (because they have a weak certificate) and that have numbers higher than the low water mark in the log of at least f + 1 261 | non-faulty replicas. The last condition is necessary for live-ness; it ensures that the ordering information for requests 262 | that committed with numbers higher than h is still available. 263 | Next, the primary selects a request to pre-prepare in the new view for each sequence number n between h and 264 | h + L (where L is the size of the log). If a request m committed in a previous view, the primary must select m. If such 265 | a request exists, it is guaranteed to be the only one that satisfies conditions A1 and A2. Condition A1 ensures that the 266 | primary selects the request that some replica in a quorum claims to have prepared in the latest view v, and A2 ensures 267 | that the request could prepare in view v because it was pre-prepared by at least one correct replica in v or a later view. 268 | If there is a quorum of replicas that did not prepare any request with sequence number n (condition B), no request 269 | committed with number n. There- fore, the primary selects a special null request that goes through the protocol as a 270 | regular request but whose execution is a no-op. (Paxos [Lamport 1989] used a similar technique to fill in gaps.) 271 | The decision procedure ends when the primary has selected a request for each number. This may require waiting 272 | for more than n− f messages but a primary is always able to complete the decision procedure once it receives all 273 | VIEW-CHANGE messages sent by non-faulty replicas for its view. After deciding, the primary multicasts a NEW-VIEW message 274 | to the other replicas with its decision: ⟨NEW-VIEW, v + 1, V , X ⟩α p . Here, V contains a pair for each entry in S 275 | consisting of the identifier of the sending replica and the digest of its VIEW-CHANGE message, and X identifies the 276 | checkpoint and request values selected. The VIEW-CHANGEs in V are the new-view certificate. 277 | */ 278 | 279 | func (s *StateEngine) GetON(newVID int64) (int64, int64, message.OMessage, message.OMessage, *message.ViewChange) { 280 | mergeP := make(map[int64]*message.PTuple) 281 | var maxNinV int64 = 0 282 | var maxNinO int64 = 0 283 | 284 | var cpVC *message.ViewChange = nil 285 | for _, vc := range s.sCache.vcMsg { 286 | if vc.LastCPSeq > maxNinV { 287 | maxNinV = vc.LastCPSeq 288 | cpVC = vc 289 | } 290 | for seq, pMsg := range vc.PMsg { 291 | if _, ok := mergeP[seq]; ok { 292 | continue 293 | } 294 | mergeP[seq] = pMsg 295 | if seq > maxNinO { 296 | maxNinO = seq 297 | } 298 | } 299 | } 300 | 301 | O := make(message.OMessage) 302 | N := make(message.OMessage) 303 | for i := maxNinV + 1; i <= maxNinO; i++ { 304 | pt, ok := mergeP[i] 305 | if ok { 306 | O[i] = pt.PPMsg 307 | O[i].ViewID = newVID 308 | } else { 309 | N[i] = &message.PrePrepare{ 310 | ViewID: newVID, 311 | SequenceID: i, 312 | Digest: nil, 313 | } 314 | } 315 | } 316 | 317 | return maxNinV, maxNinO, O, N, cpVC 318 | } 319 | 320 | func (s *StateEngine) createNewViewMsg(newVID int64) error { 321 | 322 | s.CurViewID = newVID 323 | newCP, newSeq, o, n, cpVC := s.GetON(newVID) 324 | nv := &message.NewView{ 325 | NewViewID: s.CurViewID, 326 | VMsg: s.sCache.vcMsg, 327 | OMsg: o, 328 | NMsg: n, 329 | } 330 | 331 | s.sCache.addNewView(nv) 332 | 333 | s.CurSequence = newSeq 334 | 335 | msg := message.CreateConMsg(message.MTNewView, nv) 336 | if err := s.p2pWire.BroadCast(msg); err != nil { 337 | return err 338 | } 339 | s.updateStateNV(newCP, cpVC) 340 | s.cleanRequest() 341 | return nil 342 | } 343 | 344 | /* 345 | New-View Message Processing 346 | The primary updates its state to reflect the information in the NEW-VIEW mes- sage. It obtains any requests 347 | in X that it is missing and if it does not have the checkpoint with sequence number h, it also initiates the protocol 348 | to fetch the missing state (see Section 6.2.2). When it has all requests in X and the check- point with sequence number 349 | h is stable, it records in its log that the requests are pre-prepared in view v + 1. 350 | The backups for view v + 1 collect messages until they have a correct NEW-VIEW message and a correct matching 351 | VIEW-CHANGE message for each pair in V. If a backup did not receive one of the VIEW-CHANGE messages for some replica 352 | with a pair in V, the primary alone may be unable to prove that the message it received is authentic because it is 353 | not signed. The use of VIEW-CHANGE-ACK messages solves this problem. Since the primary only includes a VIEW-CHANGE 354 | message in S after obtaining a matching view-change certificate, at least f + 1 non-faulty replicas can vouch for the 355 | authenticity of every VIEW-CHANGE message whose di- gest is in V. Therefore, if the original sender of a VIEW-CHANGE is 356 | uncooperative, the primary retransmits that sender’s VIEW-CHANGE message and the non-faulty backups retransmit their 357 | VIEW-CHANGE-ACKs. A backup can accept a VIEW-CHANGE message whose authenticator is incorrect if it receives f 358 | VIEW-CHANGE-ACKs that match the digest and identifier in V. 359 | After obtaining the NEW-VIEW message and the matching VIEW-CHANGE mes- sages, the backups check if these 360 | messages support the decisions reported by the primary by carrying out the decision procedure in Figure 4. If they do 361 | not, the replicas move immediately to view v + 2. Otherwise, they modify their state to account for the new information 362 | in a way similar to the primary. The only difference is that they multicast a PREPARE message for v + 1 for each request 363 | they mark as pre-prepared. Thereafter, normal case operation resumes. 364 | */ 365 | 366 | func (s *StateEngine) updateStateNV(maxNV int64, vc *message.ViewChange) { 367 | 368 | if maxNV > s.lastCP.Seq { 369 | cp := NewCheckPoint(maxNV, s.CurViewID) 370 | cp.CPMsg = vc.CMsg 371 | s.checks[maxNV] = cp 372 | s.runCheckPoint(maxNV) 373 | 374 | s.createCheckPoint(maxNV) 375 | } 376 | 377 | if maxNV > s.LasExeSeq { 378 | //TODO:: last reply last reply time 379 | s.LasExeSeq = maxNV 380 | } 381 | 382 | return 383 | } 384 | 385 | func (s *StateEngine) cleanRequest() { 386 | for cid, client := range s.cliRecord { 387 | for seq, req := range client.Request { 388 | if req.TimeStamp < client.LastReplyTime { 389 | delete(client.Request, seq) 390 | fmt.Printf("cleaning request[%d] when view changed for client[%s]\n", seq, cid) 391 | } 392 | } 393 | } 394 | return 395 | } 396 | 397 | func (s *StateEngine) didChangeView(nv *message.NewView) error { 398 | 399 | newVID := nv.NewViewID 400 | s.sCache.vcMsg = nv.VMsg 401 | newCP, newSeq, O, N, cpVC := s.GetON(newVID) 402 | if !O.EQ(nv.OMsg) { 403 | return fmt.Errorf("new view checking O message faliled") 404 | } 405 | if !N.EQ(nv.NMsg) { 406 | return fmt.Errorf("new view checking N message faliled") 407 | } 408 | 409 | for _, ppMsg := range O { 410 | if e := s.idle2PrePrepare(ppMsg); e != nil { 411 | return e 412 | } 413 | } 414 | 415 | for _, ppMsg := range N { 416 | if e := s.idle2PrePrepare(ppMsg); e != nil { 417 | return e 418 | } 419 | } 420 | 421 | s.sCache.addNewView(nv) 422 | s.CurSequence = newSeq 423 | s.updateStateNV(newCP, cpVC) 424 | s.cleanRequest() 425 | return nil 426 | } 427 | -------------------------------------------------------------------------------- /correct-new-view.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didchain/pbft/0efea2d062efac3631cf3babc1773c361729eb69/correct-new-view.jpg -------------------------------------------------------------------------------- /correct-view-cahnge.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didchain/pbft/0efea2d062efac3631cf3babc1773c361729eb69/correct-view-cahnge.jpg -------------------------------------------------------------------------------- /garbage_collection.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didchain/pbft/0efea2d062efac3631cf3babc1773c361729eb69/garbage_collection.jpg -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "github.com/didchain/PBFT/node" 6 | "os" 7 | "os/signal" 8 | "strconv" 9 | "syscall" 10 | ) 11 | 12 | func main() { 13 | if len(os.Args) < 2 { 14 | panic("usage: input id") 15 | } 16 | 17 | id, _ := strconv.Atoi(os.Args[1]) 18 | node := node.NewNode(int64(id)) 19 | go node.Run() 20 | 21 | sigCh := make(chan os.Signal, 1) 22 | 23 | signal.Notify(sigCh, 24 | syscall.SIGHUP, 25 | syscall.SIGINT, 26 | syscall.SIGTERM, 27 | syscall.SIGQUIT) 28 | 29 | pid := strconv.Itoa(os.Getpid()) 30 | 31 | fmt.Printf("\n===>PBFT Demo PID:%s\n", pid) 32 | fmt.Println() 33 | fmt.Println() 34 | fmt.Println("==============================================>") 35 | fmt.Println("* *") 36 | fmt.Println("* Practical Byzantine Fault Tolerance *") 37 | fmt.Println("* *") 38 | fmt.Println("<==============================================") 39 | fmt.Println() 40 | fmt.Println() 41 | sig := <-sigCh 42 | fmt.Printf("Finish by signal:===>[%s]\n", sig.String()) 43 | } 44 | -------------------------------------------------------------------------------- /message/concensus_msg.go: -------------------------------------------------------------------------------- 1 | package message 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | type ConMessage struct { 9 | Typ MType `json:"type"` 10 | Sig string `json:"sig"` 11 | From string `json:"from"` 12 | Payload []byte `json:"payload"` 13 | } 14 | 15 | func (cm *ConMessage) String() string { 16 | return fmt.Sprintf("\n======Consensus Messagetype======"+ 17 | "\ntype:%40s"+ 18 | "\nsig:%40s"+ 19 | "\npayload:%d"+ 20 | "\n<------------------>", 21 | cm.Typ.String(), 22 | cm.Sig, 23 | len(cm.Payload)) 24 | } 25 | 26 | func (cm *ConMessage) Verify() bool { 27 | //hash := HASH(cm.Payload) 28 | //return cm.From == Revert(hash, cm.Sig) 29 | return true 30 | } 31 | 32 | func CreateConMsg(t MType, msg interface{}) *ConMessage { 33 | data, e := json.Marshal(msg) 34 | if e != nil { 35 | return nil 36 | } 37 | 38 | sig := fmt.Sprintf("consensus message[%s]", t) 39 | consMsg := &ConMessage{ 40 | Typ: t, 41 | Sig: sig, 42 | Payload: data, 43 | } 44 | return consMsg 45 | } 46 | 47 | type RequestRecord struct { 48 | *PrePrepare 49 | *Request 50 | } 51 | 52 | type PrePrepare struct { 53 | ViewID int64 `json:"viewID"` 54 | SequenceID int64 `json:"sequenceID"` 55 | Digest string `json:"digest"` 56 | } 57 | 58 | type PrepareMsg map[int64]*Prepare 59 | type Prepare struct { 60 | ViewID int64 `json:"viewID"` 61 | SequenceID int64 `json:"sequenceID"` 62 | Digest string `json:"digest"` 63 | NodeID int64 `json:"nodeID"` 64 | } 65 | 66 | type Commit struct { 67 | ViewID int64 `json:"viewID"` 68 | SequenceID int64 `json:"sequenceID"` 69 | Digest string `json:"digest"` 70 | NodeID int64 `json:"nodeID"` 71 | } 72 | 73 | type CheckPoint struct { 74 | SequenceID int64 `json:"sequenceID"` 75 | Digest string `json:"digest"` 76 | ViewID int64 `json:"viewID"` 77 | NodeID int64 `json:"nodeID"` 78 | } 79 | type PTuple struct { 80 | PPMsg *PrePrepare `json:"pre-prepare"` 81 | PMsg PrepareMsg `json:"prepare"` 82 | } 83 | 84 | type ViewChange struct { 85 | NewViewID int64 `json:"newViewID"` 86 | LastCPSeq int64 `json:"lastCPSeq"` 87 | NodeID int64 `json:"nodeID"` 88 | CMsg map[int64]*CheckPoint `json:"cMsg"` 89 | PMsg map[int64]*PTuple `json:"pMsg"` 90 | } 91 | 92 | func (vc *ViewChange) Digest() string { 93 | return fmt.Sprintf("this is digest for[%d-%d]", vc.NewViewID, vc.LastCPSeq) 94 | } 95 | 96 | type OMessage map[int64]*PrePrepare 97 | 98 | func (m OMessage) EQ(msg OMessage) bool { 99 | //return HASH(m) == HASH(msg) 100 | return true 101 | } 102 | 103 | type VMessage map[int64]*ViewChange 104 | type NewView struct { 105 | NewViewID int64 `json:"newViewID"` 106 | VMsg VMessage `json:"vMSG"` 107 | OMsg OMessage `json:"oMSG"` 108 | NMsg OMessage `json:"nMSG"` 109 | } 110 | -------------------------------------------------------------------------------- /message/service_msg.go: -------------------------------------------------------------------------------- 1 | package message 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | type MType int16 8 | 9 | const ( 10 | MTPrePrepare MType = iota 11 | MTRequest 12 | MTPrepare 13 | MTCommit 14 | MTCheckpoint 15 | MTViewChange 16 | MTNewView 17 | ) 18 | const MaxFaultyNode = 1 19 | const TotalNodeNO = 3*MaxFaultyNode + 1 20 | 21 | func Digest(v interface{}) string { 22 | return "0x111111" 23 | } 24 | 25 | func PortByID(id int64) int { 26 | return 30000 + int(id) 27 | } 28 | 29 | func (mt MType) String() string { 30 | switch mt { 31 | case MTPrePrepare: 32 | return "PrePrepare" 33 | 34 | case MTPrepare: 35 | return "Prepare" 36 | 37 | case MTCommit: 38 | return "Commit" 39 | 40 | case MTCheckpoint: 41 | return "Checkpoint" 42 | } 43 | return "Unknown" 44 | } 45 | 46 | type Request struct { 47 | SeqID int64 `json:"sequenceID"` 48 | TimeStamp int64 `json:"timestamp"` 49 | ClientID string `json:"clientID"` 50 | Operation string `json:"operation"` 51 | } 52 | 53 | func (r *Request) String() string { 54 | return fmt.Sprintf("\n clientID:%20s"+ 55 | "\n time:%d"+ 56 | "\n operation:%s", 57 | r.ClientID, 58 | r.TimeStamp, 59 | r.Operation) 60 | } 61 | 62 | type Reply struct { 63 | SeqID int64 `json:"sequenceID"` 64 | ViewID int64 `json:"viewID"` 65 | Timestamp int64 `json:"timestamp"` 66 | ClientID string `json:"clientID"` 67 | NodeID int64 `json:"nodeID"` 68 | Result string `json:"result"` 69 | } 70 | -------------------------------------------------------------------------------- /new_view.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didchain/pbft/0efea2d062efac3631cf3babc1773c361729eb69/new_view.jpg -------------------------------------------------------------------------------- /node/node.go: -------------------------------------------------------------------------------- 1 | package node 2 | 3 | import ( 4 | "fmt" 5 | "github.com/didchain/PBFT/consensus" 6 | "github.com/didchain/PBFT/message" 7 | "github.com/didchain/PBFT/service" 8 | ) 9 | 10 | const MaxMsgNO = 100 11 | 12 | type Node struct { 13 | NodeID int64 14 | signal chan interface{} 15 | srvChan chan interface{} 16 | conChan <-chan *message.RequestRecord 17 | directReplyChan <-chan *message.Reply 18 | waitQueue []*message.Request 19 | consensus *consensus.StateEngine 20 | service *service.Service 21 | } 22 | 23 | func NewNode(id int64) *Node { 24 | 25 | srvChan := make(chan interface{}, MaxMsgNO) 26 | conChan := make(chan *message.RequestRecord, MaxMsgNO) 27 | rChan := make(chan *message.Reply, MaxMsgNO) 28 | 29 | c := consensus.InitConsensus(id, conChan, rChan) 30 | sr := service.InitService(message.PortByID(id), srvChan) 31 | 32 | n := &Node{ 33 | NodeID: id, 34 | consensus: c, 35 | service: sr, 36 | srvChan: srvChan, 37 | waitQueue: make([]*message.Request, 0), 38 | signal: make(chan interface{}), 39 | conChan: conChan, 40 | directReplyChan: rChan, 41 | } 42 | return n 43 | } 44 | 45 | func (n *Node) Run() { 46 | 47 | fmt.Printf("\nConsensus node[%d] start primary[%t]......\n", n.NodeID, n.NodeID == n.consensus.PrimaryID) 48 | 49 | go n.consensus.StartConsensus(n.signal) 50 | go n.service.WaitRequest(n.signal) 51 | go n.Dispatch() 52 | s := <-n.signal 53 | fmt.Printf("Node[%d] exit because of:%s", n.NodeID, s) 54 | } 55 | 56 | func (n *Node) Dispatch() { 57 | for { 58 | select { 59 | case srvMsg := <-n.srvChan: 60 | opMsg, ok := srvMsg.(*message.Request) 61 | if !ok { 62 | return 63 | } 64 | 65 | if err := n.consensus.InspireConsensus(opMsg); err != nil { 66 | fmt.Printf("consesus layer err:%s", err) 67 | n.waitQueue = append(n.waitQueue, opMsg) 68 | } 69 | 70 | case record := <-n.conChan: 71 | reply, err := n.service.Execute(record.ViewID, n.NodeID, record.SequenceID, record.Request) 72 | if err != nil { 73 | fmt.Printf("service layer err:%s", err) 74 | continue 75 | } 76 | n.consensus.ResetState(reply) 77 | case reply := <-n.directReplyChan: 78 | if err := n.service.DirectReply(reply); err != nil { 79 | fmt.Println(err) 80 | continue 81 | } 82 | } 83 | } 84 | } 85 | -------------------------------------------------------------------------------- /normal_case_operation.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didchain/pbft/0efea2d062efac3631cf3babc1773c361729eb69/normal_case_operation.jpg -------------------------------------------------------------------------------- /overview.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didchain/pbft/0efea2d062efac3631cf3babc1773c361729eb69/overview.jpg -------------------------------------------------------------------------------- /p2pnetwork/p2p.go: -------------------------------------------------------------------------------- 1 | package p2pnetwork 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "github.com/didchain/PBFT/message" 7 | "io" 8 | "net" 9 | "time" 10 | ) 11 | 12 | var nodeList = []int64{0, 1, 2, 3} 13 | 14 | type P2pNetwork interface { 15 | BroadCast(v interface{}) error 16 | SendToNode(nodeID int64, v interface{}) error 17 | } 18 | 19 | type SimpleP2p struct { 20 | SrvBub *net.TCPListener 21 | Peers map[string]*net.TCPConn 22 | MsgChan chan<- *message.ConMessage 23 | } 24 | 25 | func NewSimpleP2pLib(id int64, msgChan chan<- *message.ConMessage) P2pNetwork { 26 | 27 | port := message.PortByID(id) 28 | s, err := net.ListenTCP("tcp4", &net.TCPAddr{ 29 | Port: port, 30 | }) 31 | 32 | if err != nil { 33 | panic(err) 34 | } 35 | 36 | sp := &SimpleP2p{ 37 | SrvBub: s, 38 | Peers: make(map[string]*net.TCPConn), 39 | MsgChan: msgChan, 40 | } 41 | go sp.monitor() 42 | for _, pid := range nodeList { 43 | if pid == id { 44 | continue 45 | } 46 | 47 | rPort := message.PortByID(pid) 48 | conn, err := net.DialTCP("tcp", nil, &net.TCPAddr{Port: rPort}) 49 | if err != nil { 50 | fmt.Printf("\nnode [%d] is not valid currently\n", pid) 51 | continue 52 | } 53 | sp.Peers[conn.RemoteAddr().String()] = conn 54 | fmt.Printf("node [%d] connected=[%s=>%s]\n", pid, conn.LocalAddr().String(), conn.RemoteAddr().String()) 55 | go sp.waitData(conn) 56 | } 57 | return sp 58 | } 59 | 60 | func (sp *SimpleP2p) monitor() { 61 | fmt.Printf("===>P2p node is waiting at:%s\n", sp.SrvBub.Addr().String()) 62 | for { 63 | conn, err := sp.SrvBub.AcceptTCP() 64 | if err != nil { 65 | fmt.Printf("P2p network accept err:%s\n", err) 66 | if err == io.EOF { 67 | fmt.Printf("Remove peer node%s\n", conn.RemoteAddr().String()) 68 | delete(sp.Peers, conn.RemoteAddr().String()) 69 | } 70 | continue 71 | } 72 | 73 | sp.Peers[conn.RemoteAddr().String()] = conn 74 | fmt.Printf("connection create [%s->%s]\n", conn.RemoteAddr().String(), conn.LocalAddr().String()) 75 | go sp.waitData(conn) 76 | } 77 | } 78 | 79 | func (sp *SimpleP2p) waitData(conn *net.TCPConn) { 80 | buf := make([]byte, 2048) 81 | for { 82 | n, err := conn.Read(buf) 83 | if err != nil { 84 | fmt.Printf("P2p network capture data err:%s\n", err) 85 | if err == io.EOF { 86 | fmt.Printf("Remove peer node%s\n", conn.RemoteAddr().String()) 87 | delete(sp.Peers, conn.RemoteAddr().String()) 88 | return 89 | 90 | } 91 | continue 92 | } 93 | conMsg := &message.ConMessage{} 94 | if err := json.Unmarshal(buf[:n], conMsg); err != nil { 95 | fmt.Println(string(buf[:n])) 96 | panic(err) 97 | } 98 | sp.MsgChan <- conMsg 99 | } 100 | } 101 | 102 | func (sp *SimpleP2p) BroadCast(v interface{}) error { 103 | if v == nil { 104 | return fmt.Errorf("empty msg body") 105 | } 106 | data, err := json.Marshal(v) 107 | if err != nil { 108 | return err 109 | } 110 | for name, conn := range sp.Peers { 111 | _, err := conn.Write(data) 112 | if err != nil { 113 | fmt.Printf("write to node[%s] err:%s\n", name, err) 114 | } 115 | } 116 | time.Sleep(300 * time.Millisecond) 117 | return nil 118 | } 119 | 120 | func (sp *SimpleP2p) SendToNode(nodeID int64, v interface{}) error { 121 | //TODO:: single point message 122 | return sp.BroadCast(v) 123 | } 124 | -------------------------------------------------------------------------------- /p2pnetwork/p2p_http.go: -------------------------------------------------------------------------------- 1 | package p2pnetwork 2 | -------------------------------------------------------------------------------- /p2pnetwork/p2p_tcp.go: -------------------------------------------------------------------------------- 1 | package p2pnetwork 2 | -------------------------------------------------------------------------------- /pbft-consensus-behavior.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didchain/pbft/0efea2d062efac3631cf3babc1773c361729eb69/pbft-consensus-behavior.jpg -------------------------------------------------------------------------------- /prepared.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didchain/pbft/0efea2d062efac3631cf3babc1773c361729eb69/prepared.jpg -------------------------------------------------------------------------------- /safe_prove.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didchain/pbft/0efea2d062efac3631cf3babc1773c361729eb69/safe_prove.jpg -------------------------------------------------------------------------------- /service/service.go: -------------------------------------------------------------------------------- 1 | package service 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "github.com/didchain/PBFT/message" 7 | "net" 8 | ) 9 | 10 | /* 11 | Our algorithm can be used to implement any deterministic replicated service with a state and some operations. The 12 | operations are not restricted to simple reads or writes of portions of the service state; they can perform arbitrary 13 | deterministic computations using the state and operation arguments. Clients issue requests to the replicated service to 14 | invoke operations and block waiting for a reply. The replicated service is implemented by replicas. Clients and 15 | replicas are non-faulty if they follow the algorithm in Section 4 and if no attacker can forge their signature. 16 | */ 17 | 18 | type Service struct { 19 | SrvHub *net.UDPConn 20 | nodeChan chan interface{} 21 | } 22 | 23 | func InitService(port int, msgChan chan interface{}) *Service { 24 | locAddr := net.UDPAddr{ 25 | Port: port, 26 | } 27 | srv, err := net.ListenUDP("udp4", &locAddr) 28 | if err != nil { 29 | return nil 30 | } 31 | fmt.Printf("\n===>Service Listening at[%d]", port) 32 | s := &Service{ 33 | SrvHub: srv, 34 | nodeChan: msgChan, 35 | } 36 | return s 37 | } 38 | 39 | func (s *Service) WaitRequest(sig chan interface{}) { 40 | 41 | defer func() { 42 | if r := recover(); r != nil { 43 | sig <- r 44 | } 45 | }() 46 | 47 | buf := make([]byte, 2048) 48 | for { 49 | n, rAddr, err := s.SrvHub.ReadFromUDP(buf) 50 | if err != nil { 51 | fmt.Printf("Service received err:%s\n", err) 52 | continue 53 | } 54 | fmt.Printf("\nService message[%d] from[%s]\n", n, rAddr.String()) 55 | bo := &message.Request{} 56 | if err := json.Unmarshal(buf[:n], bo); err != nil { 57 | fmt.Printf("\nService message parse err:%s", err) 58 | continue 59 | } 60 | go s.process(bo) 61 | } 62 | } 63 | 64 | func (s *Service) process(op *message.Request) { 65 | 66 | /* 67 | TODO:: Check operation 68 | 1. if clientID is authorized 69 | 2. if operation is valid 70 | */ 71 | s.nodeChan <- op 72 | } 73 | 74 | /* 75 | Each replica i executes the operation requested by m after committed-local(m, v, n, i)is true and i’s state 76 | reflects the sequential execution of all requests with lower sequence numbers. This ensures that all non- faulty replicas 77 | execute requests in the same order as required to provide the safety property. After executing the requested operation, 78 | replicas send a reply to the client. Replicas discard requests whose timestamp is lower than the timestamp in the last 79 | reply they sent to the client to guarantee exactly-once semantics. 80 | We do not rely on ordered message delivery, and therefore it is possible for a replica to commit requests out 81 | of order. This does not matter since it keeps the pre- prepare, prepare, and commit messages logged until the 82 | corresponding request can be executed. 83 | */ 84 | func (s *Service) Execute(v, n, seq int64, o *message.Request) (reply *message.Reply, err error) { 85 | 86 | fmt.Printf("Service is executing opertion[%s]......\n", o.Operation) 87 | r := &message.Reply{ 88 | SeqID: seq, 89 | ViewID: v, 90 | Timestamp: o.TimeStamp, 91 | ClientID: o.ClientID, 92 | NodeID: n, 93 | Result: "success", 94 | } 95 | 96 | bs, _ := json.Marshal(r) 97 | cAddr := net.UDPAddr{ 98 | Port: 8088, 99 | } 100 | no, err := s.SrvHub.WriteToUDP(bs, &cAddr) 101 | if err != nil { 102 | fmt.Printf("Reply client failed:%s\n", err) 103 | return nil, err 104 | } 105 | fmt.Printf("Reply Success!:%d seq=%d\n", no, seq) 106 | return r, nil 107 | } 108 | 109 | func (s *Service) DirectReply(r *message.Reply) error { 110 | bs, _ := json.Marshal(r) 111 | cAddr := net.UDPAddr{ 112 | Port: 8088, 113 | } 114 | no, err := s.SrvHub.WriteToUDP(bs, &cAddr) 115 | if err != nil { 116 | fmt.Printf("Reply client failed:%s\n", err) 117 | return err 118 | } 119 | fmt.Printf("Reply Directly Success!:%d seq=%d\n", no, r.SeqID) 120 | return nil 121 | } 122 | -------------------------------------------------------------------------------- /test/client.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "github.com/didchain/PBFT/message" 7 | "net" 8 | "os" 9 | "strconv" 10 | "sync" 11 | "time" 12 | ) 13 | 14 | func request(conn *net.UDPConn, wg *sync.RWMutex) { 15 | for { 16 | wg.Lock() 17 | primaryID, _ := strconv.Atoi(os.Args[1]) 18 | rAddr := net.UDPAddr{ 19 | Port: message.PortByID(int64(primaryID)), 20 | } 21 | 22 | r := &message.Request{ 23 | TimeStamp: time.Now().Unix(), 24 | ClientID: "Client's address", 25 | Operation: "", 26 | } 27 | 28 | bs, err := json.Marshal(r) 29 | if err != nil { 30 | panic(err) 31 | } 32 | 33 | n, err := conn.WriteToUDP(bs, &rAddr) 34 | if err != nil || n == 0 { 35 | panic(err) 36 | } 37 | fmt.Println("Send request success!:=>") 38 | } 39 | } 40 | 41 | func normalCaseOperation(roundSize int) { 42 | fmt.Println("start test.....") 43 | lclAddr := net.UDPAddr{ 44 | Port: 8088, 45 | } 46 | conn, err := net.ListenUDP("udp4", &lclAddr) 47 | if err != nil { 48 | panic(err) 49 | } 50 | 51 | defer conn.Close() 52 | 53 | locker := &sync.RWMutex{} 54 | go request(conn, locker) 55 | waitBuffer := make([]byte, 1024) 56 | var counter = 0 57 | var curSeq int64 = 0 58 | for { 59 | n, _, err := conn.ReadFromUDP(waitBuffer) 60 | if err != nil { 61 | panic(err) 62 | } 63 | //fmt.Printf("Client Read[%d] Reply from[%s]:\n", n, rAddr.String()) 64 | 65 | re := &message.Reply{} 66 | if err := json.Unmarshal(waitBuffer[:n], re); err != nil { 67 | panic(err) 68 | } 69 | 70 | if curSeq > re.SeqID { 71 | continue 72 | } 73 | 74 | counter++ 75 | if counter >= 2 { 76 | fmt.Printf("Consensus(seq=%d) operation(%d) success!\n", curSeq, roundSize) 77 | locker.Unlock() 78 | counter = 0 79 | roundSize-- 80 | curSeq = re.SeqID + 1 81 | } 82 | if roundSize <= 0 { 83 | fmt.Println("Test case finished") 84 | os.Exit(0) 85 | } 86 | } 87 | } 88 | 89 | func main() { 90 | //normalCaseOperation(51) 91 | //normalCaseOperation(21) 92 | //normalCaseOperation(30) 93 | //normalCaseOperation(100) 94 | normalCaseOperation(1) 95 | } 96 | -------------------------------------------------------------------------------- /view_change.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didchain/pbft/0efea2d062efac3631cf3babc1773c361729eb69/view_change.jpg -------------------------------------------------------------------------------- /view_change2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didchain/pbft/0efea2d062efac3631cf3babc1773c361729eb69/view_change2.jpg -------------------------------------------------------------------------------- /view_change3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/didchain/pbft/0efea2d062efac3631cf3babc1773c361729eb69/view_change3.jpg --------------------------------------------------------------------------------