├── .gitignore ├── .travis.yml ├── CHANGELOG.md ├── CONTRIBUTOR ├── COPYING ├── Cargo.toml ├── LICENSE ├── README.md ├── appveyor.yml ├── archive └── sentinel.rs ├── docs └── sentinel.md └── src ├── key_sentinel.rs ├── key_store.rs ├── lib.rs ├── pure_sentinel.rs ├── refresh_sentinel.rs ├── statistics.rs └── wrappers.rs /.gitignore: -------------------------------------------------------------------------------- 1 | *.exe 2 | *.lock 3 | *.swp 4 | *.rsproj 5 | tags* 6 | bootstrap.cache 7 | build/ 8 | build-tests/ 9 | target/ 10 | /.idea 11 | /.project 12 | /bin 13 | *.sublime-* 14 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | env: 2 | global: 3 | - secure: b15ogudB48Gj7qbFmgz6rkE7eG2A1Avrigjd+mnB/z2feJbFIR0pztlwJfVBSdpyia5vgBmmphLjoDnYineRyo5v+W52jOLmouREuzJA2Y5SUNEMkmIYLMI9CBnjIOMQ333i6FQHwsO3K+GSz0Nt4bGi9trsd2U58sGs6i8Y5Gg= 4 | os: 5 | - linux 6 | - osx 7 | language: rust 8 | rust: 9 | - nightly 10 | - beta 11 | - stable 12 | sudo: false 13 | branches: 14 | only: 15 | - master 16 | cache: 17 | directories: 18 | - $HOME/libsodium 19 | - $HOME/elfutils 20 | install: 21 | - curl -sSLO https://github.com/maidsafe/QA/raw/master/Bash%20Scripts/Travis/install_libsodium.sh 22 | - . install_libsodium.sh 23 | script: 24 | - curl -sSL https://github.com/maidsafe/QA/raw/master/Bash%20Scripts/Travis/build_and_run_tests.sh | bash 25 | before_cache: 26 | - curl -sSLO https://github.com/maidsafe/QA/raw/master/Bash%20Scripts/Travis/install_elfutils.sh 27 | - . install_elfutils.sh 28 | after_success: 29 | - curl -sSL https://github.com/maidsafe/QA/raw/master/Bash%20Scripts/Travis/after_success.sh | bash 30 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Sentinel - Change Log 2 | 3 | ## [0.1.2] 4 | - Rename Sentinel to PureSentinel in routing 5 | - Modify PureSentinel to use dynamic threshold values 6 | - Modify KeySentinel to use dynamic threshold values 7 | - Replace the AccountSentinel with the accumulator we have in Routing 8 | 9 | ## [0.1.1] 10 | - Updated dependencies' versions 11 | 12 | ## [0.0.1 - 0.1.0] Implement the three sentinels 13 | - Move Frequency back here into this crate 14 | - Remove dependency on the custom fork of the sodiumdioxide library 15 | - Implement KeyStore 16 | - Test KeyStore 17 | - Implement PureSentinel 18 | - Test PureSentinel 19 | - Implement AccountSentinel 20 | - Test AccountSentinel 21 | - Implement KeySentinel 22 | - Test KeySentinel 23 | 24 | ## [0.0.0 - 0.0.1] 25 | - Reference implementation for the PureSentinel 26 | -------------------------------------------------------------------------------- /CONTRIBUTOR: -------------------------------------------------------------------------------- 1 | MaidSafe Contributor Agreement version 1.0 1. Scope of this Agreement This MaidSafe Contributor Agreement ("MCA") applies to any contribution (as defined below) that you make to any software or other product or project managed by us (the "project"), and sets out the intellectual property rights you assign and grant to us in the contributed materials. The term "us" shall mean MaidSafe.net Limited. The term "you" shall mean the person or entity identified below. 2. Acceptance You should read this agreement carefully before posting any contributions (as defined below) to the project. Your posting of any contribution to this project will be deemed to constitute acceptance of the terms of this MCA. This MCA is a binding legal agreement between you and us. 3. Intellectual property rights The term "contributions" or "contributed materials" means any source code, object code, patch, tool, sample, graphic, specification, manual, documentation, or any other material posted or submitted by you to the project. The term "intellectual property rights" means any patents, rights to inventions, copyrights and similar rights, rights in know-how and all other intellectual property rights anywhere in the world for the full term of those rights including all registrations and applications and the right to apply for registrations. In relation to intellectual property rights in your contributions: * you hereby assign to us with full title guarantee all the intellectual property rights (existing and future) in your contributions (the "rights"), and we hereby grant to you a perpetual, irrevocable, non-exclusive, worldwide, no-charge, royalty-free, unrestricted license to use the rights for any purpose. To the extent that such assignment is or becomes invalid, ineffective or unenforceable, you hereby grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge, royalty-free, unrestricted license to use the rights for any purpose (including, at our option, the right to sublicense these same rights to third parties through multiple levels of sublicensees or other licensing arrangements. * you hereby irrevocably and unconditionally waive all moral rights which you may have in your contributions in whatever part of the world such rights may be enforceable; * you agree to, without charge, execute and do all such acts, documents, matters and things as may be necessary or reasonably required to obtain patent, copyright or other protection for any of your contributions (or software in which they are included) or improvements or developments to them and to vest title to the intellectual property rights in them in us and you irrevocably appoint us to be your attorney and in your name and on your behalf to execute and do any such acts described above for the same purpose if needed; and * you agree that neither of us has any duty to consult with, obtain the consent of, pay or render an accounting to the other for any use or distribution of your contribution. This MCA is effective on the date you first submitted a contribution to us. Any contribution we make available under any license will also be made available under a suitable FSF (Free Software Foundation) or OSI (Open Source Initiative) approved license. You covenant, represent, warrant and agree that: * each contribution that you submit (1) is and shall be an original work of authorship and you can legally assign and grant the rights set out in this MCA, and (2) does not include any third party code or other materials; * no contribution will violate any third party's intellectual property rights; and * each contribution shall be in compliance with (and will not need a licence or permission under) applicable export or import laws. You agree to notify us if you become aware of any circumstance which would make any of the foregoing representations inaccurate in any respect. MaidSafe may publicly disclose your participation in the project, including the fact that you have signed the MCA. Any notice or other written communication to be given under or in connection with this agreement shall be in writing, no term shall be varied by statement, conduct or act of any party except that the parties may amend this agreement only by letter or written instrument signed by both parties. This agreement sets out the entire agreement and understanding between the parties relating to your contributions. This MCA is governed by Scottish law and subject to the jurisdiction of the Scottish courts save that we or you may bring action in other courts to the extent necessary to protect or enforce our intellectual property rights. -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "sentinel" 3 | version = "0.1.2" 4 | authors = ["MaidSafe Developers "] 5 | description = "Peer-to-peer network group consensus and PKI-like ID confirmation" 6 | documentation = "http://maidsafe.net/sentinel/latest" 7 | repository = "https://github.com/maidsafe/sentinel" 8 | readme = "README.md" 9 | license = "GPL-3.0" 10 | homepage = "http://maidsafe.net" 11 | 12 | [dependencies] 13 | rustc-serialize = "*" 14 | cbor = "*" 15 | sodiumoxide = "*" 16 | rand = "*" 17 | accumulator = "0.1.*" 18 | lru_time_cache = "0.2.*" 19 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MaidSafe.net Commercial Licence 1.0 2 | 3 | DATE [insert date] 4 | 5 | 6 | PARTIES 7 | 8 | (1) MaidSafe.next Ltd registered company number SC297540 of 72 Templehill, Troon, Scotland, 9 | KA10 6BE; and 10 | 11 | (2) [INSERT FULL COMPANY NAME OF CUSTOMER] (registered company number [number]) of [address] 12 | (the "Customer"). 13 | 14 | 15 | INTRODUCTION 16 | 17 | MaidSafe has agreed to supply and license, and the Customer has agreed to use and pay for, 18 | MaidSafe's proprietary software on the terms set out in this agreement. 19 | 20 | 21 | 1. Definitions 22 | 23 | In this agreement: 24 | 25 | "Affiliate" means in relation to any company, any body corporate which is from time to time a 26 | holding company of that company, a subsidiary of that company or a subsidiary of a holding 27 | company of that company ("holding company" and "subsidiary" having the meanings attributed to 28 | them by s.1159 Companies Act 2006); 29 | 30 | "Intellectual Property Rights" means any patents, rights to inventions, copyrights and similar 31 | rights, rights in know-how and all other intellectual property rights anywhere in the world 32 | for the full term of those rights including all registrations and applications and the right 33 | to apply for registrations; 34 | 35 | "Licence" shall mean the licence in clause 3 of this agreement; 36 | 37 | "Object" form shall mean any form resulting from mechanical transformation or translation of a 38 | Source form, including but not limited to compiled object code, generated documentation, and 39 | conversions to other media types; 40 | 41 | "Software" means the source or binary form of any MaidSafe.net limited developed code; and 42 | 43 | "Source" form shall mean software source code. 44 | 45 | 46 | 2. Supply of the Software 47 | 48 | MaidSafe will make available to the Customer the Software for download. 49 | 50 | 51 | 3. Licence 52 | 53 | 3.1 In consideration of, and subject to payment of, the charges payable under this agreement, 54 | MaidSafe grants the Customer a perpetual non-exclusive licence to use reproduce, sublicense, 55 | and distribute the Software in Source or Object form, in each case in accordance with this 56 | clause 3, for the duration of this agreement. This right includes the right to use the 57 | Intellectual Property Rights in the Software, including patent rights, and the Customer 58 | acknowledges that its use of the Software or any similar software (or any modified version of 59 | the Software or any software that is based on or includes any part of the Software) other than 60 | in accordance with the terms of this agreement (including the payment of the charges when due) 61 | would infringe MaidSafe's Intellectual Property Rights, including patents rights, and in such 62 | cases MaidSafe may terminate this Agreement without prejudice to its rights to claim damages, 63 | account of profits and/or injunctive relief. 64 | 65 | 3.2 Customer may reproduce and distribute copies of the Software in any medium, with or without 66 | modifications, and in Source or Object form, provided that Customer meets the following 67 | conditions: 68 | 69 | (a) Customer must ensure that any permitted user is required to enter into a written 70 | software licence and is not allowed to use the Software (including any modified version 71 | of the Software or any software that is based on or includes any part of the Software) 72 | in any manner that would not be permitted by this Licence; 73 | 74 | (b) Customer must cause any modified files to carry prominent notices stating that Customer 75 | changed the files; 76 | 77 | (c) Customer must retain, in the Source form of any copies of the Software (including any 78 | modified version of the Software or any software that is based on or includes any part 79 | of the Software) or any part thereof that Customer distributes, all copyright, patent, 80 | trademark, and attribution notices from the Source form of the Software; and 81 | 82 | (d) if the Software includes a "NOTICE" text file as part of its distribution, then any 83 | copies of the Software (including any modified version of the Software or any software 84 | that is based on or includes any part of the Software) or any part that Customer 85 | distributes must include a readable copy of the attribution notices contained within 86 | such NOTICE file in at least one of the following places: 87 | 88 | (i) within a NOTICE text file distributed as part of the Software; 89 | 90 | (ii) within the Source form or documentation, if provided along with the Software; or 91 | 92 | (iii) within a display generated by the Software, if and wherever such third-party 93 | notices normally appear. The contents of the NOTICE file are for informational 94 | purposes only and do not modify the Licence. 95 | 96 | 3.3 Except as expressly permitted otherwise by any term of this agreement, only the Customer is 97 | permitted to use the Software. Use by the Customer includes use by the Customer's employees 98 | and contractors provided that such use is solely on behalf of the Customer and for the 99 | purposes of the Customer's business. 100 | 101 | 3.4 The Customer may make such backup copies of the Software as are reasonably necessary to 102 | support the Customer's use of the Software in accordance with this agreement. MaidSafe will 103 | own the Intellectual Property Rights in any such backup copies. 104 | 105 | 3.5 The Customer may reverse engineer or decompile the Software but only to the extent allowed 106 | under applicable law and on the basis that Customer will request interoperability information 107 | from MaidSafe. 108 | 109 | 3.6 The Customer will comply with any reasonable instructions which MaidSafe gives the Customer 110 | relating to the use of the Software (or any modified version of the Software or any software 111 | that is based on or includes any part of the Software). The Customer will allow MaidSafe 112 | access to any premises controlled by the Customer in order to allow MaidSafe to check that the 113 | Software (or any modified version of the Software or any software that is based on or includes 114 | any part of the Software) is being used only as permitted. 115 | 116 | 3.7 This agreement does not grant permission to use the trade names, trademarks, service marks, or 117 | product names of the Licensor, except as required for reasonable and customary use in 118 | describing the origin of the Software and complying with this agreement. 119 | 120 | 121 | 4. Limited warranty 122 | 123 | 4.1 MaidSafe warrants that it will perform its obligations under this agreement with reasonable 124 | care and skill. 125 | 126 | 4.2 If the warranty in clause 4.1 is breached, the Customer must tell MaidSafe as soon as 127 | possible. The Customer must give MaidSafe a reasonable time to fix the problem or to 128 | re-perform any relevant services. This will be done without any additional charge to the 129 | Customer. If MaidSafe is able to do this within a reasonable time, MaidSafe will have no 130 | other obligations or liability in relation to that breach. If MaidSafe is unable to do this 131 | within a reasonable time or MaidSafe does not think that it is a sensible way to deal with the 132 | problem, then MaidSafe may if it wishes elect to take back the Software and to refund to the 133 | Customer all of the money which the Customer has paid to MaidSafe under this agreement. Where 134 | the problem relates to a portion of the Software and other elements supplied which are capable 135 | of use separately without material detriment to the Customer, MaidSafe may take back (and 136 | refund in respect of) affected portions only. 137 | 138 | 4.3 Apart from the terms set out in this agreement, no conditions, warranties or other terms apply 139 | to the Software or its supply or Licence under this agreement. In particular, no implied 140 | conditions, warranties or other terms relating to satisfactory quality or fitness for any 141 | purpose will apply to anything supplied under this agreement. MaidSafe does not warrant or 142 | enter into any terms to the effect that the Software: 143 | 144 | (a) will perform any particular function or purpose; or 145 | 146 | (b) be entirely free from defects or that its operation will be entirely error free. 147 | 148 | 4.4 MaidSafe will not be liable for breach of any of the warranties or any other terms in this 149 | agreement to the extent that the breach arises from: 150 | 151 | (a) use of the Software other than in accordance with normal operating procedures or as 152 | otherwise notified to the Customer by MaidSafe; 153 | 154 | (b) any alterations to the Software made by anyone other than MaidSafe or someone authorised 155 | by MaidSafe; 156 | 157 | (c) any problem with the computer on which the Software is installed, any equipment 158 | connected to that computer or any other software which is installed on that computer; 159 | 160 | (d) any abnormal or incorrect operating conditions; or 161 | 162 | (e) use of the Software in combination with any other hardware or software, unless this use 163 | has been approved by MaidSafe in writing. 164 | 165 | 166 | 5. Limitation of Liability 167 | 168 | 5.1 Neither party's liability: 169 | 170 | (a) for death or personal injury caused by its negligence or the negligence of its employees 171 | or agents; 172 | 173 | (b) for breach of clause 7 (Confidentiality); or 174 | 175 | (c) for fraudulent misrepresentation, is excluded or limited by this agreement, even if any 176 | other term of this agreement would otherwise suggest that this might be the case. 177 | 178 | 5.2 Other than as set out in clause 5.1, neither party shall be liable to the other (whether for 179 | breach of contract, negligence or for any other reason) for any: 180 | 181 | (a) loss of profits; 182 | 183 | (b) loss of sales; 184 | 185 | (c) loss of revenue; 186 | 187 | (d) loss of any software or data; 188 | 189 | (e) loss of use of hardware, software or data; 190 | 191 | (f) indirect, consequential or special loss. 192 | 193 | 5.3 Subject to clauses 5.1 and 5.2, MaidSafe's total aggregate liability under this agreement and 194 | in relation to anything which MaidSafe has done or not done in connection with this agreement 195 | (and whether the liability arises because of breach of contract, negligence or for any other 196 | reason) shall be limited to: 197 | 198 | (a) an amount equal to 125% of the total amount payable by the Customer under this agreement 199 | in the preceding 12 months; or 200 | 201 | (b) if the amount referred to in (a) cannot be calculated accurately at the time the 202 | relevant liability is to be assessed, or if it is less than £5,000, to £5,000 203 | 204 | 205 | 6. Charges 206 | 207 | 6.1 Schedule 1 sets out the licence fees and other charges payable by the Customer under this 208 | agreement. The charges are due on the dates (or on the happening of the events) specified in 209 | schedule 1. 210 | 211 | 6.2 MaidSafe may invoice the Customer for the charges as soon as they become due. The Customer 212 | must pay the invoices within 30 days of receiving them (and if MaidSafe posts them to the 213 | Customer, the Customer will be treated as having received them two working days later unless 214 | the Customer can show that this was not the case). 215 | 216 | 6.3 Where any charges are based on the Customer's revenues the Customer shall keep all accounts 217 | and documents necessary to evidence such revenues and to support any calculation of the 218 | relevant revenue share, and shall provide copies to MaidSafe on request. Customer shall allow 219 | MaidSafe and its agents to enter into Customer's premises and to have access to all such 220 | accounts and documents upon reasonable request. Where Customer's accounts and documents 221 | illustrate that Customer has underpaid any charges (or MaidSafe can otherwise demonstrate 222 | this) Customer shall immediately pay the balance due to MaidSafe plus MaidSafe's reasonable 223 | costs of audit. This clause 6.3 shall survive termination or expiry of this agreement for 6 224 | years. 225 | 226 | 6.4 MaidSafe may charge interest on all sums outstanding beyond the date on which they are due for 227 | payment under this agreement. Interest may be charged on that basis from the date payment was 228 | due until the date of payment (including after any judgement has been obtained) at the rate of 229 | 3% per calendar month or part thereof. 230 | 231 | 6.5 The amounts specified in schedule 1 do not include VAT or any other taxes on supplies and the 232 | Customer will pay these to MaidSafe as well as the amounts concerned. 233 | 234 | 235 | 7. Confidentiality 236 | 237 | 7.1 Each party will keep confidential any information which the other supplies to it in connection 238 | with this agreement. Confidential information will include the Software and any related 239 | documentation; all information marked as being confidential; and any other information which 240 | might reasonably be assumed to be confidential. The obligations as to confidentiality in this 241 | agreement will not apply to any information which: 242 | 243 | (a) is available to the public other than because of any breach of this agreement; 244 | 245 | (b) is, when it is supplied, already known to whomever it is disclosed to in circumstances 246 | in which they are not prevented from disclosing it to others; 247 | 248 | (c) is independently obtained by whomever it is disclosed to in circumstances in which they 249 | are not prevented from disclosing it to others; or 250 | 251 | (d) is required to be disclosed by law or by any court or tribunal with proper authority to 252 | order its disclosure (but only to the extent of such requirements). 253 | 254 | 255 | 8. Term and termination 256 | 257 | 8.1 This agreement will commence on the date set out on page 1 and will continue indefinitely 258 | until terminated in accordance with this clause 8. 259 | 260 | 8.2 Either party may terminate this agreement if: 261 | 262 | (a) the other materially breaches any term of this agreement and it is not possible to 263 | remedy that breach or it is possible to remedy that breach, but the other fails to do so 264 | within 30 days of being asked to do so; or 265 | 266 | (b) the other suffers any of the following event: 267 | 268 | (i) a meeting of creditors of that party being held or an arrangement or composition 269 | with or for the benefit of its creditors (including a voluntary arrangement as 270 | defined in the Insolvency Act 1986) being proposed by or in relation to that 271 | party; 272 | 273 | (ii) a chargeholder, receiver, administrative receiver or other similar party taking 274 | possession of or being appointed over or any distress, execution or other process 275 | being levied or enforced (and not being discharged within seven days) on the whole 276 | or a material part of the assets of that party; 277 | 278 | (iii) that party ceasing to carry on business or being deemed to be unable to pay its 279 | debts within the meaning of section 123 Insolvency Act 1986; 280 | 281 | (iv) that party or its directors or the holder of a qualifying floating charge or any 282 | of its creditors giving notice of their intention to appoint, appointing or making 283 | an application to the court for the appointment of, an administrator; 284 | 285 | (v) a petition being advertised or a resolution being passed or an order being made 286 | for the administration or the winding-up, bankruptcy or dissolution of that party; 287 | and/or 288 | 289 | (vi) the happening in relation to that party of an event analogous to any of the above 290 | in any jurisdiction in which it is incorporated or resident or in which it carries 291 | on business or has assets. 292 | 293 | 8.3 MaidSafe may terminate this agreement if: 294 | 295 | (a) Customer fails to pay any charges within 60 days of their due date; or 296 | 297 | (b) should the Software become, or in MaidSafe's reasonable opinion is likely to become, the 298 | subject of a claim of intellectual property infringement claim. 299 | 300 | 8.4 Apart from any other rights which MaidSafe might have, if the Customer breaches this agreement 301 | MaidSafe may suspend performance of any of its obligations or any of the Customer's rights 302 | under this agreement until the Customer remedies the breach to the reasonable satisfaction of 303 | MaidSafe. 304 | 305 | 306 | 9. Consequences of termination 307 | 308 | 9.1 If this agreement is terminated (regardless of who terminates it and regardless of the reason) 309 | the Customer will immediately on termination: 310 | 311 | (a) cease using the Software (including any modified version of the Software or any software 312 | that is based on or includes any part of the Software); 313 | 314 | (b) return all copies of the Software to MaidSafe or (if the copies are on media which is 315 | non-removable and forms part of equipment belonging to the Customer) delete all copies 316 | in such a way that they cannot be recovered; and 317 | 318 | (c) confirm to MaidSafe in writing that both of the above things have been done. 319 | 320 | 9.2 Termination of this agreement will not affect any accrued rights or liabilities which either 321 | MaidSafe or the Customer may have by the time termination takes effect. Clauses 5, 6 (for 322 | unpaid charges), 7 and 9 shall survive termination or expiry of this agreement and any other 323 | clause shall survive termination or expiry if expressly stated. 324 | 325 | 326 | 10. Other terms 327 | 328 | 10.1 The Customer may not assign any of the Customer's rights or obligations under this agreement. 329 | MaidSafe may assign this agreement or any of MaidSafe's rights or obligations under this 330 | agreement to someone else, provided MaidSafe tells the Customer in writing if it does so. 331 | 332 | 10.2 Neither party has any authority to enter into a contract for or on behalf of the other party, 333 | to assume a liability on behalf of the other party or to pledge the credit of the other party, 334 | unless such authority is expressly granted in writing by the other party. Neither party may 335 | act as if it has such authority and must not represent (expressly or by implying it) that it 336 | has such authority. 337 | 338 | 10.3 MaidSafe will not be liable to the Customer for any breach of this agreement which arises 339 | because of any circumstances which MaidSafe cannot reasonably be expected to control. 340 | 341 | 10.4 All notices and consents relating to this agreement must be in writing. All variations to 342 | this agreement must be agreed, set out in writing and signed on behalf of both MaidSafe and 343 | the Customer before they take effect. 344 | 345 | 10.5 In this agreement, unless it says otherwise: 346 | 347 | (a) reference to a person includes a legal person (such as a limited company) as well as a 348 | natural person; 349 | 350 | (b) reference to this agreement includes reference to the schedules and appendices and other 351 | documents attached to it or incorporated by reference into it (all as amended or added 352 | to from time to time); 353 | 354 | (c) reference to "including" in this agreement shall be treated as being by way of example 355 | and shall not limit the general applicability of any preceding words; 356 | 357 | (d) reference to any legislation shall be to that legislation as amended, extended or 358 | re-enacted from time to time and to any subordinate provision made under that 359 | legislation; 360 | 361 | (e) references to clauses or schedules shall be to those in this agreement; 362 | 363 | (f) reference to this agreement shall include reference to it after it has been amended, 364 | added to or replaced by a new agreement. 365 | 366 | 10.6 Except to the extent that this agreement expressly says otherwise, nothing in this agreement 367 | shall create a partnership between the parties or give the rights of a partner to either 368 | party. 369 | 370 | 10.7 Any software supplied or Licenced under this agreement will not be treated as goods within the 371 | meaning of the Sale of Goods Act 1979. Firmware will be treated as part of the goods in which 372 | it is installed. 373 | 374 | 10.8 This agreement sets out all of the terms that have been agreed between MaidSafe and the 375 | Customer in relation to the subjects covered by it. Subject to clause 5.1, no other 376 | representations or terms shall apply or form part of this agreement. The Customer 377 | acknowledges that it has not been influenced to enter this agreement by anything MaidSafe has 378 | said or done or committed to do, except as expressly recorded herein. 379 | 380 | 10.9 No term of this agreement is enforceable under the Contracts (Rights of Third Parties) Act 381 | 1999 by a person who is not a party to this agreement. 382 | 383 | 10.10 This agreement is governed by Scottish law. Both MaidSafe and the Customer submit to the 384 | exclusive jurisdiction of the Scottish courts in relation to any dispute concerning this 385 | agreement but MaidSafe is also entitled to apply to any court worldwide for injunctive and 386 | other remedies in order to protect or enforce its Intellectual Property Rights. 387 | 388 | 389 | SCHEDULE 1 390 | 391 | CHARGES 392 | 393 | 394 | 1. Customer shall pay to MaidSafe 1% of Qualifying Revenue. 395 | 396 | 2 "Qualifying Revenue" shall mean any revenue generated directly or indirectly by Customer or 397 | any Affiliate of Customer through: 398 | 399 | (a) use of the Software (including any modified version of the Software or any software that 400 | is based on or includes any part of the Software); or 401 | 402 | (b) the provision of services directly or indirectly to any person using the Software 403 | (including any modified version of the Software or any software that is based on or 404 | includes any part of the Software), 405 | 406 | ("Qualifying Activities") less any VAT charged on such Qualifying Activities. 407 | 408 | 3. Where any Qualifying Activity is discounted or provided for free (whether through bundling or 409 | otherwise) it will be deemed to be provided at market rate and the relevant Qualifying Revenue 410 | shall be calculated accordingly. 411 | 412 | 4. The charges will be payable quarterly in arrears. 413 | 414 | 5. Within 5 days of the end of each month Customer will provide to MaidSafe a statement setting 415 | out the Qualifying Revenue for the month. MaidSafe shall invoice Customer within 5 days of 416 | the end of each third month. Where no statement is provided or MaidSafe has cause to believe 417 | it to be inaccurate it may invoke its audit rights under this agreement. 418 | 419 | 420 | SIGNED on behalf of both parties on the date set out on page 1 of this agreement: 421 | 422 | 423 | 424 | SIGNED: ..................................................................... 425 | for and on behalf of MaidSafe 426 | 427 | 428 | 429 | ..................................................................... 430 | Name/status 431 | 432 | 433 | 434 | 435 | SIGNED: ..................................................................... 436 | for and on behalf of the Customer 437 | 438 | 439 | 440 | ..................................................................... 441 | Name/status 442 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ***This repository is no longer maintained*** 2 | # It has been moved to the maidsafe-archive organisation for reference only 3 | # 4 | # 5 | # 6 | # 7 | # Sentinel 8 | 9 | *Note:* This library is not being actively used or managed at the moment. If this continues to be the case, it will likely become deprecated in the future. 10 | 11 | [![](https://img.shields.io/badge/Project%20SAFE-Approved-green.svg)](http://maidsafe.net/applications) [![](https://img.shields.io/badge/License-GPL3-green.svg)](https://github.com/maidsafe/sentinel/blob/master/COPYING) 12 | 13 | **Primary Maintainer:** Peter Jankuliak (peter.jankuliak@maidsafe.net) 14 | 15 | **Secondary Maintainer:** Benjamin Bollen (benjamin.bollen@maidsafe.net) 16 | 17 | |Crate|Linux/OS X|Windows|Coverage|Issues| 18 | |:---:|:--------:|:-----:|:------:|:------:|:----:| 19 | |[![](http://meritbadge.herokuapp.com/sentinel)](https://crates.io/crates/sentinel)|[![Build Status](https://travis-ci.org/maidsafe/sentinel.svg?branch=master)](https://travis-ci.org/maidsafe/sentinel)|[![Build status](https://ci.appveyor.com/api/projects/status/8k0rwy0miac09p1b/branch/master?svg=true)](https://ci.appveyor.com/project/MaidSafe-QA/sentinel/branch/master)|[![Coverage Status](https://coveralls.io/repos/maidsafe/sentinel/badge.svg)](https://coveralls.io/r/maidsafe/sentinel)|[![Stories in Ready](https://badge.waffle.io/maidsafe/sentinel.png?label=ready&title=Ready)](https://waffle.io/maidsafe/sentinel)| 20 | 21 | | [API Documentation - master branch](http://maidsafe.net/sentinel/master) | [SAFE Network System Documentation](http://systemdocs.maidsafe.net) | [MaidSafe website](http://maidsafe.net) | [SAFE Network Forum](https://forum.safenetwork.io) | 22 | |:------:|:-------:|:-------:|:-------:| 23 | 24 | ## Overview 25 | 26 | Confirm group based consensus on messages in a peer-to-peer network 27 | -------------------------------------------------------------------------------- /appveyor.yml: -------------------------------------------------------------------------------- 1 | environment: 2 | global: 3 | RUST_BACKTRACE: 1 4 | matrix: 5 | - RUST_VERSION: stable 6 | # - RUST_VERSION: beta 7 | # - RUST_VERSION: nightly 8 | branches: 9 | only: 10 | - master 11 | 12 | clone_depth: 50 13 | 14 | install: 15 | - ps: | 16 | $url = "https://github.com/maidsafe/QA/raw/master/Powershell%20Scripts/AppVeyor" 17 | Start-FileDownload "$url/Install%20Rust.ps1" -FileName "Install Rust.ps1" 18 | Start-FileDownload "$url/Install%20libsodium.ps1" -FileName "Install libsodium.ps1" 19 | Start-FileDownload "$url/Build.ps1" -FileName "Build.ps1" 20 | Start-FileDownload "$url/Run%20Tests.ps1" -FileName "Run Tests.ps1" 21 | . ".\Install Rust.ps1" 22 | . ".\Install libsodium.ps1" 23 | 24 | platform: 25 | - x86 26 | - x64 27 | 28 | configuration: 29 | # - Debug 30 | - Release 31 | 32 | build_script: 33 | - ps: . ".\Build.ps1" 34 | 35 | test_script: 36 | - ps: . ".\Run Tests.ps1" 37 | -------------------------------------------------------------------------------- /archive/sentinel.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015 MaidSafe.net limited. 2 | // 3 | // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, 4 | // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which 5 | // licence you accepted on initial access to the Software (the "Licences"). 6 | // 7 | // By contributing code to the SAFE Network Software, or to this project generally, you agree to be 8 | // bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the 9 | // Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR. 10 | // 11 | // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed 12 | // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. 14 | // 15 | // Please review the Licences for the specific language governing permissions and limitations 16 | // relating to use of the SAFE Network Software. 17 | 18 | use std::collections::HashMap; 19 | use sodiumoxide::crypto; 20 | use cbor; 21 | 22 | use accumulator; 23 | use message_header; 24 | use NameType; 25 | use types; 26 | use types::{Mergeable, QUORUM_SIZE}; 27 | use frequency::Frequency; 28 | use messages::find_group_response::FindGroupResponse; 29 | use messages::get_client_key_response::GetKeyResponse; 30 | use messages::get_group_key_response::GetGroupKeyResponse; 31 | use messages::{MessageTypeTag}; 32 | use types::{PublicSignKey, SerialisedMessage}; 33 | use rustc_serialize::{Decodable, Encodable}; 34 | 35 | pub type ResultType = (message_header::MessageHeader, 36 | MessageTypeTag, SerialisedMessage, types::Signature); 37 | 38 | type NodeKeyType = (types::NodeAddress, types::MessageId); 39 | type GroupKeyType = (types::GroupAddress, types::MessageId); 40 | type NodeAccumulatorType = accumulator::Accumulator; 41 | type GroupAccumulatorType = accumulator::Accumulator; 42 | type KeyAccumulatorType = accumulator::Accumulator; 43 | 44 | 45 | // TODO (ben 2015-4-2): replace dynamic dispatching with static dispatching 46 | // https://doc.rust-lang.org/book/static-and-dynamic-dispatch.html 47 | pub trait SendGetKeys { 48 | fn get_client_key(&mut self, address : NameType); 49 | fn get_group_key(&mut self, group_address : types::GroupAddress); 50 | } 51 | 52 | pub struct Sentinel<'a> { 53 | send_get_keys_: &'a mut (SendGetKeys + 'a), 54 | node_accumulator_: NodeAccumulatorType, 55 | group_accumulator_: GroupAccumulatorType, 56 | group_key_accumulator_: KeyAccumulatorType, 57 | node_key_accumulator_: KeyAccumulatorType, 58 | } 59 | 60 | impl<'a> Sentinel<'a> { 61 | pub fn new(send_get_keys: &'a mut SendGetKeys) -> Sentinel<'a> { 62 | Sentinel { 63 | send_get_keys_: send_get_keys, 64 | node_accumulator_: NodeAccumulatorType::new(QUORUM_SIZE as usize), 65 | group_accumulator_: NodeAccumulatorType::new(QUORUM_SIZE as usize), 66 | group_key_accumulator_: KeyAccumulatorType::new(QUORUM_SIZE as usize), 67 | node_key_accumulator_: KeyAccumulatorType::new(QUORUM_SIZE as usize) 68 | } 69 | } 70 | 71 | // pub fn get_send_get_keys(&'a mut self) -> &'a mut SendGetKeys { self.send_get_keys } 72 | 73 | pub fn add(&mut self, header: message_header::MessageHeader, type_tag: MessageTypeTag, 74 | message : types::SerialisedMessage, signature : types::Signature) 75 | -> Option { 76 | match type_tag { 77 | MessageTypeTag::GetKeyResponse => { 78 | if header.is_from_group() { 79 | let keys = self.node_key_accumulator_.add(header.from_group().unwrap(), 80 | (header.clone(), type_tag, 81 | message, signature)); 82 | if keys.is_some() { 83 | let key = (header.from_group().unwrap(), header.message_id()); 84 | let messages = self.node_accumulator_.get(&key); 85 | if messages.is_some() { 86 | let resolved = Sentinel::resolve(Sentinel::validate_node(messages.unwrap().1, 87 | keys.unwrap().1)); 88 | if resolved.is_some() { 89 | self.node_accumulator_.delete(&key); 90 | return resolved; 91 | } 92 | } 93 | } 94 | } 95 | } 96 | MessageTypeTag::GetGroupKeyResponse => { 97 | if header.is_from_group() { 98 | let keys = self.group_key_accumulator_.add(header.from_group().unwrap(), 99 | (header.clone(), type_tag, 100 | message, signature)); 101 | if keys.is_some() { 102 | let key = (header.from_group().unwrap(), header.message_id()); 103 | let messages = self.group_accumulator_.get(&key); 104 | if messages.is_some() { 105 | let resolved = Sentinel::resolve(Sentinel::validate_group(messages.unwrap().1, 106 | keys.unwrap().1)); 107 | if resolved.is_some() { 108 | self.group_accumulator_.delete(&key); 109 | return resolved; 110 | } 111 | } 112 | } 113 | } 114 | } 115 | _ => { 116 | if header.is_from_group() { 117 | let key = (header.from_group().unwrap(), header.message_id()); 118 | if !self.group_accumulator_.have_name(&key) { 119 | self.send_get_keys_.get_group_key(header.from_group().unwrap()); }; 120 | let messages = self.group_accumulator_.add(key.clone(), 121 | (header.clone(), type_tag, 122 | message, signature)); 123 | if messages.is_some() { 124 | let keys = self.group_key_accumulator_.get(&header.from_group().unwrap()); 125 | if keys.is_some() { 126 | let resolved = Sentinel::resolve(Sentinel::validate_group(messages.unwrap().1, 127 | keys.unwrap().1)); 128 | if resolved.is_some() { 129 | self.group_accumulator_.delete(&key); 130 | return resolved; 131 | } 132 | } 133 | } 134 | } else { 135 | let key = (header.from_node(), header.message_id()); 136 | if !self.node_accumulator_.have_name(&key) { 137 | self.send_get_keys_.get_client_key(header.from_group().unwrap()); }; 138 | let messages = self.node_accumulator_.add(key.clone(), 139 | (header.clone(), type_tag, 140 | message, signature)); 141 | if messages.is_some() { 142 | let keys = self.node_key_accumulator_.get(&header.from_group().unwrap()); 143 | if keys.is_some() { 144 | let resolved = Sentinel::resolve(Sentinel::validate_node(messages.unwrap().1, 145 | keys.unwrap().1)); 146 | if resolved.is_some() { 147 | self.node_accumulator_.delete(&key); 148 | return resolved; 149 | } 150 | } 151 | } 152 | } 153 | } 154 | } 155 | None 156 | } 157 | 158 | fn check_signature(response: &ResultType, pub_key: &PublicSignKey) -> Option { 159 | let is_correct = crypto::sign::verify_detached( 160 | &response.3.get_crypto_signature(), 161 | &response.2[..], 162 | &pub_key.get_crypto_public_sign_key()); 163 | 164 | if !is_correct { return None; } 165 | Some(response.clone()) 166 | } 167 | 168 | fn validate_node(messages: Vec, 169 | keys: Vec) -> Vec { 170 | if messages.len() == 0 || keys.len() < QUORUM_SIZE as usize { 171 | return Vec::new(); 172 | } 173 | 174 | // TODO: Would be nice if we didn't need to decode it here every time 175 | // this function is called. We could then avoid the below check as well. 176 | let keys = keys.iter().filter_map(|key_msg| Sentinel::decode(&key_msg.2)).collect::>(); 177 | 178 | // Need to check this again because decoding may have failed. 179 | if keys.len() < QUORUM_SIZE as usize { 180 | return Vec::new(); 181 | } 182 | 183 | take_most_frequent(&keys, QUORUM_SIZE as usize) 184 | .into_iter() 185 | .flat_map(|GetKeyResponse{address: _, public_sign_key: pub_key}| { 186 | messages.iter().filter_map(move |response| { 187 | Sentinel::check_signature(&response, &pub_key) 188 | }) 189 | }) 190 | .collect::>() 191 | } 192 | 193 | fn validate_group(messages: Vec, 194 | keys: Vec) -> Vec { 195 | if messages.len() < QUORUM_SIZE as usize || keys.len() < QUORUM_SIZE as usize { 196 | return Vec::::new(); 197 | } 198 | 199 | // TODO: Would be nice if we didn't need to decode it here every time 200 | // this function is called. We could then avoid the below check as well. 201 | let keys = keys.iter().filter_map(|key_msg| Sentinel::decode(&key_msg.2)).collect::>(); 202 | 203 | // Need to check this again because decoding may have failed. 204 | if keys.len() < QUORUM_SIZE as usize { 205 | return Vec::::new(); 206 | } 207 | 208 | let key_map = Mergeable::merge(keys.iter()) 209 | .into_iter() 210 | .flat_map(|GetGroupKeyResponse{public_sign_keys: addr_key_pairs}| { 211 | addr_key_pairs.into_iter() 212 | }) 213 | .collect::>(); 214 | 215 | messages.iter().filter_map(|message| { 216 | key_map.get(&message.0.from_node()) 217 | .and_then(|pub_key| Sentinel::check_signature(&message, &pub_key)) 218 | }) 219 | .collect::>() 220 | } 221 | 222 | fn decode(data: &SerialisedMessage) -> Option { 223 | let mut decoder = cbor::Decoder::from_bytes(data.clone()); 224 | decoder.decode().next().and_then(|result_msg| result_msg.ok()) 225 | } 226 | 227 | fn encode(value: T) -> SerialisedMessage { 228 | let mut e = cbor::Encoder::from_memory(); 229 | let _ = e.encode(&[&value]); // FIXME: Panic when failed to encode? 230 | e.as_bytes().to_vec() 231 | } 232 | 233 | fn resolve(verified_messages : Vec) -> Option { 234 | if verified_messages.len() < QUORUM_SIZE as usize { 235 | return None; 236 | } 237 | 238 | // TODO: Make sure the header is used from a message that belongs to the quorum. 239 | 240 | return if verified_messages[0].1 == MessageTypeTag::FindGroupResponse { 241 | let decoded_responses = verified_messages.iter() 242 | .filter_map(|msg| Sentinel::decode::(&msg.2)) 243 | .collect::>(); 244 | 245 | //FIXME(ben): after merging the messages the headers and the signature 246 | // have lost meaning; we should be returning less then this; 247 | // in particular will the signature no longer match 248 | // merged message 249 | Mergeable::merge(decoded_responses.iter()).map(|merged| { 250 | (verified_messages[0].0.clone(), 251 | verified_messages[0].1.clone(), 252 | Sentinel::encode(merged), 253 | verified_messages[0].3.clone()) 254 | }) 255 | } else if verified_messages[0].1 == MessageTypeTag::GetGroupKeyResponse { 256 | // TODO: GetGroupKeyResponse will probably never reach this function.(?) 257 | let accounts = verified_messages.iter() 258 | .filter_map(|msg_triple| { Sentinel::decode::(&msg_triple.2) }) 259 | .collect::>(); 260 | 261 | //FIXME(ben): see comment above 262 | Mergeable::merge(accounts.iter()).map(|merged| { 263 | (verified_messages[0].0.clone(), 264 | verified_messages[0].1.clone(), 265 | Sentinel::encode(merged), 266 | verified_messages[0].3.clone()) 267 | }) 268 | } else { 269 | let header = verified_messages[0].0.clone(); 270 | let tag = verified_messages[0].1.clone(); 271 | //FIXME(ben): see comment above 272 | let signature = verified_messages[0].3.clone(); 273 | 274 | let msg_bodies = verified_messages.into_iter() 275 | .map(|(_, _, body, _)| body) 276 | .collect::>(); 277 | 278 | take_most_frequent(&msg_bodies, QUORUM_SIZE as usize) 279 | .map(|merged| { (header, tag, merged, signature) }) 280 | } 281 | } 282 | } 283 | 284 | fn take_most_frequent(elements: &Vec, min_count: usize) -> Option 285 | where E: Clone + Ord { 286 | let mut freq_counter = Frequency::::new(); 287 | for element in elements { 288 | freq_counter.update(element.clone()); 289 | } 290 | freq_counter.sort_by_highest().into_iter().nth(0).and_then(|(element, count)| { 291 | if count >= min_count as usize { Some(element) } else { None } 292 | }) 293 | } 294 | 295 | #[cfg(test)] 296 | mod test { 297 | 298 | use super::*; 299 | use std::cmp; 300 | use sodiumoxide::crypto; 301 | use types; 302 | use name_type::closer_to_target; 303 | use NameType; 304 | use message_header; 305 | use messages; 306 | use rustc_serialize::{Encodable, Decodable}; 307 | use rand; 308 | use cbor; 309 | use test_utils::Random; 310 | use message_header::MessageHeader; 311 | use messages::{RoutingMessage, MessageTypeTag}; 312 | use messages::put_data::PutData; 313 | use messages::get_group_key_response::GetGroupKeyResponse; 314 | use types::{MessageId, Id, PublicId, GroupAddress, NodeAddress, DestinationAddress, 315 | SourceAddress, PublicSignKey, GROUP_SIZE, vector_as_u8_64_array}; 316 | use authority::Authority; 317 | use sodiumoxide::crypto::hash::sha512::hash; 318 | use rand::{thread_rng, Rng}; 319 | use rand::distributions::{IndependentSample, Range}; 320 | 321 | 322 | 323 | 324 | pub struct AddSentinelMessage { 325 | header : message_header::MessageHeader, 326 | tag : messages::MessageTypeTag, 327 | serialised_message : Vec, 328 | signature: types::Signature, 329 | index : u64 330 | } 331 | 332 | pub fn generate_u8_64() -> Vec { 333 | let mut u8_64: Vec = vec![]; 334 | for _ in (0..64) { 335 | u8_64.push(rand::random::()); 336 | } 337 | u8_64 338 | } 339 | 340 | pub fn generate_data(length : usize) -> Vec { 341 | let mut data: Vec = vec![]; 342 | for _ in (0..length) { 343 | data.push(rand::random::()); 344 | } 345 | data 346 | } 347 | 348 | struct SignatureGroup { 349 | group_address_ : types::GroupAddress, 350 | group_size_ : usize, 351 | authority_ : Authority, 352 | nodes_ : Vec 353 | } 354 | 355 | impl SignatureGroup { 356 | pub fn new(group_size : usize, authority : Authority) -> SignatureGroup { 357 | let group_address : NameType = Random::generate_random(); 358 | let mut nodes : Vec = Vec::with_capacity(group_size); 359 | for _ in 0..group_size { 360 | nodes.push(types::Id::new()); 361 | } 362 | SignatureGroup { 363 | group_address_ : group_address, 364 | group_size_ : group_size, 365 | authority_ : authority, 366 | nodes_ : nodes 367 | } 368 | } 369 | 370 | pub fn get_group_address(&self) -> types::GroupAddress { self.group_address_.clone() } 371 | 372 | pub fn get_headers(&self, destination_address : &types::DestinationAddress, 373 | message_id : &types::MessageId, serialised_message : &Vec ) 374 | -> Vec<(message_header::MessageHeader, types::Signature)> { 375 | let mut headers : Vec<(message_header::MessageHeader, types::Signature)> 376 | = Vec::with_capacity(self.group_size_); 377 | for node in &self.nodes_ { 378 | headers.push((message_header::MessageHeader::new(message_id.clone(), 379 | destination_address.clone(), 380 | types::SourceAddress { 381 | from_node : node.get_name(), 382 | from_group : Some(self.group_address_.clone()), 383 | reply_to : None 384 | }, 385 | self.authority_.clone()), 386 | types::Signature::new(crypto::sign::sign_detached(&serialised_message, 387 | &node.get_crypto_secret_sign_key())))); 388 | } 389 | headers 390 | } 391 | 392 | pub fn get_public_keys(&self) -> Vec<(NameType, types::PublicSignKey)> { 393 | let mut public_keys : Vec<(NameType, types::PublicSignKey)> 394 | = Vec::with_capacity(self.nodes_.len()); 395 | for node in &self.nodes_ { 396 | public_keys.push((node.get_name(), 397 | types::PublicSignKey::new(node.get_crypto_public_sign_key()))); 398 | } 399 | public_keys 400 | } 401 | } 402 | 403 | struct EmbeddedSignatureGroup { 404 | group_address_ : types::GroupAddress, 405 | group_size_ : usize, 406 | authority_ : Authority, 407 | nodes_ : Vec, 408 | // store the close nodes according 409 | // to the close group of original group_address 410 | nodes_of_nodes_ : Vec<(NameType, Vec)> 411 | } 412 | 413 | impl EmbeddedSignatureGroup { 414 | pub fn new(group_size : usize, authority : Authority) 415 | -> EmbeddedSignatureGroup { 416 | let network_size = 10 * group_size; 417 | let mut all_nodes : Vec = Vec::with_capacity(network_size); 418 | let mut nodes : Vec = Vec::with_capacity(group_size); 419 | let mut nodes_of_nodes : Vec<(NameType, Vec)> 420 | = Vec::with_capacity(group_size); 421 | for _ in 0..network_size { 422 | all_nodes.push(types::Id::new()); // generates two keys ! 423 | // can be optimised for larger scaled 424 | } 425 | let group_address : NameType = Random::generate_random(); 426 | // first sort all nodes to group_address 427 | all_nodes.sort_by( 428 | |a, b| if closer_to_target(&a.get_name(), &b.get_name(), &group_address) { 429 | cmp::Ordering::Less 430 | } else { 431 | cmp::Ordering::Greater 432 | } 433 | ); 434 | // select group_size closest nodes 435 | for i in 0..group_size { nodes.push(all_nodes[i].clone()); }; 436 | for node in &nodes { 437 | // sort all nodes 438 | all_nodes.sort_by( 439 | |a, b| if closer_to_target(&a.get_name(), &b.get_name(), &node.get_name()) { 440 | cmp::Ordering::Less 441 | } else { 442 | cmp::Ordering::Greater 443 | } 444 | ); 445 | // add ourselves (at 0) and group_size closest 446 | assert_eq!(all_nodes[0].get_name(), node.get_name()); 447 | let mut nodes_of_node : Vec = Vec::with_capacity(group_size + 1); 448 | for i in 0..group_size + 1 { nodes_of_node.push(all_nodes[i].clone()); }; 449 | nodes_of_nodes.push((node.get_name(), nodes_of_node)); 450 | }; 451 | EmbeddedSignatureGroup { 452 | group_address_ : group_address, 453 | group_size_ : group_size, 454 | authority_ : authority, 455 | nodes_ : nodes, 456 | nodes_of_nodes_ : nodes_of_nodes 457 | } 458 | } 459 | 460 | pub fn get_group_address(&self) -> types::GroupAddress { self.group_address_.clone() } 461 | 462 | pub fn get_headers(&self, destination_address : &types::DestinationAddress, 463 | message_id : &types::MessageId, serialised_message : &Vec ) 464 | -> Vec<(message_header::MessageHeader, types::Signature)> { 465 | let mut headers : Vec<(message_header::MessageHeader, types::Signature)> 466 | = Vec::with_capacity(self.group_size_); 467 | for node in &self.nodes_ { 468 | headers.push((message_header::MessageHeader::new(message_id.clone(), 469 | destination_address.clone(), 470 | types::SourceAddress { 471 | from_node : node.get_name(), 472 | from_group : Some(self.group_address_.clone()), 473 | reply_to : None 474 | }, 475 | self.authority_.clone()), 476 | types::Signature::new(crypto::sign::sign_detached(&serialised_message, 477 | &node.get_crypto_secret_sign_key())))); 478 | } 479 | headers 480 | } 481 | 482 | pub fn get_public_keys(&self, node_name : NameType) 483 | -> Vec<(NameType, types::PublicSignKey)> { 484 | let nodes_of_node = &self.nodes_of_nodes_.iter().find(|x| x.0 == node_name).unwrap(); 485 | let mut public_keys : Vec<(NameType, types::PublicSignKey)> 486 | = Vec::with_capacity(nodes_of_node.1.len()); 487 | for node in &nodes_of_node.1 { 488 | let public_sign_key = 489 | types::PublicSignKey::new(node.get_crypto_public_sign_key()); 490 | public_keys.push((node.get_name(), public_sign_key)); 491 | } 492 | public_keys 493 | } 494 | 495 | pub fn get_public_ids(&self, node_name : NameType) -> Vec { 496 | let nodes_of_node = &self.nodes_of_nodes_.iter().find(|x| x.0 == node_name).unwrap(); 497 | let mut public_ids : Vec 498 | = Vec::with_capacity(nodes_of_node.1.len()); 499 | for node in &nodes_of_node.1 { 500 | public_ids.push(types::PublicId::new(&node)); 501 | } 502 | public_ids 503 | } 504 | 505 | pub fn generate_get_group_key_response_messages(&self, 506 | destination_address : &types::DestinationAddress, 507 | message_id : &types::MessageId, message_index : &mut u64) 508 | -> Vec { 509 | let mut collect_messages : Vec = Vec::with_capacity(self.group_size_); 510 | for node in &self.nodes_ { 511 | let get_group_key_response = messages::get_group_key_response::GetGroupKeyResponse { 512 | public_sign_keys : self.get_public_keys(node.get_name()) 513 | }; 514 | let mut e = cbor::Encoder::from_memory(); 515 | let _ = e.encode(&[&get_group_key_response]); 516 | let serialised_message_response = e.as_bytes().to_vec(); 517 | let header = message_header::MessageHeader::new(message_id.clone(), 518 | destination_address.clone(), 519 | types::SourceAddress { 520 | from_node : node.get_name(), 521 | from_group : Some(self.group_address_.clone()), 522 | reply_to : None 523 | }, 524 | self.authority_.clone()); 525 | let signature = types::Signature::new(crypto::sign::sign_detached( 526 | &serialised_message_response[..], &node.get_crypto_secret_sign_key())); 527 | collect_messages.push(AddSentinelMessage{ 528 | header : header.clone(), 529 | tag : messages::MessageTypeTag::GetGroupKeyResponse, 530 | serialised_message : serialised_message_response, 531 | signature : signature, 532 | index : message_index.clone() 533 | }); 534 | *message_index += 1; 535 | } 536 | collect_messages 537 | } 538 | 539 | pub fn generate_find_group_response_messages(&self, 540 | destination_address : &types::DestinationAddress, 541 | message_id : &types::MessageId, message_index : &mut u64) 542 | -> Vec { 543 | let mut collect_messages : Vec = Vec::with_capacity(self.group_size_); 544 | for node in &self.nodes_ { 545 | let find_group_response = messages::find_group_response::FindGroupResponse { 546 | group : self.get_public_ids(node.get_name()) 547 | }; 548 | let mut e = cbor::Encoder::from_memory(); 549 | let _ = e.encode(&[&find_group_response]); 550 | let serialised_message_response = e.as_bytes().to_vec(); 551 | let header = message_header::MessageHeader::new(message_id.clone(), 552 | destination_address.clone(), 553 | types::SourceAddress { 554 | from_node : node.get_name(), 555 | from_group : Some(self.group_address_.clone()), 556 | reply_to : None 557 | }, 558 | self.authority_.clone()); 559 | let signature = types::Signature::new(crypto::sign::sign_detached( 560 | &serialised_message_response[..], &node.get_crypto_secret_sign_key())); 561 | collect_messages.push(AddSentinelMessage{ 562 | header : header.clone(), 563 | tag : messages::MessageTypeTag::FindGroupResponse, 564 | serialised_message : serialised_message_response, 565 | signature : signature, 566 | index : message_index.clone() 567 | }); 568 | *message_index += 1; 569 | } 570 | collect_messages 571 | } 572 | } 573 | 574 | pub struct TraceGetKeys { 575 | send_get_client_key_calls_ : Vec, 576 | send_get_group_key_calls_ : Vec, 577 | } 578 | 579 | impl TraceGetKeys { 580 | pub fn new()-> TraceGetKeys { 581 | TraceGetKeys { 582 | send_get_client_key_calls_ : Vec::new(), 583 | send_get_group_key_calls_ : Vec::new() 584 | } 585 | } 586 | 587 | pub fn count_get_client_key_calls(&self, address : &NameType) -> usize { 588 | self.send_get_client_key_calls_.iter() 589 | .filter(|&x| x == address) 590 | .count() 591 | } 592 | 593 | pub fn count_get_group_key_calls(&self, group_address : &types::GroupAddress) -> usize { 594 | self.send_get_group_key_calls_.iter() 595 | .filter(|&x| x == group_address) 596 | .count() 597 | } 598 | } 599 | 600 | impl SendGetKeys for TraceGetKeys { 601 | fn get_client_key(&mut self, address : NameType) { 602 | self.send_get_client_key_calls_.push(address); 603 | } 604 | fn get_group_key(&mut self, group_address : types::GroupAddress) { 605 | self.send_get_group_key_calls_.push(group_address); 606 | } 607 | } 608 | 609 | fn generate_messages(headers : Vec<(message_header::MessageHeader, types::Signature)>, 610 | tag : messages::MessageTypeTag, message : &Vec, 611 | message_index : &mut u64) 612 | -> Vec { 613 | let mut collect_messages : Vec = Vec::with_capacity(headers.len()); 614 | for header in headers { 615 | collect_messages.push(AddSentinelMessage{ header : header.0, 616 | tag : tag.clone(), 617 | serialised_message : message.clone(), 618 | signature : header.1, 619 | index : message_index.clone()}); 620 | *message_index += 1; 621 | } 622 | collect_messages 623 | } 624 | 625 | fn count_none_sentinel_returns(sentinel_returns : &Vec<(u64, Option)>) 626 | -> usize { 627 | sentinel_returns.iter().filter(|&x| x.1.is_none()).count() 628 | } 629 | 630 | fn verify_exactly_one_response(sentinel_returns : &Vec<(u64, Option)>) 631 | -> bool { 632 | sentinel_returns.iter().filter(|&x| x.1.is_some()).count() == 1 633 | } 634 | 635 | fn get_selected_sentinel_returns(sentinel_returns: &mut Vec<(u64, Option)>, 636 | track_messages : &mut Vec) 637 | ->Vec<(u64, Option)> { 638 | if track_messages.is_empty() { return Vec::<(u64, Option)>::new(); } 639 | let mut selected_returns : Vec<(u64, Option)> = Vec::new(); 640 | sentinel_returns.sort_by(|a, b| a.0.cmp(&b.0)); 641 | track_messages.sort(); 642 | let mut track_index = 0; 643 | for sentinel_return in sentinel_returns { 644 | let track_message = track_messages[track_index]; 645 | if sentinel_return.0 == track_message { 646 | selected_returns.push(sentinel_return.clone()); 647 | } 648 | if sentinel_return.0 >= track_message { 649 | if track_index != track_messages.len() - 1 { 650 | track_index += 1; 651 | } else { break; } 652 | } 653 | } 654 | selected_returns 655 | } 656 | 657 | fn verify_match_sentinel_return(sentinel_return : &ResultType, 658 | original_message_id : types::MessageId, 659 | original_authority : Authority, 660 | original_destination : types::DestinationAddress, 661 | original_source_group : types::GroupAddress, 662 | original_message_type_tag : messages::MessageTypeTag, 663 | original_message : types::SerialisedMessage) 664 | -> bool { 665 | 666 | if original_message != sentinel_return.2 { return false; }; 667 | if original_message_type_tag != sentinel_return.1 {return false; }; 668 | if original_message_id != sentinel_return.0.message_id() { return false; }; 669 | if original_authority != sentinel_return.0.from_authority() { return false; }; 670 | if original_destination != sentinel_return.0.send_to() { return false; }; 671 | 672 | true 673 | } 674 | 675 | #[test] 676 | fn simple_add_put_data() { 677 | let our_id = types::Id::new(); 678 | let our_destination = types::DestinationAddress { 679 | dest : our_id.get_name(), 680 | reply_to : None 681 | }; 682 | let signature_group = SignatureGroup::new(types::GROUP_SIZE as usize, 683 | Authority::NaeManager); 684 | let mut trace_get_keys = TraceGetKeys::new(); 685 | let mut sentinel_returns : Vec<(u64, Option)> = Vec::new(); 686 | let mut message_tracker : u64 = 0; 687 | { 688 | let mut sentinel = Sentinel::new(&mut trace_get_keys); 689 | let data : Vec = generate_data(100usize); 690 | let put_data = messages::put_data::PutData { 691 | name: NameType::new(types::vector_as_u8_64_array(crypto::hash::sha512::hash(&data[..]).0.to_vec())), 692 | data : data 693 | }; 694 | let mut e = cbor::Encoder::from_memory(); 695 | let _ = e.encode(&[&put_data]); 696 | let serialised_message = e.as_bytes().to_vec(); 697 | let message_id = rand::random::() as types::MessageId; 698 | let tag = messages::MessageTypeTag::PutData; 699 | let headers = signature_group.get_headers(&our_destination, &message_id, &serialised_message); 700 | let collect_messages = generate_messages(headers, tag, &serialised_message, &mut message_tracker); 701 | 702 | let get_group_key_response = messages::get_group_key_response::GetGroupKeyResponse { 703 | public_sign_keys : signature_group.get_public_keys() 704 | }; 705 | let mut e = cbor::Encoder::from_memory(); 706 | let _ = e.encode(&[&get_group_key_response]); 707 | let serialised_message_response = e.as_bytes().to_vec(); 708 | let headers_response = signature_group.get_headers(&our_destination, &message_id, 709 | &serialised_message_response); 710 | let response_tag = messages::MessageTypeTag::GetGroupKeyResponse; 711 | let collect_response_messages = generate_messages(headers_response, response_tag, 712 | &serialised_message_response, &mut message_tracker); 713 | 714 | for message in collect_messages { 715 | sentinel_returns.push((message.index, 716 | sentinel.add(message.header, 717 | message.tag, 718 | message.serialised_message, 719 | message.signature))); 720 | } 721 | assert_eq!(types::GROUP_SIZE as usize, sentinel_returns.len()); 722 | assert_eq!(types::GROUP_SIZE as usize, count_none_sentinel_returns(&sentinel_returns)); 723 | assert_eq!(false, verify_exactly_one_response(&sentinel_returns)); 724 | 725 | for message in collect_response_messages { 726 | sentinel_returns.push((message.index, 727 | sentinel.add(message.header, 728 | message.tag, 729 | message.serialised_message, 730 | message.signature))); 731 | } 732 | assert_eq!(2 * types::GROUP_SIZE as usize, sentinel_returns.len()); 733 | assert_eq!(2 * types::GROUP_SIZE as usize - 1, count_none_sentinel_returns(&sentinel_returns)); 734 | assert_eq!(true, verify_exactly_one_response(&sentinel_returns)); 735 | assert_eq!(1, get_selected_sentinel_returns(&mut sentinel_returns, 736 | &mut vec![(types::GROUP_SIZE + types::QUORUM_SIZE) as u64]).len()); 737 | } 738 | 739 | assert_eq!(0, trace_get_keys.count_get_client_key_calls(&signature_group.get_group_address())); 740 | assert_eq!(1, trace_get_keys.count_get_group_key_calls(&signature_group.get_group_address())); 741 | } 742 | 743 | #[test] 744 | fn embedded_add_put_data() { 745 | let our_id = types::Id::new(); 746 | let our_destination = types::DestinationAddress { 747 | dest : our_id.get_name(), 748 | reply_to : None 749 | }; 750 | let embedded_signature_group = EmbeddedSignatureGroup::new(types::GROUP_SIZE as usize, 751 | Authority::NaeManager); 752 | let mut trace_get_keys = TraceGetKeys::new(); 753 | let mut sentinel_returns = Vec::<(u64, Option)>::new(); 754 | let mut message_tracker : u64 = 0; 755 | { 756 | let mut sentinel = Sentinel::new(&mut trace_get_keys); 757 | let data : Vec = generate_data(100usize); 758 | let put_data = messages::put_data::PutData { 759 | name: NameType::new(types::vector_as_u8_64_array(crypto::hash::sha512::hash(&data[..]).0.to_vec())), 760 | data : data 761 | }; 762 | let mut e = cbor::Encoder::from_memory(); 763 | let _ = e.encode(&[&put_data]); 764 | let serialised_message = e.as_bytes().to_vec(); 765 | let message_id = rand::random::() as types::MessageId; 766 | let tag = messages::MessageTypeTag::PutData; 767 | let headers = embedded_signature_group.get_headers(&our_destination, &message_id, &serialised_message); 768 | let collect_messages = generate_messages(headers, tag, &serialised_message, &mut message_tracker); 769 | 770 | let collect_response_messages = embedded_signature_group 771 | .generate_get_group_key_response_messages(&our_destination, 772 | &message_id, 773 | &mut message_tracker); 774 | for message in collect_messages { 775 | sentinel_returns.push((message.index, 776 | sentinel.add(message.header, 777 | message.tag, 778 | message.serialised_message, 779 | message.signature))); 780 | } 781 | assert_eq!(types::GROUP_SIZE as usize, sentinel_returns.len()); 782 | assert_eq!(types::GROUP_SIZE as usize, count_none_sentinel_returns(&sentinel_returns)); 783 | assert_eq!(false, verify_exactly_one_response(&sentinel_returns)); 784 | 785 | for message in collect_response_messages { 786 | sentinel_returns.push((message.index, 787 | sentinel.add(message.header, 788 | message.tag, 789 | message.serialised_message, 790 | message.signature))); 791 | } 792 | assert_eq!(2 * types::GROUP_SIZE as usize, sentinel_returns.len()); 793 | assert_eq!(2 * types::GROUP_SIZE as usize - 1, count_none_sentinel_returns(&sentinel_returns)); 794 | assert_eq!(true, verify_exactly_one_response(&sentinel_returns)); 795 | assert_eq!(1, get_selected_sentinel_returns(&mut sentinel_returns, 796 | &mut vec![(types::GROUP_SIZE + types::QUORUM_SIZE) as u64]).len()); 797 | } 798 | assert_eq!(0, trace_get_keys.count_get_client_key_calls(&embedded_signature_group.get_group_address())); 799 | assert_eq!(1, trace_get_keys.count_get_group_key_calls(&embedded_signature_group.get_group_address())); 800 | } 801 | 802 | #[test] 803 | fn embedded_find_group_response() { 804 | // this sentinel is now the destination 805 | let our_id = types::Id::new(); 806 | let our_destination = types::DestinationAddress { 807 | dest : our_id.get_name(), 808 | reply_to : None 809 | }; 810 | let embedded_signature_group = EmbeddedSignatureGroup::new(types::GROUP_SIZE as usize, 811 | Authority::NaeManager); 812 | let mut trace_get_keys = TraceGetKeys::new(); 813 | let mut sentinel_returns : Vec<(u64, Option)> = Vec::new(); 814 | let mut message_tracker : u64 = 0; 815 | { 816 | let mut sentinel = Sentinel::new(&mut trace_get_keys); 817 | let message_id = rand::random::() as types::MessageId; 818 | let collect_messages = embedded_signature_group 819 | .generate_find_group_response_messages(&our_destination, 820 | &message_id, 821 | &mut message_tracker); 822 | 823 | let collect_response_messages = embedded_signature_group 824 | .generate_get_group_key_response_messages(&our_destination, 825 | &message_id, 826 | &mut message_tracker); 827 | for message in collect_messages { 828 | sentinel_returns.push((message.index, 829 | sentinel.add(message.header, 830 | message.tag, 831 | message.serialised_message, 832 | message.signature))); 833 | } 834 | assert_eq!(types::GROUP_SIZE as usize, sentinel_returns.len()); 835 | assert_eq!(types::GROUP_SIZE as usize, count_none_sentinel_returns(&sentinel_returns)); 836 | assert_eq!(false, verify_exactly_one_response(&sentinel_returns)); 837 | 838 | for message in collect_response_messages { 839 | sentinel_returns.push((message.index, 840 | sentinel.add(message.header, 841 | message.tag, 842 | message.serialised_message, 843 | message.signature))); 844 | } 845 | assert_eq!(2 * types::GROUP_SIZE as usize, sentinel_returns.len()); 846 | assert_eq!(2 * types::GROUP_SIZE as usize - 1, count_none_sentinel_returns(&sentinel_returns)); 847 | assert_eq!(true, verify_exactly_one_response(&sentinel_returns)); 848 | assert_eq!(1, get_selected_sentinel_returns(&mut sentinel_returns, 849 | &mut vec![(types::GROUP_SIZE + types::QUORUM_SIZE) as u64]).len()); 850 | } 851 | assert_eq!(0, trace_get_keys.count_get_client_key_calls(&embedded_signature_group.get_group_address())); 852 | assert_eq!(1, trace_get_keys.count_get_group_key_calls(&embedded_signature_group.get_group_address())); 853 | } 854 | 855 | 856 | 857 | // SentinelMessages 858 | 859 | pub struct SentinelMessages { 860 | ids: Vec, 861 | extras: Vec, 862 | random: Id, 863 | group_keys: Vec>, 864 | client_keys: Vec 865 | } 866 | 867 | impl SentinelMessages { 868 | pub fn new(size: usize)-> SentinelMessages { 869 | assert!(size >= GROUP_SIZE as usize); 870 | let mut ids = Vec::new(); 871 | for _ in 0..size { 872 | ids.push(Id::new()); 873 | } 874 | let mut extras = Vec::new(); 875 | for _ in 1..GROUP_SIZE as usize { 876 | extras.push(Id::new()); 877 | } 878 | 879 | SentinelMessages { 880 | ids: ids, 881 | extras: extras, 882 | random: Id::new(), 883 | group_keys: Vec::new(), 884 | client_keys: Vec::new() 885 | } 886 | } 887 | 888 | fn sort_ids(&mut self, target: GroupAddress) { 889 | self.ids.sort_by( 890 | |a, b| if closer_to_target(&a.get_name(), &b.get_name(), &target) { 891 | cmp::Ordering::Less 892 | } else { 893 | cmp::Ordering::Greater 894 | }); 895 | } 896 | 897 | fn get_ids(&self, size: usize) -> Vec { 898 | assert!(self.ids.len() >= size); 899 | let mut result = Vec::new(); 900 | for i in 0..size { 901 | result.push(self.ids[i].clone()); 902 | } 903 | result 904 | } 905 | 906 | fn get_sorted_ids(&mut self, target: GroupAddress, size: usize) -> Vec { 907 | self.sort_ids(target); 908 | self.get_ids(size) 909 | } 910 | 911 | pub fn group_messages(&mut self, request: T, 912 | tag: MessageTypeTag, 913 | message_id: MessageId, 914 | authority: Authority, 915 | destination: GroupAddress, 916 | source: GroupAddress) -> Vec 917 | where T: Encodable + Decodable + Clone { 918 | let group_size = GROUP_SIZE as usize; 919 | self.sort_ids(source.clone()); 920 | 921 | let mut messages = Vec::new(); 922 | 923 | for i in 0..group_size { 924 | let destination = DestinationAddress{ dest: destination.clone(), reply_to: None }; 925 | let node = self.ids[i].get_name().clone(); 926 | let group = source.clone(); 927 | let source = SourceAddress{ from_node: node, from_group: Some(group), reply_to: None }; 928 | let header = MessageHeader::new(message_id, destination, source, authority.clone()); 929 | let sign_key = self.ids[i].get_crypto_secret_sign_key(); 930 | 931 | messages.push(RoutingMessage::new(tag.clone(), header, request.clone(), &sign_key)); 932 | } 933 | 934 | messages 935 | } 936 | 937 | pub fn fake_messages(&mut self, request: T, 938 | tag: MessageTypeTag, 939 | message_id: MessageId, 940 | authority: Authority, 941 | destination: GroupAddress, 942 | source: GroupAddress) -> Vec 943 | where T: Encodable + Decodable + Clone { 944 | let group_size = GROUP_SIZE as usize; 945 | self.sort_ids(source.clone()); 946 | 947 | let mut messages = Vec::new(); 948 | 949 | let mut rng = thread_rng(); 950 | let range = Range::new(0, group_size); 951 | { 952 | // choose random Id from first GROUP_SIZE sorted Ids... 953 | let index = range.ind_sample(&mut rng); 954 | 955 | let destination = DestinationAddress{ dest: destination.clone(), reply_to: None }; 956 | let node = self.ids[index].get_name().clone(); 957 | let group = source.clone(); 958 | let source = SourceAddress{ from_node: node, from_group: Some(group), reply_to: None }; 959 | let header = MessageHeader::new(message_id, destination, source, authority.clone()); 960 | let sign_key = self.ids[index].get_crypto_secret_sign_key(); 961 | 962 | self.random = self.ids[index].clone(); // ...set 'random' to chosen Id 963 | 964 | messages.push(RoutingMessage::new(tag.clone(), header, request.clone(), &sign_key)); 965 | } 966 | // use 'extras' for remaining messages... 967 | for i in 0..group_size - 1 { 968 | let destination = DestinationAddress{ dest: destination.clone(), reply_to: None }; 969 | let node = self.extras[i].get_name().clone(); 970 | let group = source.clone(); 971 | let source = SourceAddress{ from_node: node, from_group: Some(group), reply_to: None }; 972 | let header = MessageHeader::new(message_id, destination, source, authority.clone()); 973 | let sign_key = self.extras[i].get_crypto_secret_sign_key(); 974 | 975 | messages.push(RoutingMessage::new(tag.clone(), header, request.clone(), &sign_key)); 976 | } 977 | 978 | messages 979 | } 980 | 981 | pub fn group_key_responses(&mut self, message_id: MessageId, 982 | authority: Authority, 983 | destination: GroupAddress, 984 | source: GroupAddress) -> Vec { 985 | let group_size = GROUP_SIZE as usize; 986 | assert!(self.ids.len() >= group_size); 987 | let sorted = self.get_sorted_ids(source.clone(), group_size); 988 | self.group_keys.clear(); 989 | for i in 0..sorted.len() { 990 | let closest = self.get_sorted_ids(sorted[i].get_name(), group_size); 991 | let mut public_ids = Vec::new(); 992 | for j in 0..closest.len() { 993 | public_ids.push(PublicId::new(&closest[j])); 994 | } 995 | self.group_keys.push(public_ids.clone()); 996 | } 997 | 998 | let mut messages = Vec::new(); 999 | 1000 | for i in 0..group_size { 1001 | let mut public_sign_keys = Vec::new(); 1002 | for j in 0..group_size { 1003 | public_sign_keys.push((self.group_keys[i][j].name.clone(), 1004 | self.group_keys[i][j].public_sign_key.clone())); 1005 | } 1006 | 1007 | let group_key_response = GetGroupKeyResponse{ public_sign_keys: public_sign_keys }; 1008 | let destination = DestinationAddress{ dest: destination.clone(), reply_to: None }; 1009 | let node = self.group_keys[i][0].name.clone(); 1010 | let group = source.clone(); 1011 | let source = SourceAddress{ from_node: node, from_group: Some(group), reply_to: None }; 1012 | let tag = MessageTypeTag::GetGroupKeyResponse; 1013 | let header = MessageHeader::new(message_id, destination, source, authority.clone()); 1014 | let sign_key = self.ids[i].get_crypto_secret_sign_key(); 1015 | 1016 | messages.push(RoutingMessage::new(tag, header, group_key_response.clone(), &sign_key)); 1017 | } 1018 | 1019 | messages 1020 | } 1021 | 1022 | pub fn fake_group_keys_responses(&mut self, message_id: MessageId, 1023 | authority: Authority, 1024 | destination: GroupAddress, 1025 | source: GroupAddress) -> Vec { 1026 | let group_size = GROUP_SIZE as usize; 1027 | assert!(self.ids.len() >= group_size); 1028 | let sorted = self.get_sorted_ids(source.clone(), group_size); 1029 | self.group_keys.clear(); 1030 | for i in 0..sorted.len() { 1031 | let closest = self.get_sorted_ids(sorted[i].get_name(), group_size); 1032 | let mut public_ids = Vec::new(); 1033 | for j in 0..closest.len() { 1034 | public_ids.push(PublicId::new(&closest[j])); 1035 | } 1036 | self.group_keys.push(public_ids.clone()); 1037 | } 1038 | 1039 | // append 'extras' and 'random' PublicIds' GROUP_SIZE times... 1040 | for i in 0..group_size { 1041 | let mut public_ids = Vec::new(); 1042 | for j in 0..self.extras.len() { 1043 | public_ids.push(PublicId::new(&self.extras[j])); 1044 | } 1045 | public_ids.push(PublicId::new(&self.random)); 1046 | self.group_keys.push(public_ids.clone()); 1047 | } 1048 | 1049 | let mut messages = Vec::new(); 1050 | 1051 | for i in 0..group_size { 1052 | let mut public_sign_keys = Vec::new(); 1053 | for j in 0..group_size { 1054 | public_sign_keys.push((self.group_keys[i][j].name.clone(), 1055 | self.group_keys[i][j].public_sign_key.clone())); 1056 | } 1057 | 1058 | let group_key_response = GetGroupKeyResponse{ public_sign_keys: public_sign_keys }; 1059 | let destination = DestinationAddress{ dest: destination.clone(), reply_to: None }; 1060 | let node = self.group_keys[i][0].name.clone(); 1061 | let group = source.clone(); 1062 | let source = SourceAddress{ from_node: node, from_group: Some(group), reply_to: None }; 1063 | let tag = MessageTypeTag::GetGroupKeyResponse; 1064 | let header = MessageHeader::new(message_id, destination, source, authority.clone()); 1065 | let sign_key = self.ids[i].get_crypto_secret_sign_key(); 1066 | 1067 | messages.push(RoutingMessage::new(tag, header, group_key_response.clone(), &sign_key)); 1068 | } 1069 | 1070 | let mut index: usize = 0; 1071 | for i in group_size..2 * group_size - 1 { 1072 | let mut public_sign_keys = Vec::new(); 1073 | for j in 0..group_size { 1074 | public_sign_keys.push((self.group_keys[i][j].name.clone(), 1075 | self.group_keys[i][j].public_sign_key.clone())); 1076 | } 1077 | 1078 | let group_key_response = GetGroupKeyResponse{ public_sign_keys: public_sign_keys }; 1079 | let destination = DestinationAddress{ dest: destination.clone(), reply_to: None }; 1080 | let node = self.group_keys[i][index].name.clone(); 1081 | let group = source.clone(); 1082 | let source = SourceAddress{ from_node: node, from_group: Some(group), reply_to: None }; 1083 | let tag = MessageTypeTag::GetGroupKeyResponse; 1084 | let header = MessageHeader::new(message_id, destination, source, authority.clone()); 1085 | let sign_key = self.extras[index].get_crypto_secret_sign_key(); 1086 | 1087 | index += 1usize; 1088 | assert!(index < group_size); // ...don't include 'random' again 1089 | messages.push(RoutingMessage::new(tag, header, group_key_response.clone(), &sign_key)); 1090 | } 1091 | 1092 | messages 1093 | } 1094 | 1095 | } 1096 | 1097 | impl SendGetKeys for SentinelMessages { 1098 | fn get_client_key(&mut self, node_address: NodeAddress) {} 1099 | fn get_group_key(&mut self, group_address: GroupAddress) {} 1100 | } 1101 | 1102 | 1103 | #[test] 1104 | fn ordered_group_messages() { 1105 | // network_size is the number of Id's created for test... 1106 | let network_size = 1000usize; 1107 | let mut sentinel_messages = SentinelMessages::new(network_size); 1108 | let data = generate_data(64usize); 1109 | let name = NameType::new(vector_as_u8_64_array(hash(&data[..]).0.to_vec())); 1110 | let message_id = rand::random::() as types::MessageId; 1111 | let destination = name.clone(); 1112 | let source = NameType::generate_random(); 1113 | let authority = Authority::ClientManager; 1114 | let request = PutData{ name: name.clone(), data: data.clone() }; 1115 | let tag = MessageTypeTag::PutData; 1116 | 1117 | let group_messages = 1118 | sentinel_messages.group_messages( 1119 | request, 1120 | tag, 1121 | message_id, 1122 | authority.clone(), 1123 | destination.clone(), 1124 | source.clone()); 1125 | 1126 | let group_keys_responses = 1127 | sentinel_messages.group_key_responses( 1128 | message_id, 1129 | authority.clone(), 1130 | destination.clone(), 1131 | source.clone()); 1132 | 1133 | { 1134 | let mut resolved = None; 1135 | let mut sentinel = Sentinel::new(&mut sentinel_messages); 1136 | 1137 | for msg in group_messages { 1138 | resolved = 1139 | sentinel.add( 1140 | msg.message_header, 1141 | msg.message_type, 1142 | msg.serialised_body, 1143 | msg.signature); 1144 | 1145 | assert!(resolved.is_none()); 1146 | } 1147 | for keys in group_keys_responses { 1148 | resolved = 1149 | sentinel.add( 1150 | keys.message_header, 1151 | keys.message_type, 1152 | keys.serialised_body, 1153 | keys.signature); 1154 | 1155 | if resolved.is_some() { 1156 | break; 1157 | } 1158 | } 1159 | 1160 | assert!(resolved.is_some()); 1161 | } 1162 | } 1163 | 1164 | #[test] 1165 | fn unordered_group_messages() { 1166 | // network_size is the number of Id's created for test... 1167 | let network_size = 1000usize; 1168 | let mut sentinel_messages = SentinelMessages::new(network_size); 1169 | let data = generate_data(64usize); 1170 | let name = NameType::new(vector_as_u8_64_array(hash(&data[..]).0.to_vec())); 1171 | let message_id = rand::random::() as types::MessageId; 1172 | let destination = name.clone(); 1173 | let source = NameType::generate_random(); 1174 | let authority = Authority::ClientManager; 1175 | let request = PutData{ name: name.clone(), data: data.clone() }; 1176 | let tag = MessageTypeTag::PutData; 1177 | 1178 | let mut group_messages = 1179 | sentinel_messages.group_messages( 1180 | request, 1181 | tag, 1182 | message_id, 1183 | authority.clone(), 1184 | destination.clone(), 1185 | source.clone()); 1186 | 1187 | let mut group_keys_responses = 1188 | sentinel_messages.group_key_responses( 1189 | message_id, 1190 | authority.clone(), 1191 | destination.clone(), 1192 | source.clone()); 1193 | 1194 | { 1195 | let mut rng = thread_rng(); 1196 | 1197 | rng.shuffle(&mut group_messages[..]); 1198 | rng.shuffle(&mut group_keys_responses[..]); 1199 | 1200 | let mut sentinel = Sentinel::new(&mut sentinel_messages); 1201 | let mut rand: usize = rng.gen(); 1202 | let mut message_index = rand % group_messages.len(); 1203 | 1204 | let msg = group_messages.remove(message_index); 1205 | let mut resolved = 1206 | sentinel.add( 1207 | msg.message_header, 1208 | msg.message_type, 1209 | msg.serialised_body, 1210 | msg.signature); 1211 | 1212 | assert!(resolved.is_none()); 1213 | 1214 | loop { 1215 | if group_messages.is_empty() && group_keys_responses.is_empty() { 1216 | break; 1217 | } 1218 | let messages_empty = group_messages.is_empty(); 1219 | let group_keys_responses_empty = group_keys_responses.is_empty(); 1220 | let mut group_keys_index; 1221 | 1222 | if !messages_empty { 1223 | rand = rng.gen(); 1224 | message_index = rand % group_messages.len(); 1225 | } else { 1226 | message_index = 1usize; 1227 | } 1228 | 1229 | if !group_keys_responses_empty { 1230 | rand = rng.gen(); 1231 | group_keys_index = rand % group_keys_responses.len(); 1232 | } else { 1233 | group_keys_index = 0usize; 1234 | } 1235 | 1236 | if (message_index % 2usize != 0) && !group_keys_responses_empty { 1237 | let keys = group_keys_responses.remove(group_keys_index); 1238 | resolved = 1239 | sentinel.add( 1240 | keys.message_header, 1241 | keys.message_type, 1242 | keys.serialised_body, 1243 | keys.signature); 1244 | 1245 | if resolved.is_some() { 1246 | break; 1247 | } 1248 | } else { 1249 | if group_keys_responses_empty { 1250 | rand = rng.gen(); 1251 | message_index = rand % group_messages.len(); 1252 | } 1253 | let msg = group_messages.remove(message_index); 1254 | resolved = 1255 | sentinel.add( 1256 | msg.message_header, 1257 | msg.message_type, 1258 | msg.serialised_body, 1259 | msg.signature); 1260 | 1261 | if resolved.is_some() { 1262 | break; 1263 | } 1264 | } 1265 | } 1266 | 1267 | assert!(resolved.is_some()); 1268 | } 1269 | } 1270 | 1271 | #[test] 1272 | #[ignore] 1273 | fn fake_messages() { 1274 | // network_size is the number of Id's created for test... 1275 | let network_size = 1000usize; 1276 | let mut sentinel_messages = SentinelMessages::new(network_size); 1277 | let data = generate_data(64usize); 1278 | let name = NameType::new(vector_as_u8_64_array(hash(&data[..]).0.to_vec())); 1279 | let message_id = rand::random::() as types::MessageId; 1280 | let destination = name.clone(); 1281 | let source = NameType::generate_random(); 1282 | let authority = Authority::ClientManager; 1283 | let request = PutData{ name: name.clone(), data: data.clone() }; 1284 | let tag = MessageTypeTag::PutData; 1285 | 1286 | let mut fake_messages = 1287 | sentinel_messages.fake_messages( 1288 | request, 1289 | tag, 1290 | message_id, 1291 | authority.clone(), 1292 | destination.clone(), 1293 | source.clone()); 1294 | 1295 | let mut fake_group_keys_responses = 1296 | sentinel_messages.fake_group_keys_responses( 1297 | message_id, 1298 | authority.clone(), 1299 | destination.clone(), 1300 | source.clone()); 1301 | 1302 | { 1303 | let mut rng = thread_rng(); 1304 | 1305 | rng.shuffle(&mut fake_messages[..]); 1306 | rng.shuffle(&mut fake_group_keys_responses[..]); 1307 | 1308 | let mut sentinel = Sentinel::new(&mut sentinel_messages); 1309 | let mut rand: usize = rng.gen(); 1310 | let mut message_index = rand % fake_messages.len(); 1311 | 1312 | let msg = fake_messages.remove(message_index); 1313 | let mut resolved = 1314 | sentinel.add( 1315 | msg.message_header, 1316 | msg.message_type, 1317 | msg.serialised_body, 1318 | msg.signature); 1319 | 1320 | assert!(resolved.is_none()); 1321 | 1322 | loop { 1323 | if fake_messages.is_empty() && fake_group_keys_responses.is_empty() { 1324 | break; 1325 | } 1326 | let fake_messages_empty = fake_messages.is_empty(); 1327 | let fake_group_keys_responses_empty = fake_group_keys_responses.is_empty(); 1328 | let mut group_keys_index; 1329 | 1330 | if !fake_messages_empty { 1331 | rand = rng.gen(); 1332 | message_index = rand % fake_messages.len(); 1333 | } else { 1334 | message_index = 1usize; 1335 | } 1336 | 1337 | if !fake_group_keys_responses_empty { 1338 | rand = rng.gen(); 1339 | group_keys_index = rand % fake_group_keys_responses.len(); 1340 | } else { 1341 | group_keys_index = 0usize; 1342 | } 1343 | 1344 | if (message_index % 2usize != 0) && !fake_group_keys_responses_empty { 1345 | let keys = fake_group_keys_responses.remove(group_keys_index); 1346 | resolved = 1347 | sentinel.add( 1348 | keys.message_header, 1349 | keys.message_type, 1350 | keys.serialised_body, 1351 | keys.signature); 1352 | 1353 | if resolved.is_some() { 1354 | break; 1355 | } 1356 | } else { 1357 | if fake_group_keys_responses_empty { 1358 | rand = rng.gen(); 1359 | message_index = rand % fake_messages.len(); 1360 | } 1361 | let msg = fake_messages.remove(message_index); 1362 | resolved = 1363 | sentinel.add( 1364 | msg.message_header, 1365 | msg.message_type, 1366 | msg.serialised_body, 1367 | msg.signature); 1368 | 1369 | if resolved.is_some() { 1370 | break; 1371 | } 1372 | } 1373 | } 1374 | 1375 | assert!(resolved.is_none()); 1376 | } 1377 | } 1378 | 1379 | } 1380 | -------------------------------------------------------------------------------- /docs/sentinel.md: -------------------------------------------------------------------------------- 1 | #Sentinel overview 2 | 3 | ## Quick intro to network consensus, authority and crypto usage. 4 | 5 | In a decentralised and autonomous network there are many challenges to face. One such challenge is the range of attacks that consist of Sybil / Sparticus and Forgery attacks (did the message really come from who you think). One of the simplest attack to foil is the forgery attack, thanks to asymmetric cryptography. This allows for a public key to be known by everyone and when anything is encrypted with this key it can only (supposedly) be decrypted by the private key of that key pair. Assuming a reasonable algorithm, adequate key size and an effective implementation, this holds true. 6 | 7 | This also removes the Sparticus type attacks (claim to be another identity), but not necessarily Sybil attacks, where an attack on a section of a network is enough to persuade the rest of the network that any request is valid, or indeed, anything asked of that part of the network is genuine. To overcome this, several techniques are used in parallel, these are: 8 | 9 | 1. Have nodes create key chains (a chain of keys each signing the next until one is selected). We call these Fobs. A PublicFob consists of a public_key, a signature and a name field. The name is the SHA512HASH(public_key+signature), making forging a key very difficult (we can confirm the signature is also signed by a valid key pair by checking the signature, where this 'pure key' is self signed). The Fob type is this PublicFob + the private key. 10 | 11 | 2: Ask the network to store the PublicFob for a node. The network will accept this if the node has certain characteristics (based on rank) and the key has less than three leading bits that are different from the current group of nodes. This ensures key placement distributes equally across the address range, With regard to rank, consider only a single non-ranked node allowed per group (more on groups in point four). Failure to increase rank means that the key is deleted from the network and has to be re-stored. 12 | 13 | 3. This now resembles a PKI network where to speak to node ABC, the PublicFob at ABC must be retrieved, and to ensure validity, a message encrypted to the node. Alternatively, checking a message from the node is signed using that PublicFob.public_key would also ensure authenticity. This implementation is unique as no central authority exists and the network distributes and collects keys, as any DHT would, except in this case the DHT is secured by the very PKI it manages. In short, this is very secure implementation and does not require any human intervention, unlike a certificate authority. 14 | 15 | 4. Assemble nodes into groups that will act in unison on any request/response. Groups are selected to be large enough to ensure a Sybil attack would require at least 3X network size of attackers to be able to join (a single attacker with no other node types joining) the network. Each group requires 28 of 32 (the close group size) to reach consensus. 16 | 17 | 5. Allow a failure rate, as failures will definitely happen. This is implemented by having a GroupSize of say 32 and a QuorumSize of 28. This means for any action we require 28 nodes close to a target address to agree and carry out an action. 18 | 19 | This Quorum creates a mechanism where another group or node can confirm a network state. This is called group consensus. 20 | 21 | The group consensus provides the network a way to request or carry out actions and ensure requests are valid and actions completed. This is required as the network is self regulating and autonomous. 22 | 23 | A client has a close group and requires to persuade this group to request the network take an action which *Puts* something on the network (a data element/message etc.) Clients create data and messages, the network handles these. As the client cannot just connect to an arbitrary group and demand something be done, they connect to their close group and register themselves (with their Fob) an account. The close group can then be persuaded by the client to request another part of the network create something (a Put). In the case of the SAFE Network, the close group requests the client pay via safecoin (the crypto currency/network token of the SAFE Network) to put data. 24 | 25 | In short, a client can sign request to the group (crypto secure) and the group can check validity of the request and then ask the appropriate group close to the address of the data, or message, to accept this request. 26 | 27 | After anything is put, the client can mutate certain types of data directly (if they have signed it). This is the case for directory entries, where a client can add versions to a list (StructuredDataVersion) as it was put signed by the client. So, the owner of the signature can sign a request to alter directory entries. This is crypto secured authority and does not require the close group for consensus. 28 | 29 | In the case of groups requesting actions, the SAFE Network employs group based consensus. The network grants authority based on a group that can be measured as a valid close group, where each member has signed a request confirming membership of that close group. This authority is what the sentinel confirms prior to the routing object processing an action request. Almost all messages are checked by the Sentinel, with the exception of get_group, as this fetches Fobs which are self-validating and fetch a copy of all Fobs from all group members, confirming they agree and validate. Get_group is only used for making sure we connect to our close group as a client or node. 30 | 31 | ##Sentinel components 32 | 33 | The sentinel consists of few components and requires no network connection. This is to allow crucial elements to be fully tested. The elements are limited to two accumulator pairs, with each pair represents a different authority type: 34 | 35 | 1. Node level direct authority (i.e. could be a client) 36 | 37 | 2. Group base consensus 38 | 39 | In 1 we just accumulate a single message and get the Fob to check a signature. 40 | In 2 we require to get at least QuorumSize messages, for group based consensus, before retrieving the Fobs to check signatures and confirm the group. We also check the nodes are as close to each other in XOR space as our own group (with varying error rate). The process is as follows: 41 | 42 | 1. Message Arrives 43 | 44 | 2. Check Accumulator has seen it, if not Send a GetKey request (for a group or single node) 45 | 46 | 3. Add to accumulator. If return is true then check the key accumulator of that pair -> if true then confirm the signature with the Fob (asymm::CheckSignature(Fob.public_key, message) 47 | 48 | If the key accumulator did not have the key(s) accumulated (i.e. accumulator.CheckQuorumReached) the network takes no action. Alternatively: 49 | 50 | 1. The key arrives (from GetKey response) 51 | 52 | 2. Check value accumulators have(address). The address is the source_id+messge_id of the request and may be a group ID or nodeId 53 | 54 | 3. If not found then ignore message 55 | 56 | 4. Otherwise accumulator.Add(key) to the proper key accumulator of the pair 57 | 58 | 5. If this returns true, the keys and value (via accumulator.GetAll() calls are received from both accumulators and signatures are confirmed. The group returns a valid message to the object holding the sentinel (the sentinel add call will be async) 59 | 60 | The accumulators are LRU cache based and will empty old messages that do not confirm in this manner. 61 | 62 | ## One Explicit Example 63 | 64 | < Client { 65 | Generate payload 66 | Sign payload // currently not the case 67 | Generate message (payload, signature) 68 | Sign message 69 | Assign message id 70 | Generate header (message id, signature, source={client node, no group}) 71 | Send to Client Manager 72 | } 73 | | Client Manager { 74 | Filter on message id + source=client node 75 | Swarm 76 | (Handle pre-sentinel skipped, only for GetGroupKey, GetKey, PutKey) 77 | Sentinel { 78 | Receive single message 79 | GetKey 80 | - to this Client Manager group 81 | - from each manager, to all other managers 82 | - preserve message id 83 | - add signature 84 | - from_authority = Client Manager 85 | { 86 | Filter on same message id + source=group node from client manager 87 | --> add MessageTypeTag to FilterValue 88 | --> add from_authority to FilterValue 89 | Swarm 90 | Handle pre-sentinel { 91 | GetKey-> 92 | GetKeyResponse (preserve message id, Group Keys + Client Key, 93 | // original signature from GetKey) 94 | } 95 | } 96 | Accumulate original message and GetKeyResponses 97 | (only if we have called for it) 98 | Merge keys to verify group 99 | Check signature of client 100 | Return Sentinel 101 | } 102 | Handle Message in Persona 103 | Send to NAE Manager, preserve message id 104 | } 105 | | NAE Manager { 106 | Filter on message id + source = client manager node + MessageTypeTag 107 | Swarm 108 | (Handle pre-sentinel skipped) 109 | Sentinel { 110 | Receive first message from group 111 | GetGroupKey 112 | - to Client Manager group (target_id) 113 | - preserve message id 114 | - add signature 115 | - from_authority = NAE-manager 116 | { 117 | Filter in Client Manager node on same message_id 118 | + source = NAE-node 119 | + from_authority = NAE_manager 120 | + MessageTypeTag 121 | Swarm 122 | Handle pre-sentinel { 123 | GetGroupKey-> 124 | GetGroupKeyResponse (preserve message id, Group Keys, 125 | // original signature from GetGroupKey) 126 | 127 | } 128 | } 129 | Accumulate original message and GetKeyResponse (one per source.node) 130 | (only if we have called for it) 131 | Merge keys to verify group 132 | Return Sentinel 133 | } 134 | Handle Message in Persona 135 | } 136 | > 137 | -------------------------------------------------------------------------------- /src/key_sentinel.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015 MaidSafe.net limited. 2 | // 3 | // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, 4 | // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which 5 | // licence you accepted on initial access to the Software (the "Licences"). 6 | // 7 | // By contributing code to the SAFE Network Software, or to this project generally, you agree to be 8 | // bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the 9 | // Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR. 10 | // 11 | // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed 12 | // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. 14 | // 15 | // Please review the Licences for the specific language governing permissions and limitations 16 | // relating to use of the SAFE Network Software. 17 | 18 | use lru_time_cache::LruCache; 19 | use sodiumoxide::crypto::sign; 20 | use std::collections::{BTreeMap, BTreeSet}; 21 | use key_store::KeyStore; 22 | use std::marker::PhantomData; 23 | use std::fmt::Debug; 24 | use super::{SerialisedClaim, verify_signature}; 25 | use wrappers::SignW; 26 | 27 | #[allow(dead_code)] 28 | const MAX_REQUEST_COUNT: usize = 1000; 29 | 30 | type Map = BTreeMap; 31 | type Set = BTreeSet; 32 | 33 | pub trait IdTrait { 34 | fn name(&self) -> NameType; 35 | fn public_key(&self) -> sign::PublicKey; 36 | } 37 | 38 | pub trait GroupClaimTrait { 39 | fn group_identities(&self) -> Vec; 40 | } 41 | 42 | #[allow(dead_code)] 43 | pub struct KeySentinel 44 | where Request: Eq + PartialOrd + Ord + Clone, 45 | Name: Eq + PartialOrd + Ord + Clone + Debug, 46 | IdType: Eq + PartialOrd + Ord + Clone + IdTrait, 47 | GroupClaim: Eq + PartialOrd + Ord + Clone + GroupClaimTrait 48 | { 49 | cache: LruCache, Map>)>, 50 | phantom: PhantomData, 51 | } 52 | 53 | impl KeySentinel 54 | where Request: Eq + PartialOrd + Ord + Clone, 55 | Name: Eq + PartialOrd + Ord + Clone + Debug, 56 | IdType: Eq + PartialOrd + Ord + Clone + IdTrait, 57 | GroupClaim: Eq + PartialOrd + Ord + Clone + GroupClaimTrait, { 58 | 59 | #[allow(dead_code)] 60 | pub fn new() -> KeySentinel { 61 | KeySentinel { cache: LruCache::with_capacity(MAX_REQUEST_COUNT), phantom: PhantomData } 62 | } 63 | 64 | #[allow(dead_code)] 65 | pub fn add_identities(&mut self, 66 | request: Request, 67 | sender: Name, 68 | serialised: SerialisedClaim, 69 | signature: sign::Signature, 70 | claim: GroupClaim, 71 | quorum_size: usize) 72 | -> Option<(Request, Vec)> { 73 | 74 | let retval = { 75 | let keys_and_claims = self.cache.entry(request.clone()) 76 | .or_insert_with(||(KeyStore::new(), Map::new())); 77 | 78 | let ref mut keys = &mut keys_and_claims.0; 79 | let ref mut claims = &mut keys_and_claims.1; 80 | 81 | for id in claim.group_identities() { 82 | keys.add_key(id.name(), sender.clone(), id.public_key()); 83 | } 84 | 85 | claims.entry(sender).or_insert_with(||Set::new()) 86 | .insert((claim, serialised, SignW(signature))); 87 | 88 | Self::try_selecting_group(keys, claims, quorum_size) 89 | .map(|ids|(request, ids)) 90 | }; 91 | 92 | retval.map(|(request, ids)| { 93 | self.cache.remove(&request); 94 | (request, ids) 95 | }) 96 | } 97 | 98 | fn try_selecting_group(key_store: &mut KeyStore, 99 | claims: &Map>, 100 | quorum_size: usize) 101 | -> Option> { 102 | 103 | let verified_claims = claims.iter().filter_map(|(name, claims)| { 104 | for &(ref claim, ref serialised, ref signature) in claims { 105 | if Self::verify_claim(name, key_store, serialised, &(signature.0), quorum_size) { 106 | return Some(claim); 107 | } 108 | } 109 | None 110 | }).collect::>(); 111 | 112 | if verified_claims.len() < quorum_size { 113 | return None; 114 | } 115 | 116 | Some(verified_claims.iter().flat_map(|claim| claim.group_identities()).collect()) 117 | } 118 | 119 | fn verify_claim(author: &Name, 120 | key_store: &mut KeyStore, 121 | serialised: &SerialisedClaim, 122 | signature: &sign::Signature, 123 | quorum_size: usize) 124 | -> bool { 125 | for public_key in key_store.get_accumulated_keys(&author, quorum_size) { 126 | if verify_signature(signature, &public_key, serialised).is_some() { 127 | return true; 128 | } 129 | } 130 | false 131 | } 132 | } 133 | 134 | #[cfg(test)] 135 | mod test { 136 | use super::*; 137 | use rand::random; 138 | use sodiumoxide::crypto::sign; 139 | 140 | const MESSAGE_SIZE: usize = 4; 141 | const QUORUM: usize = 10; 142 | 143 | #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug)] 144 | pub struct TestName(pub u32); 145 | 146 | fn generate_random_message() -> Vec { 147 | let mut arr = [0u8;MESSAGE_SIZE]; 148 | for i in (0..MESSAGE_SIZE) { 149 | arr[i] = random::(); 150 | } 151 | arr.to_vec() 152 | } 153 | 154 | #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug)] 155 | struct TestRequest { 156 | core: usize, 157 | name: TestName, 158 | } 159 | 160 | impl TestRequest { 161 | pub fn new(core: usize, name: TestName) -> TestRequest { 162 | TestRequest { core: core, name: name } 163 | } 164 | } 165 | 166 | #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)] 167 | struct TestIdType { 168 | name: TestName, 169 | public_key: [u8; sign::PUBLICKEYBYTES], 170 | } 171 | 172 | impl IdTrait for TestIdType { 173 | fn name(&self) -> TestName { 174 | self.name.clone() 175 | } 176 | 177 | fn public_key(&self) -> sign::PublicKey { 178 | sign::PublicKey(self.public_key) 179 | } 180 | } 181 | 182 | #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)] 183 | struct TestGroupClaim { 184 | identities: Vec, 185 | } 186 | 187 | impl TestGroupClaim { 188 | pub fn new(identities: Vec) -> TestGroupClaim { 189 | TestGroupClaim { identities: identities } 190 | } 191 | } 192 | 193 | impl GroupClaimTrait for TestGroupClaim { 194 | fn group_identities(&self) -> Vec { 195 | self.identities.clone() 196 | } 197 | } 198 | 199 | #[test] 200 | fn key_sentinel() { 201 | let mut sentinel: KeySentinel = 202 | KeySentinel::new(); 203 | 204 | let random_message = generate_random_message(); 205 | let mut names = Vec::new(); 206 | let mut pubs = Vec::new(); 207 | let mut signatures = Vec::new(); 208 | 209 | for i in 0..QUORUM + 1 { 210 | let key_pair = sign::gen_keypair(); 211 | 212 | names.push(TestName(i as u32)); 213 | pubs.push(key_pair.0); 214 | signatures.push(sign::sign_detached(&random_message, &key_pair.1)); 215 | } 216 | 217 | let request = TestRequest::new(random::(), TestName((QUORUM + 1) as u32)); 218 | 219 | let name_pubs = names.iter().zip(pubs.iter()) 220 | .map(|(ref name, ref public_key)| 221 | TestIdType { name: (*name).clone(), 222 | public_key: public_key.clone().0 }) 223 | .collect::>(); 224 | 225 | for index in 0..QUORUM + 1 { 226 | let group_claim = TestGroupClaim::new(name_pubs.clone()); 227 | 228 | if index < QUORUM { 229 | assert!(sentinel.add_identities(request.clone(), 230 | names[index].clone(), 231 | random_message.clone(), 232 | signatures[index].clone(), 233 | group_claim, 234 | QUORUM).is_none()); 235 | continue; 236 | } 237 | 238 | assert!(sentinel.add_identities(request.clone(), 239 | names[QUORUM].clone(), 240 | random_message.clone(), 241 | signatures[QUORUM].clone(), 242 | group_claim, 243 | QUORUM).is_some()); 244 | } 245 | } 246 | } 247 | -------------------------------------------------------------------------------- /src/key_store.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015 MaidSafe.net limited. 2 | // 3 | // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, 4 | // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which 5 | // licence you accepted on initial access to the Software (the "Licences"). 6 | // 7 | // By contributing code to the SAFE Network Software, or to this project generally, you agree to be 8 | // bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the 9 | // Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR. 10 | // 11 | // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed 12 | // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. 14 | // 15 | // Please review the Licences for the specific language governing permissions and limitations 16 | // relating to use of the SAFE Network Software. 17 | 18 | use sodiumoxide::crypto::sign; 19 | use lru_time_cache::LruCache; 20 | use std::collections::{BTreeMap, BTreeSet}; 21 | 22 | const NAME_CAPACITY: usize = 1000; 23 | 24 | // FIXME: We only work with KeyData and not PublicKey directly 25 | // because PublicKey doesn't derive from Ord in the current version of 26 | // sodiumdioxide library. Once that library is bumped to version 0.0.6 27 | // or above, we should be able to get rid of KeyData and the re-wrapping. 28 | type KeyData = [u8; sign::PUBLICKEYBYTES]; 29 | type Map = BTreeMap; 30 | type Set = BTreeSet; 31 | 32 | #[derive(Clone)] 33 | pub struct KeyStore 34 | where Name: Eq + PartialOrd + Ord + Clone 35 | { 36 | // +--- Target +--- Sender 37 | // V V 38 | cache: LruCache>>, 39 | } 40 | 41 | impl KeyStore where Name: Eq + PartialOrd + Ord + Clone { 42 | pub fn new() -> KeyStore { 43 | KeyStore { cache: LruCache::with_capacity(NAME_CAPACITY) } 44 | } 45 | 46 | pub fn add_key(&mut self, target: Name, sender: Name, key: sign::PublicKey) { 47 | // No self signing. 48 | if target == sender { 49 | return; 50 | } 51 | 52 | let new_map = || Map::>::new(); 53 | let new_set = || Set::::new(); 54 | 55 | self.cache.entry(target).or_insert_with(new_map) 56 | .entry(key.0).or_insert_with(new_set) 57 | .insert(sender); 58 | } 59 | 60 | #[allow(dead_code)] 61 | pub fn len(&self) -> usize { 62 | self.cache.len() 63 | } 64 | 65 | /// Returns a vector of keys belonging to `target`, for whom we've received the key 66 | /// from at least a quorum size of unique senders. 67 | pub fn get_accumulated_keys(&mut self, 68 | target: &Name, 69 | quorum_size: usize) 70 | -> Vec { 71 | // Create temp variable to workaround a borrow checker bug 72 | // http://blog.ezyang.com/2013/12/two-bugs-in-the-borrow-checker-every-rust-developer-should-know-about/ 73 | self.cache.get(target) 74 | .iter().flat_map(|keys| Self::pick_where_quorum_reached(keys, quorum_size)) 75 | .cloned().map(sign::PublicKey) 76 | .collect::<_>() 77 | } 78 | 79 | fn pick_where_quorum_reached<'a>(keys: &'a Map>, 80 | quorum: usize) 81 | -> Vec<&'a KeyData> { 82 | keys.iter().filter_map(|(key, sender_set)| { 83 | if sender_set.len() >= quorum { Some(key) } else { None } 84 | }).collect::<_>() 85 | } 86 | } 87 | 88 | #[cfg(test)] 89 | mod test { 90 | use super::*; 91 | use sodiumoxide::crypto::sign; 92 | use rand::random; 93 | 94 | type NameType = u8; 95 | const QUORUM: usize = 6; 96 | 97 | fn random_key() -> sign::PublicKey { 98 | let mut arr = [0u8;sign::PUBLICKEYBYTES]; 99 | for i in (0..sign::PUBLICKEYBYTES) { 100 | arr[i] = random::(); 101 | } 102 | sign::PublicKey(arr) 103 | } 104 | 105 | fn add_noise(ks: &mut KeyStore, target: NameType, quantity: usize) { 106 | for _ in (0..quantity) { 107 | ks.add_key(target, random::(), random_key()); 108 | } 109 | } 110 | 111 | #[test] 112 | fn quorum_reached() { 113 | let target: NameType = 0; 114 | let mut ks = KeyStore::::new(); 115 | let valid_key = random_key(); 116 | 117 | add_noise(&mut ks, target, 1000); 118 | 119 | for i in (1..QUORUM + 1) { 120 | ks.add_key(target, i as NameType, valid_key); 121 | 122 | if i < QUORUM { 123 | assert!(ks.get_accumulated_keys(&target, QUORUM).is_empty()); 124 | } else { 125 | assert!(!ks.get_accumulated_keys(&target, QUORUM).is_empty()); 126 | } 127 | } 128 | } 129 | 130 | #[test] 131 | fn no_self_sign() { 132 | let target: NameType = 0; 133 | let mut ks = KeyStore::::new(); 134 | let valid_key = random_key(); 135 | 136 | add_noise(&mut ks, target, 1000); 137 | 138 | // Node zero sends signature for zero, that shouldn't be valid. 139 | for i in (0..QUORUM) { 140 | ks.add_key(target, i as NameType, valid_key); 141 | assert!(ks.get_accumulated_keys(&target, QUORUM).is_empty()); 142 | } 143 | } 144 | 145 | #[test] 146 | fn successful_attack() { 147 | let target: NameType = 0; 148 | let mut ks = KeyStore::::new(); 149 | let valid_key1 = random_key(); 150 | let valid_key2 = random_key(); 151 | 152 | add_noise(&mut ks, target, 1000); 153 | 154 | for i in (1..QUORUM + 1) { 155 | ks.add_key(target, i as NameType, valid_key1); 156 | 157 | if i < QUORUM { 158 | assert!(ks.get_accumulated_keys(&target, QUORUM).len() == 0); 159 | } else { 160 | assert!(ks.get_accumulated_keys(&target, QUORUM).len() == 1); 161 | } 162 | } 163 | 164 | for i in (1..QUORUM + 1) { 165 | ks.add_key(target, i as NameType, valid_key2); 166 | 167 | if i < QUORUM { 168 | assert!(ks.get_accumulated_keys(&target, QUORUM).len() == 1); 169 | } else { 170 | assert!(ks.get_accumulated_keys(&target, QUORUM).len() == 2); 171 | } 172 | } 173 | } 174 | 175 | } 176 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015 MaidSafe.net limited. 2 | // 3 | // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, 4 | // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which 5 | // licence you accepted on initial access to the Software (the "Licences"). 6 | // 7 | // By contributing code to the SAFE Network Software, or to this project generally, you agree to be 8 | // bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the 9 | // Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR. 10 | // 11 | // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed 12 | // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. 14 | // 15 | // Please review the Licences for the specific language governing permissions and limitations 16 | // relating to use of the SAFE Network Software. 17 | 18 | //! Sentinel cryptographically confirms the origin of a claim in a decentralised network. 19 | //! 20 | //! A claim has to implement Claimable in order to be verifiable and mergeable. 21 | //! A request has to implement GetSigningKeys such that Sentinel can acquire 22 | //! the necessary public signing keys. 23 | //! The request is passed immutably through sentinel 24 | //! and is used as a key to group claims and corresponding keys. 25 | //! When sentinel resolves a threshold on verified and merged message, 26 | //! it returns the requester key and the merged claim. 27 | //! Claimant names and associated signatures are discarded after successful resolution, 28 | //! as such abstracting the original request into a resolved claim. 29 | //! 30 | //! The keys_threshold specifies a minimal threshold on the number of independent mentions of 31 | //! a single public signing key needed to consider it for verifying a claim. This threshold 32 | //! can be one or higher. 33 | //! The claims_threshold specifies a minimal threshold on the number of verified claims before 34 | //! sentinel will attempt to merge these verified claims. 35 | 36 | #![doc(html_logo_url = 37 | "https://raw.githubusercontent.com/maidsafe/QA/master/Images/maidsafe_logo.png", 38 | html_favicon_url = "http://maidsafe.net/img/favicon.ico", 39 | html_root_url = "http://maidsafe.github.io/sentinel")] 40 | 41 | // For explanation of lint checks, run `rustc -W help` or see 42 | // https://github.com/maidsafe/QA/blob/master/Documentation/Rust%20Lint%20Checks.md 43 | #![forbid(bad_style, exceeding_bitshifts, mutable_transmutes, no_mangle_const_items, 44 | unknown_crate_types, warnings)] 45 | #![deny(deprecated, drop_with_repr_extern, improper_ctypes, missing_docs, 46 | non_shorthand_field_patterns, overflowing_literals, plugin_as_library, 47 | private_no_mangle_fns, private_no_mangle_statics, raw_pointer_derive, stable_features, 48 | unconditional_recursion, unknown_lints, unsafe_code, unused, unused_allocation, 49 | unused_attributes, unused_comparisons, unused_features, unused_parens, while_true)] 50 | #![warn(trivial_casts, trivial_numeric_casts, unused_extern_crates, unused_import_braces, 51 | unused_qualifications, unused_results, variant_size_differences)] 52 | #![allow(box_pointers, fat_ptr_transmutes, missing_copy_implementations, 53 | missing_debug_implementations)] 54 | 55 | extern crate rustc_serialize; 56 | extern crate accumulator; 57 | extern crate lru_time_cache; 58 | extern crate sodiumoxide; 59 | extern crate cbor; 60 | extern crate rand; 61 | 62 | use sodiumoxide::crypto; 63 | use sodiumoxide::crypto::sign::verify_detached; 64 | use sodiumoxide::crypto::sign::PublicKey; 65 | use sodiumoxide::crypto::sign::Signature; 66 | 67 | pub type SerialisedClaim = Vec; 68 | 69 | /// Sentinel provides a consensus mechanism on all content messages. 70 | /// The claims made must be identical and cryptographically signed. 71 | pub mod pure_sentinel; 72 | mod key_store; 73 | pub mod key_sentinel; 74 | mod wrappers; 75 | mod refresh_sentinel; 76 | mod statistics; 77 | 78 | fn verify_signature(signature: &Signature, 79 | public_key: &PublicKey, 80 | claim: &SerialisedClaim) 81 | -> Option { 82 | 83 | match crypto::sign::verify_detached(&signature, claim, public_key) { 84 | true => Some(claim.clone()), 85 | false => None, 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/pure_sentinel.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015 MaidSafe.net limited. 2 | // 3 | // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, 4 | // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which 5 | // licence you accepted on initial access to the Software (the "Licences"). 6 | // 7 | // By contributing code to the SAFE Network Software, or to this project generally, you agree to be 8 | // bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the 9 | // Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR. 10 | // 11 | // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed 12 | // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. 14 | // 15 | // Please review the Licences for the specific language governing permissions and limitations 16 | // relating to use of the SAFE Network Software. 17 | 18 | //! PureSentinel cryptographically confirms the origin of a claim in a decentralised network. 19 | //! 20 | //! A claim has to implement Claimable in order to be verifiable and mergeable. 21 | //! A request has to implement GetSigningKeys such that PureSentinel can aqcuire 22 | //! the necessary public signing keys. 23 | //! The request is passed immutably through pure sentinel 24 | //! and is used as a key to group claims and corresponding keys. 25 | //! When pure sentinel resolves a threshold on verified and merged message, 26 | //! it returns the requestor key and the merged claim. 27 | //! Claimant names and associated signatures are discarded after succesful resolution, 28 | //! as such abstracting the original request into a resolved claim. 29 | //! 30 | //! The keys_threshold specifies a minimal threshold on the number of independent mentions of 31 | //! a single public signing key needed to consider it for verifying a claim. This threshold 32 | //! can be one or higher. 33 | //! The claims_threshold specifies a minimal threshold on the number of verified claims before 34 | //! pure sentinel will attempt to merge these verified claims. 35 | 36 | use super::SerialisedClaim; 37 | 38 | use sodiumoxide::crypto::sign::PublicKey; 39 | use sodiumoxide::crypto::sign::Signature; 40 | use accumulator::Accumulator; 41 | use key_store::KeyStore; 42 | use statistics::Frequency; 43 | 44 | pub trait Source where Name: Eq + PartialOrd + Ord + Clone { 45 | fn get_source(&self) -> Name; 46 | } 47 | 48 | pub enum AddResult 49 | where Request: Eq + PartialOrd + Ord + Clone + Source, 50 | Name: Eq + PartialOrd + Ord + Clone 51 | { 52 | RequestKeys(Name), 53 | Resolved(Request, SerialisedClaim), 54 | } 55 | 56 | /// PureSentinel is templated on an immutable Request type, a mergeable Claim type. 57 | /// It further takes a Name type to identify claimants. 58 | /// Signature and PublicSignKey type are auxiliary types to handle a user-chosen 59 | /// cryptographic signing scheme. 60 | pub struct PureSentinel 61 | where Request: Eq + PartialOrd + Ord + Clone + Source, 62 | Name: Eq + PartialOrd + Ord + Clone 63 | { 64 | claim_accumulator: Accumulator, 65 | key_store: KeyStore, 66 | claim_quroum_size: Option, 67 | } 68 | 69 | impl 70 | PureSentinel 71 | where Request: Eq + PartialOrd + Ord + Clone + Source, 72 | Name: Eq + PartialOrd + Ord + Clone { 73 | /// This creates a new pure sentinel that will collect a minimal claim_threshold number 74 | /// of verified claims before attempting to merge these claims. 75 | /// To obtain a verified claim PureSentinel needs to have received a matching public 76 | /// signing key. Each such a public signing key needs keys_threshold confirmations 77 | /// for it to be considered valid and used for verifying the signature 78 | /// of the corresponding claim. 79 | pub fn new() -> PureSentinel { 80 | PureSentinel { 81 | claim_accumulator: Accumulator::new(0), 82 | key_store: KeyStore::new(), 83 | // TODO: Would be nice if claim_accumulator gave us this value. 84 | // But there is no api for that yet. 85 | claim_quroum_size: None, 86 | } 87 | } 88 | 89 | /// This adds a new claim for the provided request. The claimant name and 90 | /// the signature provided will be used to verify the claim with the keys 91 | /// that are independently retrieved. When an added claim leads to the 92 | /// resolution of the request, the request and the claim are returned. 93 | /// All resolved claims have to be identical. Otherwise None is returned. 94 | /// 95 | /// Possible results are: 96 | /// * Some(AddResult::Resolved(request, serialised_claim)): indicating 97 | /// that the claim has been successfully resolved. 98 | /// * Some(AddResult::RequestKeys(target)): indicating that the caller 99 | /// should request public keys from the group surrounding the target. 100 | /// * None: indicating that no resolve was possible yet. 101 | pub fn add_claim(&mut self, 102 | request: Request, 103 | claimant: Name, // Node which sent the message 104 | signature: Signature, 105 | claim: SerialisedClaim, 106 | claim_quorum: usize, 107 | key_quorum: usize) 108 | -> Option> { 109 | 110 | let saw_first_time = !self.claim_accumulator.contains_key(&request); 111 | 112 | self.claim_quroum_size = Some(claim_quorum); 113 | self.claim_accumulator.set_quorum_size(claim_quorum); 114 | 115 | self.claim_accumulator 116 | .add(request.clone(), (claimant, signature, claim)) 117 | .and_then(|(request, claims)| 118 | self.resolve(request, claims, claim_quorum, key_quorum)) 119 | .map(|(request, serialised_claim)| { 120 | AddResult::Resolved(request, serialised_claim) 121 | }).or_else(|| { 122 | if saw_first_time { 123 | Some(AddResult::RequestKeys(request.get_source())) 124 | } else { 125 | None 126 | } 127 | }) 128 | } 129 | 130 | /// This adds a new set of public_signing_keys for the provided request. 131 | /// If the request is not known yet by pure sentinel, the added keys will be ignored. 132 | /// When the added set of keys leads to the resolution of the request, 133 | /// the request and the verified and merged claim is returned. 134 | /// Otherwise None is returned. 135 | pub fn add_keys(&mut self, 136 | request: Request, 137 | sender: Name, 138 | keys: Vec<(Name, PublicKey)>, 139 | key_quorum: usize) 140 | -> Option<(Request, SerialisedClaim)> { 141 | // We don't want to store keys for requests we haven't received yet because 142 | // we couldn't have requested those keys. So someone is probably trying 143 | // something silly. 144 | if !self.claim_accumulator.contains_key(&request) { 145 | return None; 146 | } 147 | 148 | let claim_quorum = match self.claim_quroum_size { 149 | Some(q) => q, 150 | None => { 151 | // Should have been assigned in `add_claim` function and we know 152 | // it was called due to the above check. 153 | debug_assert!(false); 154 | return None; 155 | } 156 | }; 157 | 158 | for (target, public_key) in keys { 159 | self.key_store.add_key(target, sender.clone(), public_key); 160 | } 161 | 162 | self.claim_accumulator.get(&request) 163 | .and_then(|(request, claims)| { 164 | self.resolve(request, claims, claim_quorum, key_quorum) 165 | }) 166 | } 167 | 168 | /// Verify is only concerned with checking the signatures of the serialised claims. 169 | /// To achieve this it pairs up a set of signed claims and a set of public signing keys. 170 | fn verify(&mut self, 171 | claims: &Vec<(Name, Signature, SerialisedClaim)>, 172 | key_quorum: usize) 173 | -> Vec { 174 | claims.iter().filter_map(|&(ref name, ref signature, ref body)| { 175 | self.verify_single_claim(name, signature, body, key_quorum) 176 | }).collect() 177 | } 178 | 179 | fn verify_single_claim(&mut self, 180 | name: &Name, 181 | signature: &Signature, 182 | body: &SerialisedClaim, 183 | key_quorum: usize) 184 | -> Option { 185 | for public_key in self.key_store.get_accumulated_keys(&name, key_quorum) { 186 | match super::verify_signature(&signature, &public_key, &body) { 187 | Some(body) => return Some(body), 188 | None => continue, 189 | } 190 | } 191 | None 192 | } 193 | 194 | fn squash(&self, 195 | verified_claims: Vec, 196 | quorum_size: usize) 197 | -> Option { 198 | if verified_claims.len() < quorum_size { 199 | // Can't squash: not enough claims. 200 | return None; 201 | } 202 | 203 | let mut frequency = Frequency::new(); 204 | 205 | for verified_claim in verified_claims { 206 | frequency.update(&verified_claim) 207 | } 208 | 209 | let mut iter = frequency.sort_by_highest().into_iter() 210 | .filter(|&(_, ref count)| *count >= quorum_size) 211 | .map(|(resolved_claim, _)| resolved_claim); 212 | 213 | let retval = iter.next().map(|a| a.clone()); 214 | 215 | // In debug mode we expect no adversaries. 216 | debug_assert!(retval.is_some(), "Frequency returned less than one result"); 217 | debug_assert!(iter.next().is_none(), "Frequency returned more than one result"); 218 | 219 | retval 220 | } 221 | 222 | fn resolve(&mut self, 223 | request: Request, 224 | claims: Vec<(Name, Signature, SerialisedClaim)>, 225 | claim_quorum: usize, 226 | key_quorum: usize) 227 | -> Option<(Request, SerialisedClaim)> { 228 | let verified_claims = self.verify(&claims, key_quorum); 229 | self.squash(verified_claims, claim_quorum) 230 | .map(|c| { 231 | self.claim_accumulator.delete(&request); 232 | (request, c) 233 | }) 234 | } 235 | } 236 | 237 | #[cfg(test)] 238 | mod test { 239 | 240 | extern crate rustc_serialize; 241 | use super::*; 242 | 243 | use rand::random; 244 | use sodiumoxide::crypto; 245 | use SerialisedClaim; 246 | 247 | const NAMESIZE: usize = 64; 248 | const QUORUM: usize = 10; 249 | 250 | #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug)] 251 | pub struct TestName { 252 | pub data: Vec, 253 | } 254 | 255 | fn generate_random_name() -> TestName { 256 | let mut arr = [0u8;NAMESIZE]; 257 | for i in (0..NAMESIZE) { 258 | arr[i] = random::(); 259 | } 260 | TestName { data: arr.to_vec() } 261 | } 262 | 263 | #[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug)] 264 | struct TestRequest { 265 | core: usize, 266 | name: TestName, 267 | } 268 | 269 | impl TestRequest { 270 | pub fn new(core: usize, name: TestName) -> TestRequest { 271 | TestRequest { core: core, name: name } 272 | } 273 | } 274 | 275 | impl Source for TestRequest { 276 | fn get_source(&self) -> TestName { 277 | self.name.clone() 278 | } 279 | } 280 | 281 | #[derive(PartialEq, Eq, PartialOrd, Ord, Clone)] 282 | struct TestClaim { 283 | value: usize, 284 | } 285 | 286 | impl TestClaim { 287 | pub fn serialise(&self) -> SerialisedClaim { 288 | self.value.to_string().into_bytes() 289 | } 290 | } 291 | 292 | #[test] 293 | fn one_request_and_one_key() { 294 | let quorum_size = 1usize; 295 | let mut name_key_pairs = Vec::new(); 296 | let mut pure_sentinel: PureSentinel = PureSentinel::new(); 297 | let name = generate_random_name(); 298 | let request = TestRequest::new(random::(), name.clone()); 299 | let claim = TestClaim { value: random::() }; 300 | let serialised_claim = claim.serialise(); 301 | let key_pair = crypto::sign::gen_keypair(); 302 | let signature = crypto::sign::sign_detached(&serialised_claim, &key_pair.1); 303 | let climant_name = generate_random_name(); 304 | name_key_pairs.push((climant_name.clone(), key_pair.0.clone())); 305 | 306 | // first claim added should return AddResult::RequestKeys 307 | assert!(pure_sentinel.add_claim(request.clone(), climant_name.clone(), signature.clone(), 308 | serialised_claim.clone(), quorum_size, quorum_size) 309 | .and_then(|result| match result { 310 | AddResult::RequestKeys(source_name) => { 311 | assert_eq!(request.get_source(), source_name); 312 | Some(source_name) 313 | } 314 | AddResult::Resolved(_, _) => None 315 | }).is_some()); 316 | 317 | // One key is required should pass 318 | assert!(pure_sentinel.add_keys(request.clone(), 319 | generate_random_name(), 320 | name_key_pairs.clone(), 321 | quorum_size) 322 | .and_then(|result| { assert_eq!(result.1, serialised_claim); 323 | assert_eq!(result.0, request); 324 | Some(result) 325 | }).is_some()); 326 | } 327 | 328 | #[test] 329 | fn request_and_its_duplicate_added() { 330 | let mut pure_sentinel: PureSentinel = PureSentinel::new(); 331 | let name = generate_random_name(); 332 | let request = TestRequest::new(random::(), name.clone()); 333 | let claim = TestClaim { value: random::() }; 334 | let serialised_claim = claim.serialise(); 335 | let key_pair = crypto::sign::gen_keypair(); 336 | let signature = crypto::sign::sign_detached(&serialised_claim, &key_pair.1); 337 | let climant_name = generate_random_name(); 338 | 339 | // first claim added should return AddResult::RequestKeys 340 | assert!(pure_sentinel.add_claim(request.clone(), climant_name.clone(), signature.clone(), 341 | serialised_claim.clone(), QUORUM, QUORUM) 342 | .and_then(|result| match result { 343 | AddResult::RequestKeys(source_name) => { 344 | assert_eq!(request.get_source(), source_name); Some(source_name) }, 345 | AddResult::Resolved(_, _) => None 346 | }).is_some()); 347 | 348 | // same claim added for the second time none to be returned 349 | assert!(pure_sentinel.add_claim(request, climant_name, signature, serialised_claim, 350 | QUORUM, QUORUM).is_none()) 351 | } 352 | 353 | #[test] 354 | fn threshold_claims_requests_added_with_no_keys() { 355 | let mut name_key_pairs = Vec::new(); 356 | let mut pure_sentinel: PureSentinel = PureSentinel::new(); 357 | let name = generate_random_name(); 358 | let request = TestRequest::new(random::(), name.clone()); 359 | let claim = TestClaim { value: random::() }; 360 | let serialised_claim = claim.serialise(); 361 | for index in 0..QUORUM { 362 | let key_pair = crypto::sign::gen_keypair(); 363 | let signature = crypto::sign::sign_detached(&serialised_claim, &key_pair.1); 364 | let climant_name = generate_random_name(); 365 | name_key_pairs.push((climant_name.clone(), key_pair.0.clone())); 366 | assert!(pure_sentinel.add_claim(request.clone(), climant_name, signature.clone(), 367 | serialised_claim.clone(), QUORUM, QUORUM) 368 | .map_or(true, |result| match result { 369 | AddResult::RequestKeys(source_name) => { assert_eq!(request.get_source(), 370 | source_name); 371 | assert_eq!(index, 0usize); 372 | true 373 | }, 374 | AddResult::Resolved(_, _) => false 375 | })); 376 | } 377 | } 378 | 379 | #[test] 380 | fn requests_added_with_various_key_size() { 381 | let mut name_key_pairs = Vec::new(); 382 | let mut pure_sentinel: PureSentinel = PureSentinel::new(); 383 | let name = generate_random_name(); 384 | let request = TestRequest::new(random::(), name.clone()); 385 | let claim = TestClaim { value: random::() }; 386 | let serialised_claim = claim.serialise(); 387 | for index in 0..QUORUM { 388 | let key_pair = crypto::sign::gen_keypair(); 389 | let signature = crypto::sign::sign_detached(&serialised_claim, &key_pair.1); 390 | let climant_name = generate_random_name(); 391 | name_key_pairs.push((climant_name.clone(), key_pair.0.clone())); 392 | assert!(pure_sentinel.add_claim(request.clone(), climant_name, signature.clone(), 393 | serialised_claim.clone(), QUORUM, QUORUM) 394 | .map_or(true, |result| match result { 395 | AddResult::RequestKeys(source_name) => { 396 | assert_eq!(request.get_source(), source_name); 397 | assert_eq!(index, 0usize); 398 | true 399 | }, 400 | AddResult::Resolved(_, _) => false 401 | })); 402 | } 403 | 404 | // less than KEY_THRESHOLDS kyes received, should return None as the vector has the senders 405 | for index in 0..QUORUM { 406 | assert!(pure_sentinel.add_keys(request.clone(), name_key_pairs[index].0.clone(), 407 | name_key_pairs.clone(), QUORUM).is_none()); 408 | } 409 | 410 | // KEY_THRESHOLDS kyes received, should not return none 411 | assert!(pure_sentinel.add_keys(request.clone(), generate_random_name(), 412 | name_key_pairs.clone(), QUORUM) 413 | .and_then(|result| { assert_eq!(result.1, serialised_claim); 414 | assert_eq!(result.0, request); 415 | Some(result) 416 | }).is_some()); 417 | 418 | // more than KEY_THRESHOLDS kyes received, should return None 419 | assert!(pure_sentinel.add_keys(request, generate_random_name(), name_key_pairs, 420 | QUORUM).is_none()); 421 | } 422 | } 423 | -------------------------------------------------------------------------------- /src/refresh_sentinel.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015 MaidSafe.net limited. 2 | // 3 | // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, 4 | // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which 5 | // licence you accepted on initial access to the Software (the "Licences"). 6 | // 7 | // By contributing code to the SAFE Network Software, or to this project generally, you agree to be 8 | // bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the 9 | // Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR. 10 | // 11 | // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed 12 | // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. 14 | 15 | extern crate lru_time_cache; 16 | use lru_time_cache::LruCache; 17 | 18 | /// Entry for accumulation. 19 | #[derive(Clone)] 20 | pub struct Entry { 21 | /// Values accumulated for a given key. 22 | pub received_response: Vec, 23 | } 24 | 25 | /// Generic type for accumulating multiple values under a given key. 26 | #[allow(dead_code)] 27 | pub struct RefreshSentinel 28 | where K: PartialOrd + Ord + Clone, 29 | V: Clone 30 | { 31 | /// Threshold for resolution. 32 | quorum: usize, 33 | storage: LruCache>, 34 | } 35 | 36 | impl RefreshSentinel { 37 | /// Construct with quorum. 38 | #[allow(dead_code)] 39 | pub fn new(quorum: usize) -> RefreshSentinel { 40 | RefreshSentinel { quorum: quorum, storage: LruCache::>::with_capacity(1000) } 41 | } 42 | 43 | /// Check for the existence of a key. 44 | #[allow(dead_code)] 45 | pub fn contains_key(&self, key: &K) -> bool { 46 | self.storage.check(key) 47 | } 48 | 49 | /// Check whether a quorum of values has been accumulated for the given key. 50 | #[allow(dead_code)] 51 | pub fn is_quorum_reached(&mut self, key: &K) -> bool { 52 | let entry = self.storage.get(key); 53 | 54 | if entry.is_none() { 55 | false 56 | } else { 57 | entry.unwrap().received_response.len() >= self.quorum 58 | } 59 | } 60 | 61 | /// Adds a key/value pair, if the key already exists add the value under that key. 62 | /// Optionally returns the key and the vector of values if the quroum has been reached. 63 | #[allow(dead_code)] 64 | pub fn add(&mut self, key: K, value: V) -> Option<(K, Vec)> { 65 | let entry = self.storage.remove(&key); 66 | if entry.is_none() { 67 | let entry_in = Entry { received_response: vec![value] }; 68 | self.storage.add(key.clone(), entry_in.clone()); 69 | if self.quorum == 1 { 70 | let result = (key, entry_in.received_response); 71 | return Some(result); 72 | } 73 | } else { 74 | let mut tmp = entry.unwrap(); 75 | tmp.received_response.push(value); 76 | self.storage.add(key.clone(), tmp.clone()); 77 | if tmp.received_response.len() >= self.quorum { 78 | return Some((key, tmp.received_response)); 79 | } 80 | } 81 | None 82 | } 83 | 84 | /// Retrieve a key/vec pair from the cache. 85 | #[allow(dead_code)] 86 | pub fn get(&mut self, key: &K) -> Option<(K, Vec)> { 87 | let entry = self.storage.get(key); 88 | if entry.is_none() { 89 | None 90 | } else { 91 | Some((key.clone(), entry.unwrap().received_response.clone())) 92 | } 93 | } 94 | 95 | /// Remove all values for the given key. 96 | #[allow(dead_code)] 97 | pub fn delete(&mut self, key: &K) { 98 | self.storage.remove(key); 99 | } 100 | 101 | /// Return the size of the cache. 102 | #[allow(dead_code)] 103 | pub fn cache_size(&mut self) -> usize { 104 | self.storage.len() 105 | } 106 | 107 | /// Set the quorum to a new value. 108 | #[allow(dead_code)] 109 | pub fn set_quorum(&mut self, quorum: usize) { 110 | self.quorum = quorum; 111 | } 112 | } 113 | 114 | #[cfg(test)] 115 | mod test { 116 | extern crate rand; 117 | use super::*; 118 | 119 | #[test] 120 | fn add() { 121 | let mut sentinel: RefreshSentinel = RefreshSentinel::new(1); 122 | 123 | assert!(sentinel.add(2, 3).is_some()); 124 | assert_eq!(sentinel.contains_key(&1), false); 125 | assert_eq!(sentinel.contains_key(&2), true); 126 | assert_eq!(sentinel.is_quorum_reached(&1), false); 127 | assert_eq!(sentinel.is_quorum_reached(&2), true); 128 | assert!(sentinel.add(1, 3).is_some()); 129 | assert_eq!(sentinel.contains_key(&1), true); 130 | assert_eq!(sentinel.is_quorum_reached(&1), true); 131 | assert!(sentinel.add(1, 3).is_some()); 132 | assert_eq!(sentinel.contains_key(&1), true); 133 | assert_eq!(sentinel.is_quorum_reached(&1), true); 134 | 135 | let (key, responses) = sentinel.get(&1).unwrap(); 136 | 137 | assert_eq!(key, 1); 138 | assert_eq!(responses.len(), 2); 139 | assert_eq!(responses[0], 3); 140 | assert_eq!(responses[1], 3); 141 | 142 | let (key, responses) = sentinel.get(&2).unwrap(); 143 | 144 | assert_eq!(key, 2); 145 | assert_eq!(responses.len(), 1); 146 | assert_eq!(responses[0], 3); 147 | } 148 | 149 | #[test] 150 | fn add_single_value_quorum() { 151 | let quorum_size: usize = 19; 152 | let mut sentinel: RefreshSentinel = RefreshSentinel::new(quorum_size); 153 | let key = rand::random::(); 154 | let value = rand::random::(); 155 | for i in 0..quorum_size - 1 { 156 | assert!(sentinel.add(key, value).is_none()); 157 | let key_value = sentinel.get(&key).unwrap(); 158 | assert_eq!(key_value.0, key); 159 | assert_eq!(key_value.1.len(), i + 1); 160 | for response in key_value.1 { 161 | assert_eq!(response, value); 162 | }; 163 | assert_eq!(sentinel.is_quorum_reached(&key), false); 164 | } 165 | assert!(sentinel.add(key, value).is_some()); 166 | assert_eq!(sentinel.is_quorum_reached(&key), true); 167 | let key_value = sentinel.get(&key).unwrap(); 168 | assert_eq!(key_value.0, key); 169 | assert_eq!(key_value.1.len(), quorum_size); 170 | for response in key_value.1 { 171 | assert_eq!(response, value); 172 | }; 173 | } 174 | 175 | #[test] 176 | fn add_multiple_values_quorum() { 177 | let quorum_size: usize = 19; 178 | let mut sentinel: RefreshSentinel = RefreshSentinel::new(quorum_size); 179 | let key = rand::random::(); 180 | for _ in 0..quorum_size - 1 { 181 | assert!(sentinel.add(key, rand::random::()).is_none()); 182 | assert_eq!(sentinel.is_quorum_reached(&key), false); 183 | } 184 | assert!(sentinel.add(key, rand::random::()).is_some()); 185 | assert_eq!(sentinel.is_quorum_reached(&key), true); 186 | } 187 | 188 | #[test] 189 | fn add_multiple_keys_quorum() { 190 | let quorum_size: usize = 19; 191 | let mut sentinel: RefreshSentinel = RefreshSentinel::new(quorum_size); 192 | let key = rand::random::(); 193 | let mut noise_keys: Vec = Vec::with_capacity(5); 194 | while noise_keys.len() < 5 { 195 | let noise_key = rand::random::(); 196 | if noise_key != key { 197 | noise_keys.push(noise_key); 198 | }; 199 | }; 200 | for _ in 0..quorum_size - 1 { 201 | for noise_key in noise_keys.iter() { 202 | sentinel.add(noise_key.clone(), rand::random::()); 203 | } 204 | assert!(sentinel.add(key, rand::random::()).is_none()); 205 | assert_eq!(sentinel.is_quorum_reached(&key), false); 206 | } 207 | assert!(sentinel.add(key, rand::random::()).is_some()); 208 | assert_eq!(sentinel.is_quorum_reached(&key), true); 209 | } 210 | 211 | #[test] 212 | fn delete() { 213 | let mut sentinel: RefreshSentinel = RefreshSentinel::new(2); 214 | 215 | assert!(sentinel.add(1, 1).is_none()); 216 | assert_eq!(sentinel.contains_key(&1), true); 217 | assert_eq!(sentinel.is_quorum_reached(&1), false); 218 | 219 | let (key, responses) = sentinel.get(&1).unwrap(); 220 | 221 | assert_eq!(key, 1); 222 | assert_eq!(responses.len(), 1); 223 | assert_eq!(responses[0], 1); 224 | 225 | sentinel.delete(&1); 226 | 227 | let option = sentinel.get(&1); 228 | 229 | assert!(option.is_none()); 230 | 231 | assert!(sentinel.add(1, 1).is_none()); 232 | assert_eq!(sentinel.contains_key(&1), true); 233 | assert_eq!(sentinel.is_quorum_reached(&1), false); 234 | assert!(sentinel.add(1, 1).is_some()); 235 | assert_eq!(sentinel.contains_key(&1), true); 236 | assert_eq!(sentinel.is_quorum_reached(&1), true); 237 | 238 | let (key, responses) = sentinel.get(&1).unwrap(); 239 | 240 | assert_eq!(key, 1); 241 | assert_eq!(responses.len(), 2); 242 | assert_eq!(responses[0], 1); 243 | assert_eq!(responses[1], 1); 244 | 245 | sentinel.delete(&1); 246 | 247 | let option = sentinel.get(&1); 248 | 249 | assert!(option.is_none()); 250 | } 251 | 252 | #[test] 253 | fn fill() { 254 | let mut sentinel: RefreshSentinel = RefreshSentinel::new(1); 255 | 256 | for count in 0..1000 { 257 | assert!(sentinel.add(count, 1).is_some()); 258 | assert_eq!(sentinel.contains_key(&count), true); 259 | assert_eq!(sentinel.is_quorum_reached(&count), true); 260 | } 261 | 262 | for count in 0..1000 { 263 | let (key, responses) = sentinel.get(&count).unwrap(); 264 | 265 | assert_eq!(key, count); 266 | assert_eq!(responses.len(), 1); 267 | assert_eq!(responses[0], 1); 268 | } 269 | } 270 | 271 | #[test] 272 | fn cache_removals() { 273 | let mut sentinel: RefreshSentinel = RefreshSentinel::new(2); 274 | 275 | for count in 0..1000 { 276 | assert!(sentinel.add(count, 1).is_none()); 277 | assert_eq!(sentinel.contains_key(&count), true); 278 | assert_eq!(sentinel.is_quorum_reached(&count), false); 279 | 280 | let (key, responses) = sentinel.get(&count).unwrap(); 281 | 282 | assert_eq!(key, count); 283 | assert_eq!(responses.len(), 1); 284 | assert_eq!(responses[0], 1); 285 | assert_eq!(sentinel.cache_size(), count as usize + 1); 286 | } 287 | 288 | assert!(sentinel.add(1000, 1).is_none()); 289 | assert_eq!(sentinel.contains_key(&1000), true); 290 | assert_eq!(sentinel.is_quorum_reached(&1000), false); 291 | assert_eq!(sentinel.cache_size(), 1000); 292 | 293 | for count in 0..1000 { 294 | let option = sentinel.get(&count); 295 | 296 | assert!(option.is_none()); 297 | 298 | assert!(sentinel.add(count + 1001, 1).is_none()); 299 | assert_eq!(sentinel.contains_key(&(count + 1001)), true); 300 | assert_eq!(sentinel.is_quorum_reached(&(count + 1001)), false); 301 | assert_eq!(sentinel.cache_size(), 1000); 302 | } 303 | } 304 | 305 | #[test] 306 | fn set_quorum_size() { 307 | let mut sentinel: RefreshSentinel = RefreshSentinel::new(2); 308 | let random = rand::random::(); 309 | sentinel.set_quorum(random); 310 | assert_eq!(random, sentinel.quorum); 311 | } 312 | } 313 | -------------------------------------------------------------------------------- /src/statistics.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2015 MaidSafe.net limited. 2 | // 3 | // This SAFE Network Software is licensed to you under (1) the MaidSafe.net Commercial License, 4 | // version 1.0 or later, or (2) The General Public License (GPL), version 3, depending on which 5 | // licence you accepted on initial access to the Software (the "Licences"). 6 | // 7 | // By contributing code to the SAFE Network Software, or to this project generally, you agree to be 8 | // bound by the terms of the MaidSafe Contributor Agreement, version 1.0. This, along with the 9 | // Licenses can be found in the root directory of this project at LICENSE, COPYING and CONTRIBUTOR. 10 | // 11 | // Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed 12 | // under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 13 | // KIND, either express or implied. 14 | // 15 | // Please review the Licences for the specific language governing permissions and limitations 16 | // relating to use of the SAFE Network Software. 17 | 18 | pub struct Frequency { 19 | map: Vec<(Key, usize)>, 20 | } 21 | 22 | impl Frequency { 23 | pub fn new() -> Frequency { 24 | Frequency { map: Vec::<(Key, usize)>::new() } 25 | } 26 | 27 | pub fn update(&mut self, key: &Key) { 28 | let mut fresh_key: bool = true; 29 | for stored_key in self.map.iter_mut() { 30 | if &stored_key.0 == key { 31 | stored_key.1 += 1; 32 | fresh_key = false; 33 | break; 34 | } 35 | } 36 | if fresh_key { 37 | self.map.push((key.clone(), 1)); 38 | } 39 | } 40 | 41 | pub fn sort_by_highest(&mut self) -> Vec<(Key, usize)> { 42 | self.map.sort_by(|a,b| b.1.cmp(&a.1)); 43 | self.map.clone() 44 | } 45 | } 46 | 47 | #[cfg(test)] 48 | mod test { 49 | use super::*; 50 | use rand::{Rng, thread_rng}; 51 | 52 | #[test] 53 | fn fill_monotonic_distribution() { 54 | let mut rng = thread_rng(); 55 | 56 | // ensure a monotonic decreasing function 57 | let domain_low = 0u32; 58 | let domain_high = 500u32; 59 | assert!(domain_low < domain_high); 60 | let mut all_counts: Vec = Vec::with_capacity(3000); // simple approx upperbound 61 | for _ in 0..100 { 62 | let x: u32 = rng.gen_range(domain_low, domain_high); 63 | if all_counts.contains(&x) { 64 | continue; 65 | } // avoid double counting 66 | let fx: f64 = x.clone() as f64; 67 | // use monotonic descending range of gaussian 68 | let y: f64 = 30f64 * (- (fx.powi(2i32) / 100000f64)).exp(); 69 | let count: usize = y.trunc() as usize + 1; 70 | // duplicate the keys for 71 | for _ in 0usize..count { 72 | all_counts.push(x.clone()); 73 | }; 74 | }; 75 | 76 | // shuffle duplicated keys 77 | rng.shuffle(&mut all_counts[..]); 78 | let mut freq = Frequency::new(); 79 | for occurance in all_counts { 80 | // and register each key multiple times in random order 81 | freq.update(&occurance); 82 | }; 83 | // sort the counts 84 | let ordered_counts = freq.sort_by_highest(); 85 | let mut max_count = 31usize; 86 | for value in ordered_counts { 87 | let fx: f64 = value.0.clone() as f64; 88 | let y: f64 = 30f64 * (- (fx.powi(2i32) / 100000f64)).exp(); 89 | let count: usize = y.trunc() as usize + 1; 90 | // because we started with random keys whos occurance monotonically decreased 91 | // for increasing key, the keys should now increase, as the count decreases. 92 | assert_eq!(value.1, count); 93 | assert!(value.1 <= max_count); 94 | max_count = value.1.clone(); 95 | }; 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/wrappers.rs: -------------------------------------------------------------------------------- 1 | 2 | use sodiumoxide::crypto::sign; 3 | use std::cmp::Ordering; 4 | 5 | pub struct SignW(pub sign::Signature); 6 | 7 | impl Clone for SignW { 8 | fn clone(&self) -> SignW { 9 | let mut bytes = [0u8; sign::SIGNATUREBYTES]; 10 | for i in (0..sign::SIGNATUREBYTES) { 11 | bytes[i] = (self.0).0[i] 12 | } 13 | SignW(sign::Signature(bytes)) 14 | } 15 | } 16 | 17 | impl PartialOrd for SignW { 18 | fn partial_cmp(&self, other: &SignW) -> Option { 19 | Some(self.cmp(&other)) 20 | } 21 | } 22 | 23 | impl Ord for SignW { 24 | fn cmp(&self, other: &SignW) -> Ordering { 25 | for i in (0..sign::SIGNATUREBYTES) { 26 | let ord = (self.0).0[i].cmp(&(other.0).0[i]); 27 | if ord != Ordering::Equal { 28 | return ord; 29 | } 30 | } 31 | Ordering::Equal 32 | } 33 | } 34 | 35 | impl PartialEq for SignW { 36 | fn eq(&self, other: &SignW) -> bool { 37 | for i in (0..sign::SIGNATUREBYTES) { 38 | if (self.0).0[i] != (other.0).0[i] { 39 | return false; 40 | } 41 | } 42 | true 43 | } 44 | } 45 | 46 | impl Eq for SignW { } 47 | --------------------------------------------------------------------------------