├── .github └── workflows │ └── test.yml ├── .gitignore ├── CONTRIBUTING.md ├── Cargo.toml ├── LICENSE ├── README.md └── src ├── lib.rs └── protocols ├── aggsig ├── mod.rs └── test.rs ├── mod.rs ├── multisig ├── mod.rs └── test.rs ├── musig2 ├── mod.rs └── test.rs └── thresholdsig ├── mod.rs └── test.rs /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | # Based on https://github.com/actions-rs/meta/blob/master/recipes/quickstart.md 2 | 3 | on: [push, pull_request] 4 | 5 | name: Continuous Integration 6 | 7 | jobs: 8 | check: 9 | name: Check 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Checkout sources 13 | uses: actions/checkout@v2 14 | 15 | - name: Install stable toolchain 16 | uses: actions-rs/toolchain@v1 17 | with: 18 | profile: minimal 19 | toolchain: stable 20 | override: true 21 | 22 | - name: Run cargo check 23 | uses: actions-rs/cargo@v1 24 | with: 25 | command: check 26 | args: --tests 27 | 28 | test: 29 | name: Test Suite 30 | runs-on: ubuntu-latest 31 | steps: 32 | - name: Checkout sources 33 | uses: actions/checkout@v2 34 | 35 | - name: Install stable toolchain 36 | uses: actions-rs/toolchain@v1 37 | with: 38 | profile: minimal 39 | toolchain: stable 40 | override: true 41 | 42 | - name: Run cargo test 43 | uses: actions-rs/cargo@v1 44 | with: 45 | command: test 46 | 47 | test-release: 48 | name: Test Suite Release 49 | runs-on: ubuntu-latest 50 | steps: 51 | - name: Checkout sources 52 | uses: actions/checkout@v2 53 | 54 | - name: Install stable toolchain 55 | uses: actions-rs/toolchain@v1 56 | with: 57 | profile: minimal 58 | toolchain: stable 59 | override: true 60 | 61 | - name: Run cargo test --release 62 | uses: actions-rs/cargo@v1 63 | with: 64 | command: test 65 | 66 | lints: 67 | name: Lints 68 | runs-on: ubuntu-latest 69 | steps: 70 | - name: Checkout sources 71 | uses: actions/checkout@v2 72 | 73 | - name: Install stable toolchain 74 | uses: actions-rs/toolchain@v1 75 | with: 76 | profile: minimal 77 | toolchain: stable 78 | override: true 79 | components: rustfmt, clippy 80 | 81 | - name: Run cargo fmt 82 | uses: actions-rs/cargo@v1 83 | with: 84 | command: fmt 85 | args: --all -- --check 86 | 87 | - name: Run cargo clippy 88 | uses: actions-rs/cargo@v1 89 | with: 90 | command: clippy 91 | args: --tests -- -D warnings 92 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Generated by Cargo 2 | # will have compiled files and executables 3 | /target/ 4 | 5 | # Remove Cargo.lock from gitignore if creating an executable, leave it for libraries 6 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 7 | Cargo.lock 8 | 9 | # These are backup files generated by rustfmt 10 | **/*.rs.bk 11 | **/venv 12 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Contributing to the Multisig ed25519 project 2 | ===================================== 3 | 4 | Pull requests are always welcome, and the KZen dev team appreciates any help the community can 5 | give to help make Multisig Schnorr project better. 6 | 7 | Contributor Agreement (CA) 8 | ---------------- 9 | 10 | Any contributor must sign the Contributor Agreement (CA). 11 | 12 | ### How to sign the Contributor Agreement (CA)? 13 | 14 | Please send an email to [github@kzencorp.com](mailto:github@kzencorp.com) containing your github username, the CA will be send to you by email. 15 | After signature you will be added to the team as a contributor. 16 | 17 | Communication Channels 18 | ---------------- 19 | 20 | * Most communication about KZen cryptography happens on Telegram, feel free to send us an email with your contact details. 21 | 22 | * Discussion about code base improvements happens in GitHub issues and on pull requests. 23 | 24 | Contributor Workflow 25 | ---------------- 26 | 27 | The codebase is maintained using the "contributor workflow" where everyone contributes patch proposals using "pull requests". This facilitates social contribution, easy testing and peer review. 28 | 29 | To contribute a patch, the workflow is as follows: 30 | 31 | * Fork repository 32 | * Create topic branch 33 | * Commit patches 34 | * Push changes to your fork 35 | * Create pull request 36 | 37 | Make sure to provide a clear description in your Pull Request (PR). 38 | 39 | ### Header 40 | 41 | Make sure to include the following header (by configuring your IDE) in all files: 42 | 43 | ```rust 44 | /* 45 | Multisig ed25519 46 | 47 | Copyright 2018 by Kzen Networks 48 | 49 | This file is part of Multisig ed25519 library 50 | (https://github.com/KZen-networks/multi-party-ed25519) 51 | 52 | Multisig ed25519 is free software: you can redistribute 53 | it and/or modify it under the terms of the GNU General Public 54 | License as published by the Free Software Foundation, either 55 | version 3 of the License, or (at your option) any later version. 56 | 57 | @license GPL-3.0+ 58 | */ 59 | ``` -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "multi-party-eddsa" 3 | version = "0.3.0" 4 | authors = [ 5 | "Omer ", 6 | "Gary " 7 | ] 8 | 9 | [lib] 10 | crate-type = ["rlib", "dylib"] 11 | 12 | [dependencies] 13 | curv = { package = "curv-kzen", version = "0.9", default-features = false } 14 | hex = "0.3.2" 15 | serde = "1.0" 16 | serde_json = "1.0" 17 | serde_derive = "1.0" 18 | rand = "0.8" 19 | sha2 = "0.9" 20 | 21 | [dev-dependencies] 22 | ed25519-dalek = "1.0.1" 23 | rand_xoshiro = "0.6.0" 24 | itertools = "0.10" 25 | 26 | [features] 27 | default = ["curv/rust-gmp-kzen"] 28 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # Multi Party EdDSA signatures 3 | Rust implementation of multiparty Ed25519 signature scheme. 4 | 5 | #### Currently supporting: 6 | * [Aggregated Signatures](https://github.com/KZen-networks/multi-party-ed25519/wiki/Aggregated-Ed25519-Signatures) 7 | * [Accountable-Subgroup Multisignatures](https://github.com/KZen-networks/multi-party-schnorr/blob/master/papers/accountable_subgroups_multisignatures.pdf). 8 | * Threshold EdDSA scheme based on [provably secure distributed schnorr signatures and a {t,n} threshold scheme](https://github.com/KZen-networks/multi-party-schnorr/blob/master/papers/provably_secure_distributed_schnorr_signatures_and_a_threshold_scheme.pdf). For more efficient implementation we used the DKG from [Fast Multiparty Threshold ECDSA with Fast Trustless Setup](https://eprint.iacr.org/2019/114.pdf). The cost is robustness: if there is a malicious party out of the n parties in DKG the protocol stops and if there is a malicious party out of the t parties used for signing the signature protocol will stop. 9 | 10 | The above protocols are for Schnorr signature system. EdDSA is a variant of Schnorr signature system with (possibly twisted) Edwards curves. We adopt the multi party implementations to follow Ed25519 methods for private key and public key generation according to [RFC8032](https://tools.ietf.org/html/rfc8032#section-5.1) 11 | 12 | License 13 | ------- 14 | This library is released under the terms of the GPL-3.0 license. See [LICENSE](LICENSE) for more information. 15 | 16 | Development Process 17 | ------------------- 18 | The contribution workflow is described in [CONTRIBUTING.md](CONTRIBUTING.md). 19 | 20 | Contact 21 | ------------------- 22 | Feel free to [reach out](mailto:github@kzencorp.com) or join the ZenGo X [Telegram](https://t.me/joinchat/ET1mddGXRoyCxZ-7) for discussions on code and research. 23 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Multisig ed25519 3 | 4 | Copyright 2018 by Kzen Networks 5 | 6 | This file is part of Multisig Schnorr library 7 | (https://github.com/KZen-networks/multisig-schnorr) 8 | 9 | Multisig Schnorr is free software: you can redistribute 10 | it and/or modify it under the terms of the GNU General Public 11 | License as published by the Free Software Foundation, either 12 | version 3 of the License, or (at your option) any later version. 13 | 14 | @license GPL-3.0+ 15 | */ 16 | 17 | extern crate curv; 18 | 19 | extern crate hex; 20 | #[macro_use] 21 | extern crate serde_derive; 22 | extern crate rand; 23 | extern crate serde_json; 24 | extern crate sha2; 25 | 26 | #[cfg(test)] 27 | extern crate ed25519_dalek; 28 | #[cfg(test)] 29 | extern crate itertools; 30 | #[cfg(test)] 31 | extern crate rand_xoshiro; 32 | 33 | pub mod protocols; 34 | 35 | #[derive(Copy, PartialEq, Eq, Clone, Debug)] 36 | pub enum Error { 37 | InvalidKey, 38 | InvalidSS, 39 | InvalidCom, 40 | InvalidSig, 41 | } 42 | 43 | use std::fmt; 44 | 45 | impl fmt::Display for Error { 46 | fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 47 | write!(f, "{}", &self) 48 | } 49 | } 50 | 51 | impl std::error::Error for Error {} 52 | -------------------------------------------------------------------------------- /src/protocols/aggsig/mod.rs: -------------------------------------------------------------------------------- 1 | #![allow(non_snake_case)] 2 | /* 3 | multi-party-ed25519 4 | 5 | Copyright 2018 by Kzen Networks 6 | 7 | This file is part of multi-party-ed25519 library 8 | (https://github.com/KZen-networks/multisig-schnorr) 9 | 10 | multi-party-ed25519 is free software: you can redistribute 11 | it and/or modify it under the terms of the GNU General Public 12 | License as published by the Free Software Foundation, either 13 | version 3 of the License, or (at your option) any later version. 14 | 15 | @license GPL-3.0+ 16 | */ 17 | 18 | //! Simple ed25519 19 | //! 20 | //! See https://tools.ietf.org/html/rfc8032 21 | 22 | use super::ExpandedKeyPair; 23 | 24 | pub use curv::arithmetic::traits::Samplable; 25 | use curv::cryptographic_primitives::commitments::hash_commitment::HashCommitment; 26 | use curv::cryptographic_primitives::hashing::DigestExt; 27 | use curv::elliptic::curves::{Ed25519, Point, Scalar}; 28 | use curv::BigInt; 29 | 30 | pub use curv::arithmetic::traits::Converter; 31 | use curv::cryptographic_primitives::commitments::traits::Commitment; 32 | use protocols::{ProofError, Signature}; 33 | use rand::{thread_rng, Rng}; 34 | use sha2::{digest::Digest, Sha512}; 35 | 36 | #[derive(Clone, Debug, Serialize, Deserialize)] 37 | pub struct KeyAgg { 38 | pub apk: Point, 39 | pub hash: Scalar, 40 | } 41 | 42 | impl KeyAgg { 43 | pub fn key_aggregation_n(pks: &[Point], party_index: usize) -> KeyAgg { 44 | let mut my_hash = Scalar::zero(); 45 | let mut sum = Point::zero(); 46 | pks.iter().enumerate().for_each(|(index, pk)| { 47 | let mut hasher = Sha512::new().chain(&[1]).chain(&*pk.to_bytes(true)); 48 | for pk in pks { 49 | hasher.update(&*pk.to_bytes(true)); 50 | } 51 | let hash = hasher.result_scalar(); 52 | let a_i = pk * &hash; 53 | if index == party_index { 54 | my_hash = hash; 55 | } 56 | sum = &sum + a_i 57 | }); 58 | 59 | KeyAgg { 60 | apk: sum, 61 | hash: my_hash, 62 | } 63 | } 64 | } 65 | 66 | #[derive(Debug, Serialize, Deserialize)] 67 | pub struct EphemeralKey { 68 | pub r: Scalar, 69 | pub R: Point, 70 | } 71 | 72 | #[derive(Clone, PartialEq, Debug, Serialize, Deserialize)] 73 | pub struct SignFirstMsg { 74 | pub commitment: BigInt, 75 | } 76 | 77 | #[derive(Clone, PartialEq, Debug, Serialize, Deserialize)] 78 | pub struct SignSecondMsg { 79 | pub R: Point, 80 | pub blind_factor: BigInt, 81 | } 82 | 83 | pub fn create_ephemeral_key_and_commit( 84 | keys: &ExpandedKeyPair, 85 | message: &[u8], 86 | ) -> (EphemeralKey, SignFirstMsg, SignSecondMsg) { 87 | create_ephemeral_key_and_commit_rng(keys, message, &mut thread_rng()) 88 | } 89 | 90 | fn create_ephemeral_key_and_commit_rng( 91 | keys: &ExpandedKeyPair, 92 | message: &[u8], 93 | rng: &mut impl Rng, 94 | ) -> (EphemeralKey, SignFirstMsg, SignSecondMsg) { 95 | // here we deviate from the spec, by introducing non-deterministic element (random number) 96 | // to the nonce 97 | let r = Sha512::new() 98 | .chain(&[2]) 99 | .chain(&*keys.expanded_private_key.prefix.to_bytes()) 100 | .chain(message) 101 | .chain(rng.gen::<[u8; 32]>()) 102 | .result_scalar(); 103 | let R = Point::generator() * &r; 104 | let (commitment, blind_factor) = 105 | HashCommitment::::create_commitment(&R.y_coord().unwrap()); 106 | ( 107 | EphemeralKey { r, R: R.clone() }, 108 | SignFirstMsg { commitment }, 109 | SignSecondMsg { R, blind_factor }, 110 | ) 111 | } 112 | pub fn get_R_tot(Rs: &[Point]) -> Point { 113 | let first = Rs[0].clone(); 114 | Rs[1..].iter().fold(first, |acc, Ri| acc + Ri) 115 | } 116 | 117 | pub fn partial_sign( 118 | r: &Scalar, 119 | keys: &ExpandedKeyPair, 120 | a: &Scalar, 121 | R_tot: &Point, 122 | agg_pubkey: &Point, 123 | msg: &[u8], 124 | ) -> Signature { 125 | let k = Signature::k(R_tot, agg_pubkey, msg); 126 | let k_mul_sk = k * &keys.expanded_private_key.private_key; 127 | let k_mul_sk_mul_ai = k_mul_sk * a; 128 | let s = r + k_mul_sk_mul_ai; 129 | Signature { 130 | R: R_tot.clone(), 131 | s, 132 | } 133 | } 134 | 135 | pub fn sign_single(message: &[u8], keys: &ExpandedKeyPair) -> Signature { 136 | let r = Sha512::new() 137 | .chain(&*keys.expanded_private_key.prefix.to_bytes()) 138 | .chain(message) 139 | .result_scalar(); 140 | let R = &r * Point::generator(); 141 | let k = Signature::k(&R, &keys.public_key, message); 142 | 143 | let k_mul_sk = k * &keys.expanded_private_key.private_key; 144 | let s = r + k_mul_sk; 145 | Signature { R, s } 146 | } 147 | 148 | pub fn add_signature_parts(sigs: &[Signature]) -> Signature { 149 | //test equality of group elements: 150 | assert!(sigs[1..].iter().all(|x| x.R == sigs[0].R)); 151 | //sum s part of the signature: 152 | 153 | let s1 = sigs[0].s.clone(); 154 | let sum = sigs[1..].iter().fold(s1, |acc, si| acc + &si.s); 155 | Signature { 156 | s: sum, 157 | R: sigs[0].R.clone(), 158 | } 159 | } 160 | 161 | pub fn verify_partial_sig( 162 | sig: &Signature, 163 | message: &[u8], 164 | a: &Scalar, 165 | partial_R: &Point, 166 | partial_public_key: &Point, 167 | agg_pubkey: &Point, 168 | ) -> Result<(), ProofError> { 169 | let k = Signature::k(&sig.R, agg_pubkey, message); 170 | let A = partial_public_key; 171 | 172 | let kA = A * k * a; 173 | 174 | let R_plus_kA = kA + partial_R; 175 | let sG = &sig.s * Point::generator(); 176 | 177 | if R_plus_kA == sG { 178 | Ok(()) 179 | } else { 180 | Err(ProofError) 181 | } 182 | } 183 | 184 | mod test; 185 | -------------------------------------------------------------------------------- /src/protocols/aggsig/test.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Multisig ed25519 3 | 4 | Copyright 2018 by Kzen Networks 5 | 6 | This file is part of Multi party eddsa library 7 | (https://github.com/KZen-networks/multisig-schnorr) 8 | 9 | Multisig Schnorr is free software: you can redistribute 10 | it and/or modify it under the terms of the GNU General Public 11 | License as published by the Free Software Foundation, either 12 | version 3 of the License, or (at your option) any later version. 13 | 14 | @license GPL-3.0+ 15 | */ 16 | 17 | #[cfg(test)] 18 | mod tests { 19 | use std::convert::TryInto; 20 | 21 | use curv::cryptographic_primitives::commitments::{ 22 | hash_commitment::HashCommitment, traits::Commitment, 23 | }; 24 | use curv::elliptic::curves::{Ed25519, Point, Scalar}; 25 | use curv::{arithmetic::Converter, BigInt}; 26 | use hex::decode; 27 | use itertools::{izip, MultiUnzip}; 28 | use rand::{Rng, RngCore}; 29 | use sha2::Sha512; 30 | 31 | use protocols::tests::deterministic_fast_rand; 32 | use protocols::{ 33 | aggsig::{self, KeyAgg}, 34 | tests::verify_dalek, 35 | ExpandedKeyPair, Signature, 36 | }; 37 | 38 | #[test] 39 | fn test_ed25519_generate_keypair_from_seed() { 40 | let priv_str = "48ab347b2846f96b7bcd00bf985c52b83b92415c5c914bc1f3b09e186cf2b14f"; // Private Key 41 | let priv_dec: [u8; 32] = decode(priv_str).unwrap().try_into().unwrap(); 42 | 43 | let expected_pubkey_hex = 44 | "c7d17a93f129527bf7ca413f34a0f23c8462a9c3a3edd4f04550a43cdd60b27a"; 45 | let expected_pubkey = decode(expected_pubkey_hex).unwrap(); 46 | 47 | let party1_keys = ExpandedKeyPair::create_from_private_key(priv_dec); 48 | let mut pubkey = party1_keys.public_key.y_coord().unwrap().to_bytes(); 49 | // Reverse is requried because bigInt returns hex in big endian while pubkeys are usually little endian. 50 | pubkey.reverse(); 51 | 52 | assert_eq!(pubkey, expected_pubkey,); 53 | } 54 | 55 | #[test] 56 | fn test_sign_single_verify_dalek() { 57 | let mut rng = deterministic_fast_rand("test_sign_single_verify_dalek", None); 58 | 59 | let mut msg = [0u8; 64]; 60 | let mut privkey = [0u8; 32]; 61 | for msg_len in 0..msg.len() { 62 | let msg = &mut msg[..msg_len]; 63 | for _ in 0..20 { 64 | rng.fill_bytes(&mut privkey); 65 | rng.fill_bytes(msg); 66 | let keypair = ExpandedKeyPair::create_from_private_key(privkey); 67 | let signature = aggsig::sign_single(msg, &keypair); 68 | assert!(verify_dalek(&keypair.public_key, &signature, msg)); 69 | } 70 | } 71 | } 72 | 73 | #[test] 74 | fn test_sign_aggsig_verify_dalek() { 75 | let mut rng = deterministic_fast_rand("test_sign_aggsig_verify_dalek", None); 76 | 77 | let mut msg = [0u8; 64]; 78 | const MAX_SIGNERS: usize = 8; 79 | let mut privkeys = [[0u8; 32]; MAX_SIGNERS]; 80 | for msg_len in 0..msg.len() { 81 | let msg = &mut msg[..msg_len]; 82 | for signers in 1..MAX_SIGNERS { 83 | let privkeys = &mut privkeys[..signers]; 84 | 85 | privkeys.iter_mut().for_each(|p| rng.fill_bytes(p)); 86 | rng.fill_bytes(msg); 87 | // Generate keypairs and pubkeys_list from the private keys. 88 | let keypairs: Vec<_> = privkeys 89 | .iter() 90 | .copied() 91 | .map(ExpandedKeyPair::create_from_private_key) 92 | .collect(); 93 | let pubkeys_list: Vec<_> = keypairs.iter().map(|k| k.public_key.clone()).collect(); 94 | 95 | // Aggregate the public keys 96 | let agg_keys: Vec<_> = (0..signers) 97 | .map(|i| KeyAgg::key_aggregation_n(&pubkeys_list, i)) 98 | .collect(); 99 | 100 | // Make sure all parties generated the same aggregated public key 101 | assert!(agg_keys[1..] 102 | .iter() 103 | .all(|agg_key| agg_key.apk == agg_keys[0].apk)); 104 | 105 | // Start signing 106 | 107 | // Generate the first and second messages 108 | let (Rs, rs, first_msgs, second_msgs): (Vec<_>, Vec<_>, Vec<_>, Vec<_>) = keypairs 109 | .iter() 110 | .map(|keypair| { 111 | let (ephemeral, sign_first, sign_second) = 112 | aggsig::create_ephemeral_key_and_commit_rng(keypair, msg, &mut rng); 113 | (ephemeral.R, ephemeral.r, sign_first, sign_second) 114 | }) 115 | .multiunzip(); 116 | // Send first first msg, wait to recieve everyone else's and then send second msg. 117 | 118 | // Verify that the second message matches the first message. 119 | first_msgs 120 | .iter() 121 | .zip(second_msgs.iter()) 122 | .for_each(|(first_msg, second_msg)| { 123 | assert!(test_com( 124 | &second_msg.R, 125 | &second_msg.blind_factor, 126 | &first_msg.commitment 127 | )); 128 | }); 129 | // Each party aggregates the Rs to get the aggregate R 130 | let agg_R = aggsig::get_R_tot(&Rs); 131 | 132 | // keypairs 133 | let partial_sigs: Vec<_> = izip!(keypairs.iter(), rs.iter(), agg_keys.iter()) 134 | .map(|(keypair, r, aggkey)| { 135 | aggsig::partial_sign(r, keypair, &aggkey.hash, &agg_R, &aggkey.apk, msg) 136 | }) 137 | .collect(); 138 | 139 | let signature = aggsig::add_signature_parts(&partial_sigs); 140 | assert!(verify_dalek(&agg_keys[0].apk, &signature, msg)); 141 | } 142 | } 143 | } 144 | 145 | #[test] 146 | fn test_ed25519_one_party() { 147 | let message: [u8; 4] = [79, 77, 69, 82]; 148 | let party1_keys = ExpandedKeyPair::create(); 149 | let signature = aggsig::sign_single(&message, &party1_keys); 150 | assert!(signature.verify(&message, &party1_keys.public_key).is_ok()); 151 | } 152 | 153 | #[test] 154 | fn test_multiparty_signing_for_two_parties() { 155 | let mut rng = deterministic_fast_rand("test_multiparty_signing_for_two_parties", None); 156 | for _i in 0..128 { 157 | test_multiparty_signing_for_two_parties_internal(&mut rng); 158 | } 159 | } 160 | 161 | fn test_multiparty_signing_for_two_parties_internal(rng: &mut impl Rng) { 162 | let message: [u8; 4] = [79, 77, 69, 82]; 163 | 164 | // round 0: generate signing keys 165 | let party1_key = ExpandedKeyPair::create(); 166 | let party2_key = ExpandedKeyPair::create(); 167 | 168 | // round 1: send commitments to ephemeral public keys 169 | let (party1_ephemeral_key, party1_sign_first_message, party1_sign_second_message) = 170 | aggsig::create_ephemeral_key_and_commit_rng(&party1_key, &message, rng); 171 | let (party2_ephemeral_key, party2_sign_first_message, party2_sign_second_message) = 172 | aggsig::create_ephemeral_key_and_commit_rng(&party2_key, &message, rng); 173 | 174 | let party1_commitment = &party1_sign_first_message.commitment; 175 | let party2_commitment = &party2_sign_first_message.commitment; 176 | 177 | // round 2: send ephemeral public keys and check commitments 178 | assert!(test_com( 179 | &party2_sign_second_message.R, 180 | &party2_sign_second_message.blind_factor, 181 | party2_commitment 182 | )); 183 | assert!(test_com( 184 | &party1_sign_second_message.R, 185 | &party1_sign_second_message.blind_factor, 186 | party1_commitment 187 | )); 188 | 189 | // compute apk: 190 | let pks = [party1_key.public_key.clone(), party2_key.public_key.clone()]; 191 | let party1_key_agg = KeyAgg::key_aggregation_n(&pks, 0); 192 | let party2_key_agg = KeyAgg::key_aggregation_n(&pks, 1); 193 | assert_eq!(party1_key_agg.apk, party2_key_agg.apk); 194 | // compute R' = sum(Ri): 195 | let Ri = [party1_ephemeral_key.R, party2_ephemeral_key.R]; 196 | // each party i should run this: 197 | let R_tot = aggsig::get_R_tot(&Ri); 198 | let s1 = aggsig::partial_sign( 199 | &party1_ephemeral_key.r, 200 | &party1_key, 201 | &party1_key_agg.hash, 202 | &R_tot, 203 | &party1_key_agg.apk, 204 | &message, 205 | ); 206 | let s2 = aggsig::partial_sign( 207 | &party2_ephemeral_key.r, 208 | &party2_key, 209 | &party2_key_agg.hash, 210 | &R_tot, 211 | &party2_key_agg.apk, 212 | &message, 213 | ); 214 | 215 | let s = [s1, s2]; 216 | let signature = aggsig::add_signature_parts(&s); 217 | 218 | // verify: 219 | assert!(signature.verify(&message, &party1_key_agg.apk).is_ok()) 220 | } 221 | 222 | #[test] 223 | fn test_multiparty_signing_for_three_parties() { 224 | let mut rng = deterministic_fast_rand("test_multiparty_signing_for_three_parties", None); 225 | for _i in 0..128 { 226 | test_multiparty_signing_for_three_parties_internal(&mut rng); 227 | } 228 | } 229 | 230 | fn test_multiparty_signing_for_three_parties_internal(rng: &mut impl Rng) { 231 | let message: [u8; 4] = [79, 77, 69, 82]; 232 | 233 | // round 0: generate signing keys 234 | let party1_key = ExpandedKeyPair::create(); 235 | let party2_key = ExpandedKeyPair::create(); 236 | let party3_key = ExpandedKeyPair::create(); 237 | 238 | // round 1: send commitments to ephemeral public keys 239 | let (party1_ephemeral_key, party1_sign_first_message, party1_sign_second_message) = 240 | aggsig::create_ephemeral_key_and_commit_rng(&party1_key, &message, rng); 241 | let (party2_ephemeral_key, party2_sign_first_message, party2_sign_second_message) = 242 | aggsig::create_ephemeral_key_and_commit_rng(&party2_key, &message, rng); 243 | let (party3_ephemeral_key, party3_sign_first_message, party3_sign_second_message) = 244 | aggsig::create_ephemeral_key_and_commit_rng(&party3_key, &message, rng); 245 | 246 | let party1_commitment = &party1_sign_first_message.commitment; 247 | let party2_commitment = &party2_sign_first_message.commitment; 248 | let party3_commitment = &party3_sign_first_message.commitment; 249 | 250 | // round 2: send ephemeral public keys and check commitments 251 | assert!(test_com( 252 | &party2_sign_second_message.R, 253 | &party2_sign_second_message.blind_factor, 254 | party2_commitment 255 | )); 256 | assert!(test_com( 257 | &party1_sign_second_message.R, 258 | &party1_sign_second_message.blind_factor, 259 | party1_commitment 260 | )); 261 | assert!(test_com( 262 | &party3_sign_second_message.R, 263 | &party3_sign_second_message.blind_factor, 264 | party3_commitment 265 | )); 266 | 267 | // compute apk: 268 | let pks = [ 269 | party1_key.public_key.clone(), 270 | party2_key.public_key.clone(), 271 | party3_key.public_key.clone(), 272 | ]; 273 | let party1_key_agg = KeyAgg::key_aggregation_n(&pks, 0); 274 | let party2_key_agg = KeyAgg::key_aggregation_n(&pks, 1); 275 | let party3_key_agg = KeyAgg::key_aggregation_n(&pks, 2); 276 | assert_eq!(party1_key_agg.apk, party2_key_agg.apk); 277 | assert_eq!(party1_key_agg.apk, party3_key_agg.apk); 278 | // compute R' = sum(Ri): 279 | let Ri = [ 280 | party1_ephemeral_key.R, 281 | party2_ephemeral_key.R, 282 | party3_ephemeral_key.R, 283 | ]; 284 | // each party i should run this: 285 | let R_tot = aggsig::get_R_tot(&Ri); 286 | let s1 = aggsig::partial_sign( 287 | &party1_ephemeral_key.r, 288 | &party1_key, 289 | &party1_key_agg.hash, 290 | &R_tot, 291 | &party1_key_agg.apk, 292 | &message, 293 | ); 294 | let s2 = aggsig::partial_sign( 295 | &party2_ephemeral_key.r, 296 | &party2_key, 297 | &party2_key_agg.hash, 298 | &R_tot, 299 | &party2_key_agg.apk, 300 | &message, 301 | ); 302 | let s3 = aggsig::partial_sign( 303 | &party3_ephemeral_key.r, 304 | &party3_key, 305 | &party3_key_agg.hash, 306 | &R_tot, 307 | &party3_key_agg.apk, 308 | &message, 309 | ); 310 | 311 | let s = [s1, s2, s3]; 312 | let signature = aggsig::add_signature_parts(&s); 313 | 314 | // verify: 315 | assert!(signature.verify(&message, &party1_key_agg.apk).is_ok()) 316 | } 317 | 318 | #[test] 319 | fn test_verify_standard_sig() { 320 | // msg hash:05b5d2c43079b8d696ebb21f6e1d1feb7c4aa7c5ba47eea4940f549ebb212e3d 321 | // sk: ab2add54327c0baa15d21961f820d8fa231de60450dadd7ce2dec12a9934dddc3b97c9279bbb4b501b84d7c3506d5f018a1e1df1d86daab5e97d888af44887eb 322 | // pk: 3b97c9279bbb4b501b84d7c3506d5f018a1e1df1d86daab5e97d888af44887eb 323 | // sig: 311b4390d1d92ee3c56d66e22c7cacf13fba86c44b61769b81aa26680af02d1b5a180452743fac943b53728e4cbea288a566ba49f7695808d53b3f9f1cd6ed02 324 | // R = 311b4390d1d92ee3c56d66e22c7cacf13fba86c44b61769b81aa26680af02d1b 325 | // s = 5a180452743fac943b53728e4cbea288a566ba49f7695808d53b3f9f1cd6ed02 326 | 327 | let msg_str = "05b5d2c43079b8d696ebb21f6e1d1feb7c4aa7c5ba47eea4940f549ebb212e3d"; 328 | let message = decode(msg_str).unwrap(); 329 | 330 | let pk_str = "3b97c9279bbb4b501b84d7c3506d5f018a1e1df1d86daab5e97d888af44887eb"; 331 | let pk_dec = decode(pk_str).unwrap(); 332 | let pk = Point::from_bytes(&pk_dec[..]).unwrap(); 333 | 334 | let R_str = "311b4390d1d92ee3c56d66e22c7cacf13fba86c44b61769b81aa26680af02d1b"; 335 | let R_dec = decode(R_str).unwrap(); 336 | let R = Point::from_bytes(&R_dec[..]).unwrap(); 337 | 338 | let s_str = "5a180452743fac943b53728e4cbea288a566ba49f7695808d53b3f9f1cd6ed02"; 339 | let mut s_dec = decode(s_str).unwrap(); 340 | s_dec.reverse(); 341 | let s_bn = BigInt::from_bytes(&s_dec[..]); 342 | let s = Scalar::from(&s_bn); 343 | 344 | let sig = Signature { R, s }; 345 | assert!(sig.verify(&message, &pk).is_ok()) 346 | } 347 | 348 | pub fn test_com(r_to_test: &Point, blind_factor: &BigInt, comm: &BigInt) -> bool { 349 | let computed_comm = 350 | &HashCommitment::::create_commitment_with_user_defined_randomness( 351 | &r_to_test.y_coord().unwrap(), 352 | blind_factor, 353 | ); 354 | computed_comm == comm 355 | } 356 | } 357 | -------------------------------------------------------------------------------- /src/protocols/mod.rs: -------------------------------------------------------------------------------- 1 | #![allow(non_snake_case)] 2 | /* 3 | Multisig ed25519 4 | 5 | Copyright 2018 by Kzen Networks 6 | 7 | This file is part of Multisig Schnorr library 8 | (https://github.com/KZen-networks/multisig-schnorr) 9 | 10 | Multisig Schnorr is free software: you can redistribute 11 | it and/or modify it under the terms of the GNU General Public 12 | License as published by the Free Software Foundation, either 13 | version 3 of the License, or (at your option) any later version. 14 | 15 | @license GPL-3.0+ 16 | */ 17 | use curv::arithmetic::Converter; 18 | use curv::cryptographic_primitives::proofs::ProofError; 19 | use curv::elliptic::curves::{Ed25519, Point, Scalar}; 20 | use curv::BigInt; 21 | use rand::{thread_rng, Rng}; 22 | use sha2::{Digest, Sha512}; 23 | 24 | // simple ed25519 based on rfc8032 25 | // reference implementation: https://ed25519.cr.yp.to/python/ed25519.py 26 | pub mod aggsig; 27 | pub mod multisig; 28 | pub mod musig2; 29 | pub mod thresholdsig; 30 | 31 | #[derive(Clone, Debug, Serialize, Deserialize)] 32 | pub struct ExpandedPrivateKey { 33 | pub prefix: Scalar, 34 | private_key: Scalar, 35 | } 36 | 37 | #[derive(Clone, Debug, Serialize, Deserialize)] 38 | pub struct ExpandedKeyPair { 39 | pub public_key: Point, 40 | expanded_private_key: ExpandedPrivateKey, 41 | } 42 | 43 | impl ExpandedKeyPair { 44 | pub fn create() -> ExpandedKeyPair { 45 | let secret = thread_rng().gen(); 46 | Self::create_from_private_key(secret) 47 | } 48 | 49 | pub fn create_from_private_key(secret: [u8; 32]) -> ExpandedKeyPair { 50 | let h = Sha512::new().chain(secret).finalize(); 51 | let mut private_key: [u8; 32] = [0u8; 32]; 52 | let mut prefix: [u8; 32] = [0u8; 32]; 53 | prefix.copy_from_slice(&h[32..64]); 54 | private_key.copy_from_slice(&h[0..32]); 55 | private_key[0] &= 248; 56 | private_key[31] &= 63; 57 | private_key[31] |= 64; 58 | let private_key = Scalar::from_bytes(&private_key) 59 | .expect("private_key is the right length, so can't fail"); 60 | let prefix = 61 | Scalar::from_bytes(&prefix).expect("prefix is the right length, so can't fail"); 62 | let public_key = Point::generator() * &private_key; 63 | ExpandedKeyPair { 64 | public_key, 65 | expanded_private_key: ExpandedPrivateKey { 66 | prefix, 67 | private_key, 68 | }, 69 | } 70 | } 71 | } 72 | 73 | #[derive(Clone, PartialEq, Debug, Serialize, Deserialize)] 74 | pub struct Signature { 75 | pub R: Point, 76 | pub s: Scalar, 77 | } 78 | 79 | impl Signature { 80 | pub fn verify(&self, message: &[u8], public_key: &Point) -> Result<(), ProofError> { 81 | let k = Self::k(&self.R, public_key, message); 82 | let A = public_key; 83 | 84 | let kA = A * k; 85 | let R_plus_kA = &kA + &self.R; 86 | let sG = &self.s * Point::generator(); 87 | 88 | if R_plus_kA == sG { 89 | Ok(()) 90 | } else { 91 | Err(ProofError) 92 | } 93 | } 94 | 95 | pub(crate) fn k(R: &Point, PK: &Point, message: &[u8]) -> Scalar { 96 | let mut k = Sha512::new() 97 | .chain(&*R.to_bytes(true)) 98 | .chain(&*PK.to_bytes(true)) 99 | .chain(message) 100 | .finalize(); 101 | // reverse because BigInt uses BigEndian. 102 | k.reverse(); 103 | // This will reduce it mod the group order. 104 | Scalar::from_bigint(&BigInt::from_bytes(&k)) 105 | } 106 | } 107 | 108 | #[cfg(test)] 109 | pub(crate) mod tests { 110 | 111 | use curv::elliptic::curves::{Ed25519, Point, Scalar}; 112 | use ed25519_dalek::Verifier; 113 | use rand::{thread_rng, Rng}; 114 | use rand_xoshiro::rand_core::{RngCore, SeedableRng}; 115 | use rand_xoshiro::Xoshiro256PlusPlus; 116 | 117 | use protocols::{ExpandedKeyPair, Signature}; 118 | 119 | pub fn verify_dalek(pk: &Point, sig: &Signature, msg: &[u8]) -> bool { 120 | let mut sig_bytes = [0u8; 64]; 121 | sig_bytes[..32].copy_from_slice(&*sig.R.to_bytes(true)); 122 | sig_bytes[32..].copy_from_slice(&sig.s.to_bytes()); 123 | 124 | let dalek_pub = ed25519_dalek::PublicKey::from_bytes(&*pk.to_bytes(true)).unwrap(); 125 | let dalek_sig = ed25519_dalek::Signature::from_bytes(&sig_bytes).unwrap(); 126 | 127 | dalek_pub.verify(msg, &dalek_sig).is_ok() 128 | } 129 | 130 | /// This will generate a fast deterministic rng and will print the seed, 131 | /// if a test fails, pass in the printed seed to reproduce. 132 | pub fn deterministic_fast_rand(name: &str, seed: Option) -> impl Rng { 133 | let seed = seed.unwrap_or_else(|| thread_rng().gen()); 134 | println!("{} seed: {}", name, seed); 135 | Xoshiro256PlusPlus::seed_from_u64(seed) 136 | } 137 | 138 | #[test] 139 | fn test_generate_pubkey_dalek() { 140 | let mut rng = deterministic_fast_rand("test_generate_pubkey_dalek", None); 141 | 142 | let mut privkey = [0u8; 32]; 143 | for _ in 0..4096 { 144 | rng.fill_bytes(&mut privkey); 145 | let zengo_keypair = ExpandedKeyPair::create_from_private_key(privkey); 146 | let dalek_secret = ed25519_dalek::SecretKey::from_bytes(&privkey) 147 | .expect("Can only fail if bytes.len()<32"); 148 | let dalek_pub = ed25519_dalek::PublicKey::from(&dalek_secret); 149 | 150 | let zengo_pub_serialized = &*zengo_keypair.public_key.to_bytes(true); 151 | let dalek_pub_serialized = dalek_pub.to_bytes(); 152 | 153 | assert_eq!(zengo_pub_serialized, dalek_pub_serialized); 154 | } 155 | } 156 | 157 | #[test] 158 | fn test_verify_dalek_signatures() { 159 | let mut rng = deterministic_fast_rand("test_verify_dalek_signatures", None); 160 | 161 | let mut msg = [0u8; 64]; 162 | let mut privkey = [0u8; 32]; 163 | for msg_len in 0..msg.len() { 164 | let msg = &mut msg[..msg_len]; 165 | for _ in 0..20 { 166 | rng.fill_bytes(&mut privkey); 167 | rng.fill_bytes(msg); 168 | let dalek_secret = ed25519_dalek::ExpandedSecretKey::from( 169 | &ed25519_dalek::SecretKey::from_bytes(&privkey) 170 | .expect("Can only fail if bytes.len()<32"), 171 | ); 172 | let dalek_pub = ed25519_dalek::PublicKey::from(&dalek_secret); 173 | let dalek_sig = dalek_secret.sign(msg, &dalek_pub); 174 | 175 | let zengo_sig = Signature { 176 | R: Point::from_bytes(&dalek_sig.as_ref()[..32]).unwrap(), 177 | s: Scalar::from_bytes(&dalek_sig.as_ref()[32..]).unwrap(), 178 | }; 179 | let zengo_pubkey = Point::from_bytes(&dalek_pub.to_bytes()).unwrap(); 180 | zengo_sig.verify(msg, &zengo_pubkey).unwrap(); 181 | } 182 | } 183 | } 184 | } 185 | -------------------------------------------------------------------------------- /src/protocols/multisig/mod.rs: -------------------------------------------------------------------------------- 1 | #![allow(non_snake_case)] 2 | /* 3 | multi-party-ed25519 4 | 5 | Copyright 2018 by Kzen Networks 6 | 7 | This file is part of multi-party-ed25519 library 8 | (https://github.com/KZen-networks/multisig-schnorr) 9 | 10 | multi-party-ed25519 is free software: you can redistribute 11 | it and/or modify it under the terms of the GNU General Public 12 | License as published by the Free Software Foundation, either 13 | version 3 of the License, or (at your option) any later version. 14 | 15 | @license GPL-3.0+ 16 | */ 17 | //! Schnorr {n,n}-Signatures based on Accountable-Subgroup Multisignatures 18 | //! 19 | //See (https://pdfs.semanticscholar.org/6bf4/f9450e7a8e31c106a8670b961de4735589cf.pdf) 20 | 21 | use super::ExpandedKeyPair; 22 | 23 | use curv::cryptographic_primitives::hashing::DigestExt; 24 | use curv::elliptic::curves::{Ed25519, Point, Scalar}; 25 | use curv::BigInt; 26 | use protocols::multisig; 27 | 28 | use sha2::{digest::Digest, Sha512}; 29 | 30 | // I is a private key and public key keypair, X is a commitment of the form X = xG used only in key generation (see p11 in the paper) 31 | #[derive(Debug, Clone)] 32 | pub struct Keys { 33 | pub I: ExpandedKeyPair, 34 | pub X: SingleKeyPair, 35 | } 36 | 37 | #[derive(Debug, Clone)] 38 | pub struct SingleKeyPair { 39 | pub public_key: Point, 40 | private_key: Scalar, 41 | } 42 | impl SingleKeyPair { 43 | pub fn create() -> SingleKeyPair { 44 | let ec_point = Point::generator(); 45 | let private_key = Scalar::random(); 46 | let public_key = ec_point * &private_key; 47 | SingleKeyPair { 48 | public_key, 49 | private_key, 50 | } 51 | } 52 | pub fn create_from_private_key(private_key: Scalar) -> SingleKeyPair { 53 | let g = Point::generator(); 54 | let public_key = g * &private_key; 55 | 56 | SingleKeyPair { 57 | public_key, 58 | private_key, 59 | } 60 | } 61 | } 62 | 63 | impl ExpandedKeyPair { 64 | pub fn update_key_pair(&mut self, to_add: Scalar) { 65 | self.expanded_private_key.private_key = to_add + &self.expanded_private_key.private_key; 66 | let g = Point::generator(); 67 | self.public_key = g * &self.expanded_private_key.private_key; 68 | } 69 | } 70 | 71 | impl Keys { 72 | pub fn create() -> Keys { 73 | let I = ExpandedKeyPair::create(); 74 | let X = SingleKeyPair::create(); 75 | Keys { I, X } 76 | } 77 | 78 | pub fn create_from_private_keys(priv_I: [u8; 32], priv_X: Scalar) -> Keys { 79 | let I = ExpandedKeyPair::create_from_private_key(priv_I); 80 | let X = SingleKeyPair::create_from_private_key(priv_X); 81 | Keys { I, X } 82 | } 83 | 84 | pub fn create_from(secret_share: [u8; 32]) -> Keys { 85 | let I = ExpandedKeyPair::create_from_private_key(secret_share); 86 | let X = SingleKeyPair::create(); 87 | Keys { I, X } 88 | } 89 | 90 | pub fn create_signing_key(keys: &Keys, eph_key: &EphKey) -> Keys { 91 | Keys { 92 | I: keys.I.clone(), 93 | X: eph_key.eph_key_pair.clone(), 94 | } 95 | } 96 | 97 | pub fn broadcast(keys: Keys) -> Vec> { 98 | return vec![keys.I.public_key, keys.X.public_key]; 99 | } 100 | 101 | pub fn collect_and_compute_challenge(ix_vec: &[Vec>]) -> Scalar { 102 | let concat_vec = ix_vec.iter().fold(Vec::new(), |mut acc, x| { 103 | acc.extend_from_slice(x); 104 | acc 105 | }); 106 | multisig::hash_4(&concat_vec) 107 | } 108 | } 109 | 110 | pub fn partial_sign(keys: &Keys, e: Scalar) -> Scalar { 111 | e * &keys.I.expanded_private_key.private_key + &keys.X.private_key 112 | } 113 | 114 | pub fn verify<'a>(I: &Point, sig: &Signature, e: &Scalar) -> Result<(), &'a str> { 115 | let X = &sig.X; 116 | let y = &sig.y; 117 | let base_point = Point::generator(); 118 | let yG = base_point * y; 119 | let eI = I * e; 120 | let X_plus_eI = X + &eI; 121 | if yG == X_plus_eI { 122 | Ok(()) 123 | } else { 124 | Err("error verification") 125 | } 126 | } 127 | 128 | fn hash_4(key_list: &[Point]) -> Scalar { 129 | let four_fe: Scalar = Scalar::from_bigint(&BigInt::from(4)); 130 | let base_point = Point::generator(); 131 | let four_ge = base_point * four_fe; 132 | Sha512::new() 133 | .chain_point(&four_ge) 134 | .chain_points(key_list) 135 | .result_scalar() 136 | } 137 | 138 | pub struct EphKey { 139 | pub eph_key_pair: SingleKeyPair, 140 | } 141 | 142 | impl EphKey { 143 | //signing step 1 144 | pub fn gen_commit(key_gen_key_pair: &ExpandedKeyPair, message: &BigInt) -> EphKey { 145 | // here we deviate from the spec, by introducing non-deterministic element (random number) 146 | // to the nonce 147 | let r = Sha512::new() 148 | .chain_scalar(&key_gen_key_pair.expanded_private_key.prefix) 149 | .chain_bigint(message) 150 | .chain_scalar(&Scalar::::random()) 151 | .result_bigint(); 152 | let r_fe = Scalar::from_bigint(&r); 153 | let g = Point::generator(); 154 | let eph_key_pair = SingleKeyPair { 155 | public_key: g * &r_fe, 156 | private_key: r_fe, 157 | }; 158 | EphKey { eph_key_pair } 159 | } 160 | //signing steps 2,3 161 | // we treat S as a list of public keys and compute a sum. 162 | pub fn compute_joint_comm_e( 163 | mut pub_key_vec: Vec>, 164 | mut eph_pub_key_vec: Vec>, 165 | message: &BigInt, 166 | ) -> (Point, Point, Scalar) { 167 | let first_pub_key = pub_key_vec.remove(0); 168 | let sum_pub = pub_key_vec.iter().fold(first_pub_key, |acc, x| acc + x); 169 | let first_eph_pub_key = eph_pub_key_vec.remove(0); 170 | let sum_pub_eph = eph_pub_key_vec 171 | .iter() 172 | .fold(first_eph_pub_key, |acc, x| acc + x); 173 | //TODO: maybe there is a better way? 174 | let m_fe = Scalar::from_bigint(message); 175 | let base_point = Point::generator(); 176 | let m_ge = base_point * m_fe; 177 | let e = multisig::hash_4(&[sum_pub_eph.clone(), m_ge, sum_pub.clone()]); 178 | (sum_pub, sum_pub_eph, e) 179 | } 180 | 181 | pub fn partial_sign( 182 | &self, 183 | local_keys: &ExpandedKeyPair, 184 | es: Scalar, 185 | ) -> Scalar { 186 | es * &local_keys.expanded_private_key.private_key + &self.eph_key_pair.private_key 187 | } 188 | 189 | pub fn add_signature_parts(sig_vec: Vec>) -> Scalar { 190 | let mut sig_vec_c = sig_vec; 191 | let first_sig = sig_vec_c.remove(0); 192 | 193 | sig_vec_c.iter().fold(first_sig, |acc, x| acc + x) 194 | } 195 | } 196 | 197 | pub struct Signature { 198 | X: Point, 199 | y: Scalar, 200 | } 201 | 202 | impl Signature { 203 | pub fn set_signature(X: &Point, y: &Scalar) -> Signature { 204 | Signature { 205 | X: X.clone(), 206 | y: y.clone(), 207 | } 208 | } 209 | } 210 | 211 | mod test; 212 | -------------------------------------------------------------------------------- /src/protocols/multisig/test.rs: -------------------------------------------------------------------------------- 1 | #![allow(non_snake_case)] 2 | /* 3 | multi-party-ed25519 4 | 5 | Copyright 2018 by Kzen Networks 6 | 7 | This file is part of multi-party-ed25519 library 8 | (https://github.com/KZen-networks/multisig-schnorr) 9 | 10 | multi-party-ed25519 is free software: you can redistribute 11 | it and/or modify it under the terms of the GNU General Public 12 | License as published by the Free Software Foundation, either 13 | version 3 of the License, or (at your option) any later version. 14 | 15 | @license GPL-3.0+ 16 | */ 17 | #[cfg(test)] 18 | mod tests { 19 | 20 | use curv::arithmetic::Converter; 21 | use curv::cryptographic_primitives::hashing::merkle_tree::MT256; 22 | use curv::cryptographic_primitives::hashing::DigestExt; 23 | use curv::elliptic::curves::Scalar; 24 | use curv::BigInt; 25 | use protocols::multisig::{partial_sign, verify, EphKey, Keys, Signature}; 26 | use sha2::{digest::Digest, Sha256}; 27 | 28 | #[test] 29 | fn two_party_key_gen() { 30 | for _i in 0..256 { 31 | two_party_key_gen_internal(); 32 | } 33 | } 34 | 35 | fn two_party_key_gen_internal() { 36 | let message_vec = vec![79, 77, 69, 82]; 37 | let message_bn = BigInt::from_bytes(&message_vec[..]); 38 | let message = Sha256::new().chain_bigint(&message_bn).result_bigint(); 39 | 40 | // party1 key gen: 41 | let keys_1 = Keys::create(); 42 | 43 | keys_1.clone().I.update_key_pair(Scalar::zero()); 44 | 45 | let broadcast1 = Keys::broadcast(keys_1.clone()); 46 | // party2 key gen: 47 | let keys_2 = Keys::create(); 48 | let broadcast2 = Keys::broadcast(keys_2.clone()); 49 | let ix_vec = vec![broadcast1, broadcast2]; 50 | let e = Keys::collect_and_compute_challenge(&ix_vec); 51 | 52 | let y1 = partial_sign(&keys_1, e.clone()); 53 | let y2 = partial_sign(&keys_2, e.clone()); 54 | let sig1 = Signature::set_signature(&keys_1.X.public_key, &y1); 55 | let sig2 = Signature::set_signature(&keys_2.X.public_key, &y2); 56 | // partial verify 57 | assert!(verify(&keys_1.I.public_key, &sig1, &e).is_ok()); 58 | assert!(verify(&keys_2.I.public_key, &sig2, &e).is_ok()); 59 | 60 | // merkle tree (in case needed) 61 | 62 | let ge_vec = vec![(keys_1.I.public_key).clone(), (keys_2.I.public_key).clone()]; 63 | let mt256 = MT256::<_, Sha256>::create_tree(ge_vec); 64 | let proof1 = mt256.build_proof(keys_1.I.public_key.clone()).unwrap(); 65 | let proof2 = mt256.build_proof(keys_2.I.public_key.clone()).unwrap(); 66 | let root = mt256.get_root(); 67 | 68 | //TODO: reduce number of clones. 69 | // signing 70 | let party1_com = EphKey::gen_commit(&keys_1.I, &message); 71 | 72 | let party2_com = EphKey::gen_commit(&keys_2.I, &message); 73 | 74 | let eph_pub_key_vec = vec![ 75 | party1_com.eph_key_pair.public_key.clone(), 76 | party2_com.eph_key_pair.public_key.clone(), 77 | ]; 78 | let pub_key_vec = vec![keys_1.I.public_key.clone(), keys_2.I.public_key.clone()]; 79 | 80 | let (It, Xt, es) = EphKey::compute_joint_comm_e(pub_key_vec, eph_pub_key_vec, &message); 81 | 82 | let y1 = party1_com.partial_sign(&keys_1.I, es.clone()); 83 | let y2 = party2_com.partial_sign(&keys_2.I, es.clone()); 84 | let y = EphKey::add_signature_parts(vec![y1, y2]); 85 | let sig = Signature::set_signature(&Xt, &y); 86 | assert!(verify(&It, &sig, &es).is_ok()); 87 | 88 | assert!(proof1.verify(&root).is_ok()); 89 | assert!(proof2.verify(&root).is_ok()); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/protocols/musig2/mod.rs: -------------------------------------------------------------------------------- 1 | #![allow(non_snake_case)] 2 | 3 | //! Simple ed25519 4 | //! 5 | //! See https://tools.ietf.org/html/rfc8032 6 | //! This is an implementation of the Musig2 protocol as shown in https://eprint.iacr.org/2020/1261.pdf with the addition named Musig2* suggested in Section B of the paper. 7 | //! We implement the v = 2 (NUMBER_OF_NONCES) version, meaning there are 2 nonces generated by each party. 8 | 9 | use super::{ExpandedKeyPair, Signature}; 10 | use curv::arithmetic::Converter; 11 | use curv::elliptic::curves::{Ed25519, Point, Scalar}; 12 | use curv::BigInt; 13 | use protocols::Rng; 14 | use sha2::{digest::Digest, Sha512}; 15 | 16 | pub const NUMBER_OF_NONCES: usize = 2; 17 | 18 | #[derive(Clone, Debug, Serialize, Deserialize, PartialEq)] 19 | pub struct PublicKeyAgg { 20 | pub agg_public_key: Point, 21 | pub musig_coefficient: Scalar, 22 | } 23 | 24 | impl PublicKeyAgg { 25 | #[allow(clippy::unnecessary_sort_by)] 26 | pub fn key_aggregation_n( 27 | mut public_keys: Vec>, 28 | my_public_key: &Point, 29 | ) -> Option { 30 | // When there are at least 2 distinct public keys, it is secure to set the musig coefficient 31 | // of one them to 1 - saving a scalar multiplication operation - proof in Section B of the Musig2 paper linked above. 32 | // We therefore find the second public key (by lexicographic order) and later set its musig coefficient to 1. 33 | public_keys.sort_by(|left, right| left.to_bytes(false).cmp(&right.to_bytes(false))); 34 | let mut second_public_key = &public_keys[0]; 35 | for public_key in &public_keys[1..] { 36 | if *public_key.to_bytes(false) > *public_keys[0].to_bytes(false) { 37 | second_public_key = public_key; 38 | break; 39 | } 40 | } 41 | let mut found_my_pub_key = false; 42 | let (sum, my_coeff) = public_keys.iter().fold( 43 | (Point::::zero(), Scalar::::from(1)), 44 | |(mut agg_pub_key, mut musig_coeff), public_key| { 45 | let mut musig_coefficient: Scalar = Scalar::from(1); 46 | if public_key != second_public_key { 47 | let mut hasher = Sha512::new().chain(&[1]).chain(&*public_key.to_bytes(true)); 48 | for pk in &public_keys { 49 | hasher.update(&*pk.to_bytes(true)); 50 | } 51 | let mut hash_result = hasher.finalize(); 52 | // reverse because BigInt uses BigEndian. 53 | hash_result.reverse(); 54 | // This will reduce it mod the group order. 55 | musig_coefficient = Scalar::from_bigint(&BigInt::from_bytes(&hash_result)); 56 | } 57 | 58 | let party_i_public_key = public_key * &musig_coefficient; 59 | if public_key == my_public_key { 60 | musig_coeff = musig_coefficient; 61 | found_my_pub_key = true; 62 | } 63 | agg_pub_key = &agg_pub_key + party_i_public_key; 64 | (agg_pub_key, musig_coeff) 65 | }, 66 | ); 67 | if found_my_pub_key { 68 | Some(PublicKeyAgg { 69 | agg_public_key: sum, 70 | musig_coefficient: my_coeff, 71 | }) 72 | } else { 73 | None 74 | } 75 | } 76 | } 77 | #[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] 78 | pub struct PrivatePartialNonces { 79 | pub r: [Scalar; NUMBER_OF_NONCES], 80 | } 81 | 82 | #[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] 83 | pub struct PublicPartialNonces { 84 | pub R: [Point; NUMBER_OF_NONCES], 85 | } 86 | 87 | #[derive(Debug, Serialize, Deserialize, Clone, PartialEq)] 88 | pub struct PartialSignature { 89 | pub R: Point, 90 | pub my_partial_s: Scalar, 91 | } 92 | 93 | pub fn generate_partial_nonces( 94 | keys: &ExpandedKeyPair, 95 | message: Option<&[u8]>, 96 | ) -> (PrivatePartialNonces, PublicPartialNonces) { 97 | let mut rng = rand::thread_rng(); 98 | generate_partial_nonces_internal(keys, message, &mut rng) 99 | } 100 | 101 | fn generate_partial_nonces_internal( 102 | keys: &ExpandedKeyPair, 103 | message: Option<&[u8]>, 104 | rng: &mut impl Rng, 105 | ) -> (PrivatePartialNonces, PublicPartialNonces) { 106 | // here we deviate from the spec, by introducing non-deterministic element (random number) 107 | // to the nonce, this is important for MPC implementations 108 | let r: [Scalar; NUMBER_OF_NONCES] = [(); NUMBER_OF_NONCES].map(|_| { 109 | let mut hash_result = Sha512::new() 110 | .chain(&[2]) 111 | .chain(&*keys.expanded_private_key.prefix.to_bytes()) 112 | .chain(message.unwrap_or(&[])) 113 | .chain(rng.gen::<[u8; 32]>()) 114 | .finalize(); 115 | // reverse because BigInt uses big-endian 116 | hash_result.reverse(); 117 | // reduce modulu the group order 118 | Scalar::from_bigint(&BigInt::from_bytes(&hash_result)) 119 | }); 120 | let R: [Point; NUMBER_OF_NONCES] = r.clone().map(|scalar| Point::generator() * scalar); 121 | (PrivatePartialNonces { r }, PublicPartialNonces { R }) 122 | } 123 | 124 | pub fn partial_sign( 125 | nonces_from_other_parties: &[[Point; NUMBER_OF_NONCES]], 126 | my_private_partial_nonces: PrivatePartialNonces, 127 | my_public_partial_nonces: PublicPartialNonces, 128 | agg_public_key: &PublicKeyAgg, 129 | my_keypair: &ExpandedKeyPair, 130 | message: &[u8], 131 | ) -> PartialSignature { 132 | // Sum up the partial nonces from all parties index-wise, meaning, R[i] 133 | // is the sum of partial_nonces[i] from all parties 134 | let R: [Point; NUMBER_OF_NONCES] = nonces_from_other_parties.iter().fold( 135 | my_public_partial_nonces.R, 136 | |mut sum_partial_nonces, partial_nonce_array| { 137 | for (accum_nonce, nonce) in sum_partial_nonces.iter_mut().zip(partial_nonce_array) { 138 | *accum_nonce = &*accum_nonce + nonce; 139 | } 140 | sum_partial_nonces 141 | }, 142 | ); 143 | 144 | // Compute b as hash of nonces 145 | let mut hasher = Sha512::new() 146 | .chain(&[3]) 147 | .chain(&*agg_public_key.agg_public_key.to_bytes(false)); 148 | for nonce in &R { 149 | hasher.update(&*nonce.to_bytes(false)); 150 | } 151 | hasher.update(message); 152 | let mut hash_result = hasher.finalize(); 153 | // Reverse because BigInt uses big-endian 154 | hash_result.reverse(); 155 | // Reduce modulu the group order 156 | let b: Scalar = Scalar::from_bigint(&BigInt::from_bytes(&hash_result)); 157 | // Compute effective nonce 158 | // The idea is to compute R and r s.t. R = R_0 + b•R_1 + ... + b^(v-1)•R_v and r = r_0 + b•r_1 + ... + b^(v-1)•r_v 159 | let (effective_R, effective_r, _) = R[1..] 160 | .iter() 161 | .zip(my_private_partial_nonces.r[1..].iter()) 162 | .fold( 163 | ( 164 | R[0].clone(), 165 | my_private_partial_nonces.r[0].clone(), 166 | b.clone(), 167 | ), 168 | |(eff_R, eff_r, b_exp), (nonce_R_i, nonce_r_i)| { 169 | ( 170 | eff_R + &b_exp * nonce_R_i, 171 | &eff_r + &b_exp * nonce_r_i, 172 | b_exp * &b, 173 | ) 174 | }, 175 | ); 176 | // Compute Fiat-Shamir challenge of signature 177 | let sig_challenge = Signature::k(&effective_R, &agg_public_key.agg_public_key, message); 178 | 179 | // Computes the partial signature 180 | let partial_signature: Scalar = sig_challenge 181 | * &agg_public_key.musig_coefficient 182 | * &my_keypair.expanded_private_key.private_key 183 | + effective_r; 184 | PartialSignature { 185 | R: effective_R, 186 | my_partial_s: partial_signature, 187 | } 188 | } 189 | 190 | pub fn aggregate_partial_signatures( 191 | my_partial_sig: &PartialSignature, 192 | partial_sigs_from_other_parties: &[Scalar], 193 | ) -> Signature { 194 | let aggregate_signature = partial_sigs_from_other_parties 195 | .iter() 196 | .sum::>() 197 | + &my_partial_sig.my_partial_s; 198 | 199 | Signature { 200 | R: my_partial_sig.R.clone(), 201 | s: aggregate_signature, 202 | } 203 | } 204 | 205 | mod test; 206 | -------------------------------------------------------------------------------- /src/protocols/musig2/test.rs: -------------------------------------------------------------------------------- 1 | /* 2 | Multisig ed25519 3 | 4 | Copyright 2018 by Kzen Networks 5 | 6 | This file is part of Multi party eddsa library 7 | (https://github.com/KZen-networks/multisig-schnorr) 8 | 9 | Multisig Schnorr is free software: you can redistribute 10 | it and/or modify it under the terms of the GNU General Public 11 | License as published by the Free Software Foundation, either 12 | version 3 of the License, or (at your option) any later version. 13 | 14 | @license GPL-3.0+ 15 | */ 16 | 17 | #[cfg(test)] 18 | mod tests { 19 | use curv::arithmetic::Converter; 20 | use hex::decode; 21 | use rand::{Rng, RngCore}; 22 | use std::convert::TryInto; 23 | 24 | use protocols::tests::deterministic_fast_rand; 25 | use protocols::{ 26 | musig2::{self, PublicKeyAgg}, 27 | tests::verify_dalek, 28 | ExpandedKeyPair, 29 | }; 30 | 31 | #[test] 32 | fn test_ed25519_generate_keypair_from_seed() { 33 | let priv_str = "48ab347b2846f96b7bcd00bf985c52b83b92415c5c914bc1f3b09e186cf2b14f"; // Private Key 34 | let priv_dec: [u8; 32] = decode(priv_str).unwrap().try_into().unwrap(); 35 | 36 | let expected_pubkey_hex = 37 | "c7d17a93f129527bf7ca413f34a0f23c8462a9c3a3edd4f04550a43cdd60b27a"; 38 | let expected_pubkey = decode(expected_pubkey_hex).unwrap(); 39 | 40 | let party1_keys = ExpandedKeyPair::create_from_private_key(priv_dec); 41 | let mut pubkey = party1_keys.public_key.y_coord().unwrap().to_bytes(); 42 | // Reverse is requried because bigInt returns hex in big endian while pubkeys are usually little endian. 43 | pubkey.reverse(); 44 | 45 | assert_eq!(pubkey, expected_pubkey,); 46 | } 47 | 48 | #[test] 49 | fn test_sign_musig2_verify_dalek() { 50 | let mut rng = deterministic_fast_rand("test_sign_musig2_verify_dalek", None); 51 | 52 | let mut msg = [0u8; 36]; 53 | const MAX_SIGNERS: usize = 8; 54 | let mut privkeys = [[0u8; 32]; MAX_SIGNERS]; 55 | for msg_len in 0..msg.len() { 56 | let msg = &mut msg[..msg_len]; 57 | for signers in 1..MAX_SIGNERS { 58 | let privkeys = &mut privkeys[..signers]; 59 | 60 | privkeys.iter_mut().for_each(|p| rng.fill_bytes(p)); 61 | rng.fill_bytes(msg); 62 | 63 | // Generate keypairs and pubkeys_list from the private keys. 64 | let keypairs: Vec<_> = privkeys 65 | .iter() 66 | .copied() 67 | .map(ExpandedKeyPair::create_from_private_key) 68 | .collect(); 69 | let pubkeys_list: Vec<_> = keypairs.iter().map(|k| k.public_key.clone()).collect(); 70 | 71 | // Aggregate the public keys 72 | let agg_pub_keys: Vec<_> = pubkeys_list 73 | .iter() 74 | .map(|pubkey| { 75 | match PublicKeyAgg::key_aggregation_n(pubkeys_list.clone(), pubkey) { 76 | Some(agg_pub_key) => agg_pub_key, 77 | None => panic!("Missing party public key in key aggregation!"), 78 | } 79 | }) 80 | .collect(); 81 | 82 | // Make sure all parties generated the same aggregated public key 83 | assert!(agg_pub_keys[1..] 84 | .iter() 85 | .all(|agg_key| agg_key.agg_public_key == agg_pub_keys[0].agg_public_key)); 86 | 87 | // Generate the first messages - (partial nonces) 88 | let (private_partial_nonces, public_partial_nonces): (Vec<_>, Vec<_>) = keypairs 89 | .iter() 90 | .map(|keypair| { 91 | musig2::generate_partial_nonces_internal( 92 | keypair, 93 | Option::Some(msg), 94 | &mut rng, 95 | ) 96 | }) 97 | .unzip(); 98 | // Send partial nonces to everyone and wait to receive everyone else's 99 | 100 | // Compute partial signatures 101 | let partial_sigs: Vec<_> = keypairs 102 | .iter() 103 | .enumerate() 104 | .map(|(index, keypair)| { 105 | let mut pub_partial_nonces_without_signer = public_partial_nonces.clone(); 106 | let my_pub_partial_nonces = pub_partial_nonces_without_signer.remove(index); 107 | let partial_nonce_slice = pub_partial_nonces_without_signer 108 | .iter() 109 | .map(|partial_nonce| partial_nonce.R.clone()) 110 | .collect::>(); 111 | 112 | musig2::partial_sign( 113 | partial_nonce_slice.as_slice(), 114 | private_partial_nonces[index].clone(), 115 | my_pub_partial_nonces, 116 | &agg_pub_keys[index], 117 | keypair, 118 | msg, 119 | ) 120 | }) 121 | .collect(); 122 | 123 | // Compute signature 124 | let signatures: Vec<_> = (0..signers) 125 | .into_iter() 126 | .map(|index| { 127 | let mut partial_sigs_without_signer = partial_sigs.clone(); 128 | let my_partial_sig = partial_sigs_without_signer.remove(index); 129 | let partial_sig_slice = partial_sigs_without_signer 130 | .iter() 131 | .map(|partial_sig_other| partial_sig_other.my_partial_s.clone()) 132 | .collect::>(); 133 | 134 | musig2::aggregate_partial_signatures( 135 | &my_partial_sig, 136 | partial_sig_slice.as_slice(), 137 | ) 138 | }) 139 | .collect(); 140 | 141 | // Make sure all parties generated the same signature 142 | assert!(signatures[1..].iter().all(|sig| sig == &signatures[0])); 143 | // Verify signature 144 | assert!( 145 | signatures[0] 146 | .verify(msg, &agg_pub_keys[0].agg_public_key) 147 | .is_ok(), 148 | "Signature verification failed!" 149 | ); 150 | 151 | // Verify result against dalek 152 | assert!( 153 | verify_dalek(&agg_pub_keys[0].agg_public_key, &signatures[0], msg), 154 | "Dalek signature verification failed!" 155 | ); 156 | } 157 | } 158 | } 159 | 160 | #[test] 161 | fn test_multiparty_signing_for_two_parties() { 162 | let mut rng = deterministic_fast_rand("test_multiparty_signing_for_two_parties", None); 163 | for _i in 0..100 { 164 | test_multiparty_signing_for_two_parties_internal(&mut rng); 165 | } 166 | } 167 | 168 | fn test_multiparty_signing_for_two_parties_internal(rng: &mut impl Rng) { 169 | let message: [u8; 12] = [79, 77, 69, 82, 60, 61, 100, 156, 109, 125, 3, 19]; 170 | 171 | // round 0: generate signing keys generate nonces 172 | let party0_key = ExpandedKeyPair::create(); 173 | let party1_key = ExpandedKeyPair::create(); 174 | 175 | let (p0_private_nonces, p0_public_nonces) = 176 | musig2::generate_partial_nonces_internal(&party0_key, Option::Some(&message), rng); 177 | let (p1_private_nonces, p1_public_nonces) = 178 | musig2::generate_partial_nonces_internal(&party1_key, Option::Some(&message), rng); 179 | 180 | // compute aggregated public key: 181 | let pks = vec![party0_key.public_key.clone(), party1_key.public_key.clone()]; 182 | let party0_key_agg = 183 | match PublicKeyAgg::key_aggregation_n(pks.clone(), &party0_key.public_key) { 184 | Some(pub_key_agg1) => pub_key_agg1, 185 | None => panic!("Missing party public key in key aggregation!"), 186 | }; 187 | let party1_key_agg = match PublicKeyAgg::key_aggregation_n(pks, &party1_key.public_key) { 188 | Some(pub_key_agg2) => pub_key_agg2, 189 | None => panic!("Missing party public key in key aggregation!"), 190 | }; 191 | assert_eq!(party0_key_agg.agg_public_key, party1_key_agg.agg_public_key); 192 | // Compute partial signatures 193 | let s0 = musig2::partial_sign( 194 | &[p1_public_nonces.R.clone()], 195 | p0_private_nonces, 196 | p0_public_nonces.clone(), 197 | &party0_key_agg, 198 | &party0_key, 199 | &message, 200 | ); 201 | let s1 = musig2::partial_sign( 202 | &[p0_public_nonces.R], 203 | p1_private_nonces, 204 | p1_public_nonces, 205 | &party1_key_agg, 206 | &party1_key, 207 | &message, 208 | ); 209 | 210 | let signature0 = musig2::aggregate_partial_signatures(&s0, &[s1.my_partial_s.clone()]); 211 | let signature1 = musig2::aggregate_partial_signatures(&s1, &[s0.my_partial_s.clone()]); 212 | assert!(s0.R == s1.R, "Different partial nonce aggregation!"); 213 | assert!(signature0.s == signature1.s); 214 | // debugging asserts 215 | assert!(s0.my_partial_s + s1.my_partial_s == signature0.s, "TEST1"); 216 | // verify: 217 | assert!( 218 | signature0 219 | .verify(&message, &party0_key_agg.agg_public_key) 220 | .is_ok(), 221 | "Verification failed!" 222 | ); 223 | // Verify result against dalek 224 | assert!( 225 | verify_dalek(&party0_key_agg.agg_public_key, &signature0, &message), 226 | "Dalek signature verification failed!" 227 | ); 228 | } 229 | } 230 | -------------------------------------------------------------------------------- /src/protocols/thresholdsig/mod.rs: -------------------------------------------------------------------------------- 1 | #![allow(non_snake_case)] 2 | /* 3 | Multisig eddsa 4 | Copyright 2018 by Kzen Networks 5 | This file is part of multi-party-eddsa library 6 | (https://github.com/KZen-networks/multi-party-eddsa) 7 | Multisig Schnorr is free software: you can redistribute 8 | it and/or modify it under the terms of the GNU General Public 9 | License as published by the Free Software Foundation, either 10 | version 3 of the License, or (at your option) any later version. 11 | @license GPL-3.0+ 12 | */ 13 | use Error::{self, InvalidKey, InvalidSS}; 14 | 15 | use curv::arithmetic::traits::*; 16 | use curv::cryptographic_primitives::commitments::hash_commitment::HashCommitment; 17 | use curv::cryptographic_primitives::commitments::traits::Commitment; 18 | use curv::cryptographic_primitives::hashing::DigestExt; 19 | use curv::cryptographic_primitives::secret_sharing::feldman_vss::{SecretShares, VerifiableSS}; 20 | use curv::elliptic::curves::{Ed25519, Point, Scalar}; 21 | use curv::BigInt; 22 | use protocols::{ExpandedKeyPair, Signature}; 23 | use rand::{thread_rng, Rng}; 24 | use sha2::{digest::Digest, Sha512}; 25 | 26 | const SECURITY: usize = 256; 27 | 28 | // u_i is private key and {u__i, prefix} are extended private key. 29 | pub struct Keys { 30 | pub keypair: ExpandedKeyPair, 31 | pub party_index: u16, 32 | } 33 | 34 | pub struct KeyGenBroadcastMessage1 { 35 | com: BigInt, 36 | } 37 | 38 | #[derive(Debug)] 39 | pub struct Parameters { 40 | pub threshold: u16, //t 41 | pub share_count: u16, //n 42 | } 43 | #[derive(Clone, Serialize, Deserialize)] 44 | pub struct SharedKeys { 45 | pub y: Point, 46 | pub x_i: Scalar, 47 | prefix: Scalar, 48 | } 49 | 50 | pub struct EphemeralKey { 51 | pub r_i: Scalar, 52 | pub R_i: Point, 53 | pub party_index: u16, 54 | } 55 | 56 | #[derive(Clone, Serialize, Deserialize)] 57 | pub struct EphemeralSharedKeys { 58 | pub R: Point, 59 | pub r_i: Scalar, 60 | } 61 | 62 | pub struct LocalSig { 63 | gamma_i: Scalar, 64 | k: Scalar, 65 | } 66 | 67 | impl Keys { 68 | pub fn phase1_create(party_index: u16) -> Keys { 69 | Keys { 70 | keypair: ExpandedKeyPair::create(), 71 | party_index, 72 | } 73 | } 74 | 75 | pub fn phase1_create_from_private_key(party_index: u16, secret: [u8; 32]) -> Keys { 76 | Keys { 77 | keypair: ExpandedKeyPair::create_from_private_key(secret), 78 | party_index, 79 | } 80 | } 81 | 82 | pub fn phase1_broadcast(&self) -> (KeyGenBroadcastMessage1, BigInt) { 83 | self.phase1_broadcast_rng(&mut thread_rng()) 84 | } 85 | 86 | fn phase1_broadcast_rng(&self, rng: &mut impl Rng) -> (KeyGenBroadcastMessage1, BigInt) { 87 | let blind_factor: [u8; SECURITY / 8] = rng.gen(); 88 | let blind_factor = BigInt::from_bytes(&blind_factor); 89 | let com = HashCommitment::::create_commitment_with_user_defined_randomness( 90 | &self.keypair.public_key.y_coord().unwrap(), 91 | &blind_factor, 92 | ); 93 | let bcm1 = KeyGenBroadcastMessage1 { com }; 94 | (bcm1, blind_factor) 95 | } 96 | 97 | pub fn phase1_verify_com_phase2_distribute( 98 | &self, 99 | params: &Parameters, 100 | blind_vec: &[BigInt], 101 | y_vec: &[Point], 102 | bc1_vec: &[KeyGenBroadcastMessage1], 103 | parties: &[u16], 104 | ) -> Result<(VerifiableSS, SecretShares), Error> { 105 | // test length: 106 | assert_eq!(blind_vec.len(), usize::from(params.share_count)); 107 | assert_eq!(bc1_vec.len(), usize::from(params.share_count)); 108 | assert_eq!(y_vec.len(), usize::from(params.share_count)); 109 | // test decommitments 110 | let correct_key_correct_decom_all = y_vec 111 | .iter() 112 | .zip(blind_vec.iter()) 113 | .zip(bc1_vec.iter()) 114 | .all(|((y, blind), comm)| { 115 | HashCommitment::::create_commitment_with_user_defined_randomness( 116 | &y.y_coord().unwrap(), 117 | blind, 118 | ) == comm.com 119 | }); 120 | if !correct_key_correct_decom_all { 121 | return Err(InvalidKey); 122 | } 123 | Ok(VerifiableSS::share_at_indices( 124 | params.threshold, 125 | params.share_count, 126 | &self.keypair.expanded_private_key.private_key, 127 | parties, 128 | )) 129 | } 130 | 131 | pub fn phase2_verify_vss_construct_keypair( 132 | &self, 133 | params: &Parameters, 134 | y_vec: &[Point], 135 | secret_shares_vec: &[Scalar], 136 | vss_scheme_vec: &[VerifiableSS], 137 | index: u16, 138 | ) -> Result { 139 | assert_eq!(y_vec.len(), usize::from(params.share_count)); 140 | assert_eq!(secret_shares_vec.len(), usize::from(params.share_count)); 141 | assert_eq!(vss_scheme_vec.len(), usize::from(params.share_count)); 142 | 143 | let correct_ss_verify = vss_scheme_vec 144 | .iter() 145 | .zip(secret_shares_vec.iter()) 146 | .zip(y_vec.iter()) 147 | .all(|((vss_scheme, secret_share), y)| { 148 | vss_scheme.validate_share(secret_share, index).is_ok() 149 | && &vss_scheme.commitments[0] == y 150 | }); 151 | if !correct_ss_verify { 152 | return Err(InvalidSS); 153 | } 154 | let first_y = y_vec[0].clone(); 155 | let y = y_vec[1..].iter().fold(first_y, |acc, y| acc + y); 156 | let x_i = secret_shares_vec 157 | .iter() 158 | .fold(Scalar::zero(), |acc, x| acc + x); 159 | Ok(SharedKeys { 160 | y, 161 | x_i, 162 | prefix: self.keypair.expanded_private_key.prefix.clone(), 163 | }) 164 | } 165 | } 166 | 167 | impl EphemeralKey { 168 | // r = H(prefix||M): in order to do it for global r we need MPC. we skip it and deviate from the protocol 169 | // Nevertheless our ephemeral key will still be deterministic as a sum of deterministic ephemeral keys: 170 | 171 | pub fn ephermeral_key_create_from_deterministic_secret( 172 | keys: &Keys, 173 | message: &[u8], 174 | index: u16, 175 | ) -> EphemeralKey { 176 | Self::ephermeral_key_create_from_deterministic_secret_rng( 177 | keys, 178 | message, 179 | index, 180 | &mut thread_rng(), 181 | ) 182 | } 183 | 184 | fn ephermeral_key_create_from_deterministic_secret_rng( 185 | keys: &Keys, 186 | message: &[u8], 187 | index: u16, 188 | rng: &mut impl Rng, 189 | ) -> EphemeralKey { 190 | // here we deviate from the spec, by introducing non-deterministic element (random number) 191 | // to the nonce 192 | let r_i = Sha512::new() 193 | .chain_scalar(&keys.keypair.expanded_private_key.prefix) 194 | .chain(message) 195 | .chain(rng.gen::<[u8; 32]>()) 196 | .result_scalar(); 197 | let R_i = Point::generator() * &r_i; 198 | 199 | EphemeralKey { 200 | r_i, 201 | R_i, 202 | party_index: index, 203 | } 204 | } 205 | 206 | pub fn phase1_broadcast(&self) -> (KeyGenBroadcastMessage1, BigInt) { 207 | self.phase1_broadcast_rng(&mut thread_rng()) 208 | } 209 | 210 | pub fn phase1_broadcast_rng(&self, rng: &mut impl Rng) -> (KeyGenBroadcastMessage1, BigInt) { 211 | let blind_factor: [u8; SECURITY / 8] = rng.gen(); 212 | let blind_factor = BigInt::from_bytes(&blind_factor); 213 | let com = HashCommitment::::create_commitment_with_user_defined_randomness( 214 | &self.R_i.y_coord().unwrap(), 215 | &blind_factor, 216 | ); 217 | let bcm1 = KeyGenBroadcastMessage1 { com }; 218 | (bcm1, blind_factor) 219 | } 220 | 221 | pub fn phase1_verify_com_phase2_distribute( 222 | &self, 223 | params: &Parameters, 224 | blind_vec: &[BigInt], 225 | R_vec: &[Point], 226 | bc1_vec: &[KeyGenBroadcastMessage1], 227 | parties: &[u16], 228 | ) -> Result<(VerifiableSS, SecretShares), Error> { 229 | // test length: 230 | assert!( 231 | blind_vec.len() > usize::from(params.threshold) 232 | && blind_vec.len() <= usize::from(params.share_count) 233 | ); 234 | assert!( 235 | bc1_vec.len() > usize::from(params.threshold) 236 | && bc1_vec.len() <= usize::from(params.share_count) 237 | ); 238 | assert!( 239 | R_vec.len() > usize::from(params.threshold) 240 | && R_vec.len() <= usize::from(params.share_count) 241 | ); 242 | // test decommitments 243 | let correct_key_correct_decom_all = R_vec 244 | .iter() 245 | .zip(blind_vec.iter()) 246 | .zip(bc1_vec.iter()) 247 | .all(|((R, blind), comm)| { 248 | HashCommitment::::create_commitment_with_user_defined_randomness( 249 | &R.y_coord().unwrap(), 250 | blind, 251 | ) == comm.com 252 | }); 253 | 254 | if !correct_key_correct_decom_all { 255 | return Err(InvalidKey); 256 | } 257 | 258 | Ok(VerifiableSS::share_at_indices( 259 | params.threshold, 260 | params.share_count, 261 | &self.r_i, 262 | parties, 263 | )) 264 | } 265 | 266 | pub fn phase2_verify_vss_construct_keypair( 267 | &self, 268 | params: &Parameters, 269 | R_vec: &[Point], 270 | secret_shares_vec: &[Scalar], 271 | vss_scheme_vec: &[VerifiableSS], 272 | index: u16, 273 | ) -> Result { 274 | assert!( 275 | R_vec.len() > usize::from(params.threshold) 276 | && R_vec.len() <= usize::from(params.share_count) 277 | ); 278 | assert!( 279 | secret_shares_vec.len() > usize::from(params.threshold) 280 | && secret_shares_vec.len() <= usize::from(params.share_count) 281 | ); 282 | assert!( 283 | vss_scheme_vec.len() > usize::from(params.threshold) 284 | && vss_scheme_vec.len() <= usize::from(params.share_count) 285 | ); 286 | 287 | let correct_ss_verify = vss_scheme_vec 288 | .iter() 289 | .zip(secret_shares_vec.iter()) 290 | .zip(R_vec.iter()) 291 | .all(|((vss_scheme, secret_share), R)| { 292 | vss_scheme.validate_share(secret_share, index).is_ok() 293 | && &vss_scheme.commitments[0] == R 294 | }); 295 | if !correct_ss_verify { 296 | return Err(InvalidSS); 297 | } 298 | 299 | let R_first = R_vec[0].clone(); 300 | let R = R_vec[1..].iter().fold(R_first, |acc, x| acc + x); 301 | let r_i = secret_shares_vec 302 | .iter() 303 | .fold(Scalar::zero(), |acc, x| acc + x); 304 | Ok(EphemeralSharedKeys { R, r_i }) 305 | } 306 | } 307 | 308 | impl LocalSig { 309 | pub fn compute( 310 | message: &[u8], 311 | local_ephemaral_key: &EphemeralSharedKeys, 312 | local_private_key: &SharedKeys, 313 | ) -> LocalSig { 314 | let r_i = local_ephemaral_key.r_i.clone(); 315 | let s_i = local_private_key.x_i.clone(); 316 | 317 | let k = Signature::k(&local_ephemaral_key.R, &local_private_key.y, message); 318 | let gamma_i = r_i + &k * s_i; 319 | 320 | LocalSig { gamma_i, k } 321 | } 322 | 323 | // section 4.2 step 3 324 | #[allow(unused_doc_comments)] 325 | pub fn verify_local_sigs( 326 | gamma_vec: &[LocalSig], 327 | parties_index_vec: &[u16], 328 | vss_private_keys: &[VerifiableSS], 329 | vss_ephemeral_keys: &[VerifiableSS], 330 | ) -> Result, Error> { 331 | //parties_index_vec is a vector with indices of the parties that are participating and provided gamma_i for this step 332 | // test that enough parties are in this round 333 | assert!(parties_index_vec.len() > usize::from(vss_private_keys[0].parameters.threshold)); 334 | 335 | // Vec of joint commitments: 336 | // n' = num of signers, n - num of parties in keygen 337 | // [com0_eph_0,... ,com0_eph_n', e*com0_kg_0, ..., e*com0_kg_n ; 338 | // ... ; 339 | // comt_eph_0,... ,comt_eph_n', e*comt_kg_0, ..., e*comt_kg_n ] 340 | let comm_vec: Vec<_> = (0..usize::from(vss_private_keys[0].parameters.threshold) + 1) 341 | .map(|i| { 342 | let mut key_gen_comm_i_vec: Vec<_> = (0..vss_private_keys.len()) 343 | .map(|j| &vss_private_keys[j].commitments[i] * &gamma_vec[i].k) 344 | .collect(); 345 | let mut eph_comm_i_vec: Vec<_> = (0..vss_ephemeral_keys.len()) 346 | .map(|j| vss_ephemeral_keys[j].commitments[i].clone()) 347 | .collect(); 348 | key_gen_comm_i_vec.append(&mut eph_comm_i_vec); 349 | let first = key_gen_comm_i_vec[0].clone(); 350 | key_gen_comm_i_vec[1..].iter().fold(first, |acc, x| acc + x) 351 | }) 352 | .collect(); 353 | 354 | let vss_sum = VerifiableSS { 355 | parameters: vss_ephemeral_keys[0].parameters.clone(), 356 | commitments: comm_vec, 357 | }; 358 | 359 | let g = Point::generator(); 360 | 361 | let correct_ss_verify = 362 | gamma_vec 363 | .iter() 364 | .zip(parties_index_vec.iter()) 365 | .all(|(gamma, &party_index)| { 366 | let gamma_i_g = &gamma.gamma_i * g; 367 | vss_sum 368 | .validate_share_public(&gamma_i_g, party_index + 1) 369 | .is_ok() 370 | }); 371 | 372 | match correct_ss_verify { 373 | true => Ok(vss_sum), 374 | false => Err(InvalidSS), 375 | } 376 | } 377 | } 378 | 379 | pub fn generate( 380 | vss_sum_local_sigs: &VerifiableSS, 381 | local_sig_vec: &[LocalSig], 382 | parties_index_vec: &[u16], 383 | R: Point, 384 | ) -> Signature { 385 | let reconstruct_limit = usize::from(vss_sum_local_sigs.parameters.threshold) + 1; 386 | let gamma_vec: Vec<_> = local_sig_vec[..reconstruct_limit] 387 | .iter() 388 | .map(|sig| sig.gamma_i.clone()) 389 | .collect(); 390 | let s = vss_sum_local_sigs.reconstruct(&parties_index_vec[0..reconstruct_limit], &gamma_vec); 391 | Signature { s, R } 392 | } 393 | 394 | mod test; 395 | -------------------------------------------------------------------------------- /src/protocols/thresholdsig/test.rs: -------------------------------------------------------------------------------- 1 | #![allow(non_snake_case)] 2 | /* 3 | Multisig eddsa 4 | Copyright 2018 by Kzen Networks 5 | This file is part of multi-party-eddsa library 6 | (https://github.com/KZen-networks/multi-party-eddsa) 7 | Multisig Schnorr is free software: you can redistribute 8 | it and/or modify it under the terms of the GNU General Public 9 | License as published by the Free Software Foundation, either 10 | version 3 of the License, or (at your option) any later version. 11 | @license GPL-3.0+ 12 | */ 13 | #[cfg(test)] 14 | mod tests { 15 | use curv::cryptographic_primitives::secret_sharing::feldman_vss::VerifiableSS; 16 | use curv::elliptic::curves::{Ed25519, Point}; 17 | use itertools::{izip, Itertools}; 18 | use protocols::tests::{deterministic_fast_rand, verify_dalek}; 19 | use protocols::thresholdsig::{ 20 | self, EphemeralKey, EphemeralSharedKeys, Keys, LocalSig, Parameters, SharedKeys, 21 | }; 22 | use rand::{Rng, RngCore}; 23 | 24 | #[test] 25 | fn test_sign_threshold_verify_dalek_n1() { 26 | test_sign_threshold_verify_dalek_for_all_t(1); 27 | } 28 | #[test] 29 | fn test_sign_threshold_verify_dalek_n2() { 30 | test_sign_threshold_verify_dalek_for_all_t(2); 31 | } 32 | #[test] 33 | fn test_sign_threshold_verify_dalek_n3() { 34 | test_sign_threshold_verify_dalek_for_all_t(3); 35 | } 36 | #[test] 37 | fn test_sign_threshold_verify_dalek_n4() { 38 | test_sign_threshold_verify_dalek_for_all_t(4); 39 | } 40 | #[test] 41 | fn test_sign_threshold_verify_dalek_n5() { 42 | test_sign_threshold_verify_dalek_for_all_t(5); 43 | } 44 | 45 | #[test] 46 | // Only run n=6 on release 47 | #[cfg(not(debug_assertions))] 48 | fn test_sign_threshold_verify_dalek_n6() { 49 | test_sign_threshold_verify_dalek_for_all_t(6); 50 | } 51 | 52 | fn test_sign_threshold_verify_dalek_for_all_t(n: u16) { 53 | let mut rng = deterministic_fast_rand( 54 | &format!("test_sign_threshold_verify_dalek_for_all_t_{}", n), 55 | None, 56 | ); 57 | 58 | // max message size, will try from empty message until full. 59 | let mut msg = [0u8; 33]; 60 | 61 | let indicies: Vec<_> = (1..=n).collect(); 62 | // test all t from 0 to n 63 | for t in 0..n { 64 | // KeyGen 65 | let (keypairs, combined_shares, agg_pubkey, vss_schemes) = 66 | keygen_t_n_parties(t, n, &indicies, &mut rng); 67 | 68 | // Sign for all possible groups (combinatorially) 69 | for group in (1u16..=n).combinations(usize::from(t + 1)) { 70 | let group_indexs: Vec<_> = group.iter().map(|a| a - 1).collect(); 71 | 72 | // Try to sign for all possible message lengths from 0 to msg.len() 73 | for msg_len in 0..msg.len() { 74 | let msg = &mut msg[..msg_len]; 75 | rng.fill_bytes(msg); 76 | // Generate Rs 77 | let (combined_nonce_shares, agg_nonce, nonce_vss_schemes) = 78 | eph_keygen_t_n_parties(t, t + 1, &group, &keypairs, msg, &mut rng); 79 | 80 | let partial_sigs: Vec<_> = combined_nonce_shares 81 | .iter() 82 | .zip_eq(group_indexs.iter()) 83 | .map(|(nonce_share, &index)| { 84 | LocalSig::compute( 85 | msg, 86 | nonce_share, 87 | &combined_shares[usize::from(index)], 88 | ) 89 | }) 90 | .collect(); 91 | 92 | // Verify all partial signatures 93 | let vss_sum_sigs = LocalSig::verify_local_sigs( 94 | &partial_sigs, 95 | &group_indexs, 96 | &vss_schemes, 97 | &nonce_vss_schemes, 98 | ) 99 | .unwrap(); 100 | let sig = thresholdsig::generate( 101 | &vss_sum_sigs, 102 | &partial_sigs, 103 | &group_indexs, 104 | agg_nonce, 105 | ); 106 | assert!(verify_dalek(&agg_pubkey, &sig, msg)); 107 | } 108 | } 109 | } 110 | } 111 | 112 | #[test] 113 | fn test_t2_n4() { 114 | let mut rng = deterministic_fast_rand("test_t2_n4", None); 115 | for _i in 0..128 { 116 | test_t2_n4_internal(&mut rng); 117 | } 118 | } 119 | 120 | fn test_t2_n4_internal(rng: &mut impl Rng) { 121 | // this test assumes that in keygen we have n=4 parties and in signing we have 4 parties as well. 122 | let t = 2u16; 123 | let n = 4u16; 124 | let key_gen_parties_index_vec: [u16; 4] = [0, 1, 2, 3]; 125 | let key_gen_parties_points_vec: Vec<_> = 126 | key_gen_parties_index_vec.iter().map(|i| i + 1).collect(); 127 | 128 | let (priv_keys_vec, priv_shared_keys_vec, Y, key_gen_vss_vec) = 129 | keygen_t_n_parties(t, n, &key_gen_parties_points_vec, rng); 130 | let parties_index_vec: [u16; 4] = [0, 1, 2, 3]; 131 | let parties_points_vec: Vec<_> = parties_index_vec.iter().map(|i| i + 1).collect(); 132 | 133 | let message: [u8; 4] = [79, 77, 69, 82]; 134 | let (eph_shared_keys_vec, R, eph_vss_vec) = 135 | eph_keygen_t_n_parties(t, n, &parties_points_vec, &priv_keys_vec, &message, rng); 136 | let local_sig_vec = (0..usize::from(n)) 137 | .map(|i| LocalSig::compute(&message, &eph_shared_keys_vec[i], &priv_shared_keys_vec[i])) 138 | .collect::>(); 139 | let verify_local_sig = LocalSig::verify_local_sigs( 140 | &local_sig_vec, 141 | &parties_index_vec, 142 | &key_gen_vss_vec, 143 | &eph_vss_vec, 144 | ); 145 | 146 | assert!(verify_local_sig.is_ok()); 147 | let vss_sum_local_sigs = verify_local_sig.unwrap(); 148 | let signature = 149 | thresholdsig::generate(&vss_sum_local_sigs, &local_sig_vec, &parties_index_vec, R); 150 | let verify_sig = signature.verify(&message, &Y); 151 | assert!(verify_sig.is_ok()); 152 | } 153 | 154 | #[test] 155 | fn test_t2_n5_sign_with_4() { 156 | let mut rng = deterministic_fast_rand("test_t2_n5_sign_with_4", None); 157 | for _i in 0..128 { 158 | test_t2_n5_sign_with_4_internal(&mut rng); 159 | } 160 | } 161 | 162 | #[allow(unused_doc_comments)] 163 | fn test_t2_n5_sign_with_4_internal(rng: &mut impl Rng) { 164 | /// this test assumes that in keygen we have n=4 parties and in signing we have 4 parties, indices 0,1,3,4. 165 | let t = 2; 166 | let n = 5; 167 | /// keygen: 168 | let key_gen_parties_index_vec: [u16; 5] = [0, 1, 2, 3, 4]; 169 | let key_gen_parties_points_vec: Vec<_> = 170 | key_gen_parties_index_vec.iter().map(|i| i + 1).collect(); 171 | let (priv_keys_vec, priv_shared_keys_vec, Y, key_gen_vss_vec) = 172 | keygen_t_n_parties(t, n, &key_gen_parties_points_vec, rng); 173 | /// signing: 174 | let parties_index_vec: [u16; 4] = [0, 1, 3, 4]; 175 | let parties_points_vec: Vec<_> = parties_index_vec.iter().map(|i| i + 1).collect(); 176 | let num_parties = parties_index_vec.len() as u16; 177 | let message: [u8; 4] = [79, 77, 69, 82]; 178 | 179 | let (eph_shared_keys_vec, R, eph_vss_vec) = eph_keygen_t_n_parties( 180 | t, 181 | num_parties, 182 | &parties_points_vec, 183 | &priv_keys_vec, 184 | &message, 185 | rng, 186 | ); 187 | 188 | // each party computes and share a local sig, we collected them here to a vector as each party should do AFTER receiving all local sigs 189 | let local_sig_vec = (0..usize::from(num_parties)) 190 | .map(|i| { 191 | LocalSig::compute( 192 | &message, 193 | &eph_shared_keys_vec[i], 194 | &priv_shared_keys_vec[usize::from(parties_index_vec[i])], 195 | ) 196 | }) 197 | .collect::>(); 198 | 199 | let verify_local_sig = LocalSig::verify_local_sigs( 200 | &local_sig_vec, 201 | &parties_index_vec, 202 | &key_gen_vss_vec, 203 | &eph_vss_vec, 204 | ); 205 | 206 | assert!(verify_local_sig.is_ok()); 207 | let vss_sum_local_sigs = verify_local_sig.unwrap(); 208 | 209 | /// each party / dealer can generate the signature 210 | let signature = 211 | thresholdsig::generate(&vss_sum_local_sigs, &local_sig_vec, &parties_index_vec, R); 212 | let verify_sig = signature.verify(&message, &Y); 213 | assert!(verify_sig.is_ok()); 214 | } 215 | 216 | pub fn keygen_t_n_parties( 217 | t: u16, 218 | n: u16, 219 | parties: &[u16], 220 | rng: &mut impl Rng, 221 | ) -> ( 222 | Vec, 223 | Vec, 224 | Point, 225 | Vec>, 226 | ) { 227 | let params = Parameters { 228 | threshold: t, 229 | share_count: n, 230 | }; 231 | assert_eq!(parties.len(), usize::from(n)); 232 | let keypairs: Vec<_> = parties.iter().copied().map(Keys::phase1_create).collect(); 233 | 234 | let (first_msgs, first_msg_blinds): (Vec<_>, Vec<_>) = keypairs 235 | .iter() 236 | .map(|keypair| Keys::phase1_broadcast_rng(keypair, rng)) 237 | .unzip(); 238 | 239 | let pubkeys_list: Vec<_> = keypairs 240 | .iter() 241 | .map(|k| k.keypair.public_key.clone()) 242 | .collect(); 243 | 244 | // Generate the aggregate key 245 | let agg_pubkey = { 246 | let first_key = pubkeys_list[0].clone(); 247 | pubkeys_list[1..].iter().fold(first_key, |acc, p| acc + p) 248 | }; 249 | let (vss_schemes, secret_shares): (Vec<_>, Vec<_>) = keypairs 250 | .iter() 251 | .map(|keypair| { 252 | keypair 253 | .phase1_verify_com_phase2_distribute( 254 | ¶ms, 255 | &first_msg_blinds, 256 | &pubkeys_list, 257 | &first_msgs, 258 | parties, 259 | ) 260 | .unwrap() 261 | }) 262 | .unzip(); 263 | 264 | let parties_shares: Vec> = (0..usize::from(n)) 265 | .map(|i| { 266 | (0..usize::from(n)) 267 | .map(|j| secret_shares[j][i].clone()) 268 | .collect() 269 | }) 270 | .collect(); 271 | 272 | let combined_shares: Vec<_> = izip!(keypairs.iter(), parties_shares.iter(), parties.iter()) 273 | .map(|(keypair, secret_shares, &index)| { 274 | keypair 275 | .phase2_verify_vss_construct_keypair( 276 | ¶ms, 277 | &pubkeys_list, 278 | secret_shares, 279 | &vss_schemes, 280 | index, 281 | ) 282 | .unwrap() 283 | }) 284 | .collect(); 285 | 286 | (keypairs, combined_shares, agg_pubkey, vss_schemes) 287 | } 288 | 289 | pub fn eph_keygen_t_n_parties( 290 | t: u16, // system threshold 291 | n: u16, // number of signers 292 | parties: &[u16], 293 | keypairs: &[Keys], 294 | message: &[u8], 295 | rng: &mut impl Rng, 296 | ) -> ( 297 | Vec, 298 | Point, 299 | Vec>, 300 | ) { 301 | assert!(parties.len() > usize::from(t) && parties.len() <= usize::from(n)); 302 | let params = Parameters { 303 | threshold: t, 304 | share_count: n, 305 | }; 306 | // Generate Rs 307 | let (Rs, nonce_keys): (Vec<_>, Vec<_>) = parties 308 | .iter() 309 | .map(|&index| { 310 | let ephemeral_key = 311 | EphemeralKey::ephermeral_key_create_from_deterministic_secret_rng( 312 | &keypairs[usize::from(index - 1)], 313 | message, 314 | index, 315 | rng, 316 | ); 317 | (ephemeral_key.R_i.clone(), ephemeral_key) 318 | }) 319 | .unzip(); 320 | 321 | // Generate first messages 322 | let (first_msgs, first_msg_blinds): (Vec<_>, Vec<_>) = nonce_keys 323 | .iter() 324 | .map(|nonce| EphemeralKey::phase1_broadcast_rng(nonce, rng)) 325 | .unzip(); 326 | 327 | // Generate the aggregate nonce point 328 | let agg_nonce = { 329 | let first_key = Rs[0].clone(); 330 | Rs[1..].iter().fold(first_key, |acc, p| acc + p) 331 | }; 332 | // Verify the first messages and generate the vss and secret shares 333 | let (nonce_vss_schemes, nonce_secret_shares): (Vec<_>, Vec<_>) = nonce_keys 334 | .iter() 335 | .map(|nonce| { 336 | nonce 337 | .phase1_verify_com_phase2_distribute( 338 | ¶ms, 339 | &first_msg_blinds, 340 | &Rs, 341 | &first_msgs, 342 | parties, 343 | ) 344 | .unwrap() 345 | }) 346 | .unzip(); 347 | 348 | let nonce_parties_shares: Vec> = (0..usize::from(n)) 349 | .map(|i| { 350 | (0..usize::from(n)) 351 | .map(|j| nonce_secret_shares[j][i].clone()) 352 | .collect() 353 | }) 354 | .collect(); 355 | 356 | let combined_nonce_shares: Vec<_> = izip!( 357 | nonce_keys.iter(), 358 | nonce_parties_shares.iter(), 359 | parties.iter() 360 | ) 361 | .map(|(nonce, nonce_secret_share, &index)| { 362 | nonce 363 | .phase2_verify_vss_construct_keypair( 364 | ¶ms, 365 | &Rs, 366 | nonce_secret_share, 367 | &nonce_vss_schemes, 368 | index, 369 | ) 370 | .unwrap() 371 | }) 372 | .collect(); 373 | 374 | (combined_nonce_shares, agg_nonce, nonce_vss_schemes) 375 | } 376 | } 377 | --------------------------------------------------------------------------------