├── .gitattributes ├── .gitignore ├── .npmignore ├── .prettierignore ├── .prettierrc ├── .solhint.json ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── buidler.config.ts ├── compiler.json ├── contracts ├── Verifier.sol └── VerifierTesting.sol ├── package-lock.json ├── package.json ├── proof_0x.json ├── test └── vdf_test.ts ├── tsconfig.json ├── tslint.json ├── verifier.py └── yarn.lock /.gitattributes: -------------------------------------------------------------------------------- 1 | *.sol linguist-language=Solidity 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # IDEs 2 | .vscode 3 | .DS_Store 4 | *.trace 5 | *.code-workspace 6 | 7 | # Vim swap files 8 | *.swp 9 | 10 | #Buidler files 11 | cache 12 | artifacts 13 | typechain 14 | node_modules 15 | 16 | # Remove Cargo.lock from gitignore if creating an libbraries, leave it for executable 17 | # More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html 18 | Cargo.lock -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | # Blacklist all files 2 | .* 3 | * 4 | # Whitelist lib 5 | !lib/**/* 6 | # Whitelist Solidity contracts 7 | !contracts/src/**/* 8 | # Blacklist tests in lib 9 | /lib/test/* 10 | # Package specific ignore 11 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | lib 2 | .nyc_output 3 | generated_artifacts 4 | generated_wrappers 5 | package.json 6 | *.sol 7 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 80, 3 | "tabWidth": 4, 4 | "singleQuote": true, 5 | "trailingComma": "all" 6 | } 7 | -------------------------------------------------------------------------------- /.solhint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "default", 3 | "rules": { 4 | "avoid-low-level-calls": false, 5 | "avoid-tx-origin": "warn", 6 | "bracket-align": false, 7 | "code-complexity": false, 8 | "compiler-fixed": false, 9 | "const-name-snakecase": "error", 10 | "expression-indent": "error", 11 | "function-max-lines": false, 12 | "func-order": "error", 13 | "indent": ["error", 4], 14 | "max-line-length": ["warn", 160], 15 | "no-inline-assembly": false, 16 | "quotes": ["error", "double"], 17 | "separate-by-one-line-in-contract": "error", 18 | "space-after-comma": "error", 19 | "statement-indent": "error" 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | - Using welcoming and inclusive language 12 | - Being respectful of differing viewpoints and experiences 13 | - Gracefully accepting constructive criticism 14 | - Focusing on what is best for the community 15 | - Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | - The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | - Trolling, insulting/derogatory comments, and personal or political attacks 21 | - Public or private harassment 22 | - Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | - Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at team@0xproject.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # VDF 2 | A Solidity implementation of a VDF verifier contract, please note the code has not been audited and the preformance may not be completly optimized. 3 | The verrify proof function checks that given: an input random, y, pi, number of iterations and a potential prime, that (1) the hash of the input random and y matches on all digits of the potential prime except the bottom twelve bits and the top bit and that the potential prime passes a random base miller rabin test and (2) it checks that pi is a valid VDF proof over the inputs. 4 | -------------------------------------------------------------------------------- /buidler.config.ts: -------------------------------------------------------------------------------- 1 | import {BuidlerConfig, usePlugin} from '@nomiclabs/buidler/config'; 2 | 3 | usePlugin('@nomiclabs/buidler-waffle'); 4 | usePlugin('buidler-typechain'); 5 | 6 | const config: BuidlerConfig = { 7 | solc: { 8 | version: '0.6.4', 9 | }, 10 | typechain: { 11 | outDir: 'typechain', 12 | target: 'ethers', 13 | }, 14 | }; 15 | 16 | // tslint:disable-next-line:no-default-export 17 | export default config; 18 | -------------------------------------------------------------------------------- /compiler.json: -------------------------------------------------------------------------------- 1 | { 2 | "artifactsDir": "./generated-artifacts", 3 | "contractsDir": "./contracts", 4 | "useDockerisedSolc": false, 5 | "isOfflineMode": false, 6 | "shouldSaveStandardInput": true, 7 | "compilerSettings": { 8 | "evmVersion": "istanbul", 9 | "optimizer": { 10 | "enabled": true, 11 | "runs": 1000000, 12 | "details": { 13 | "yul": true, 14 | "deduplicate": true, 15 | "cse": true, 16 | "constantOptimizer": true 17 | } 18 | }, 19 | "outputSelection": { 20 | "*": { 21 | "*": [ 22 | "abi", 23 | "devdoc", 24 | "evm.bytecode.object", 25 | "evm.bytecode.sourceMap", 26 | "evm.deployedBytecode.object", 27 | "evm.deployedBytecode.sourceMap" 28 | ] 29 | } 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /contracts/Verifier.sol: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2020 ZeroEx Intl. 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | */ 18 | 19 | pragma solidity ^0.6.4; 20 | 21 | contract Verifier { 22 | // Preset 2048 bit mod 23 | bytes constant MODULUS = hex"C7970CEEDCC3B0754490201A7AA613CD73911081C790F5F1A8726F463550BB5B7FF0DB8E1EA1189EC72F93D1650011BD721AEEACC2ACDE32A04107F0648C2813A31F5B0B7765FF8B44B4B6FFC93384B646EB09C7CF5E8592D40EA33C80039F35B4F14A04B51F7BFD781BE4D1673164BA8EB991C2C4D730BBBE35F592BDEF524AF7E8DAEFD26C66FC02C479AF89D64D373F442709439DE66CEB955F3EA37D5159F6135809F85334B5CB1813ADDC80CD05609F10AC6A95AD65872C909525BDAD32BC729592642920F24C61DC5B3C3B7923E56B16A4D9D373D8721F24A3FC0F1B3131F55615172866BCCC30F95054C824E733A5EB6817F7BC16399D48C6361CC7E5"; 24 | bytes constant HALF_MOD = hex"63CB86776E61D83AA248100D3D5309E6B9C88840E3C87AF8D43937A31AA85DADBFF86DC70F508C4F6397C9E8B28008DEB90D775661566F19502083F832461409D18FAD85BBB2FFC5A25A5B7FE499C25B237584E3E7AF42C96A07519E4001CF9ADA78A5025A8FBDFEBC0DF268B398B25D475CC8E1626B985DDF1AFAC95EF7A9257BF46D77E936337E01623CD7C4EB269B9FA21384A1CEF33675CAAF9F51BEA8ACFB09AC04FC299A5AE58C09D6EE406682B04F8856354AD6B2C396484A92DED6995E394AC9321490792630EE2D9E1DBC91F2B58B526CE9B9EC390F9251FE078D9898FAAB0A8B94335E66187CA82A64127399D2F5B40BFBDE0B1CCEA4631B0E63F2"; 25 | 26 | // Version of VDF verification which uses more calldata 27 | function verify_vdf_proof(bytes32 input_random, bytes memory y, bytes memory pi, uint256 iterations, uint256 prime) public view { 28 | // Check that y is a group member 29 | require(group_member(y), "Y improperly formatted"); 30 | require(group_member(pi), "Pi improperly formatted"); 31 | check_hash_to_prime(input_random, y, prime); 32 | 33 | // No need to cast this into the group because the size will always be small. 34 | uint256 r = expmod(2, iterations, prime); 35 | 36 | bytes memory part_1 = bignum_expmod(pi, prime, MODULUS); 37 | part_1 = trim(part_1); 38 | bytes memory part_2 = bignum_expmod(bytes_to_big_num(input_random), r, MODULUS); 39 | part_2 = trim(part_2); 40 | // Gives us four times what we want 41 | bytes memory proposed_y = almost_mulmod(part_1, part_2, MODULUS); 42 | proposed_y = trim(proposed_y); 43 | // So we compare to four times the y 44 | bytes memory almost_y = almost_mulmod(y, hex"01", MODULUS); 45 | almost_y = trim(almost_y); 46 | 47 | require(big_eq(proposed_y, almost_y), "VDF proof verification failed"); 48 | } 49 | 50 | // This function hard casts a number which must be less than MODULUS into a RSA group member 51 | function group_cast(bytes memory candidate) internal view { 52 | if (!group_member(candidate)) { 53 | candidate = big_sub(candidate, HALF_MOD); 54 | } 55 | } 56 | 57 | // Returns true if the group member is less than half the RSA group mod 58 | // NOTE - Will trim leading zeros from the candidate 59 | function group_member(bytes memory candidate) internal pure returns(bool) { 60 | candidate = trim(candidate); 61 | return lte(candidate, HALF_MOD); 62 | } 63 | 64 | // This trim function removes leading zeros don't contain information in our big endian format. 65 | function trim(bytes memory data) internal pure returns(bytes memory) { 66 | uint256 msb = 0; 67 | while (data[msb] == 0) { 68 | msb ++; 69 | if (msb == data.length) { 70 | return hex""; 71 | } 72 | } 73 | 74 | if (msb > 0) { 75 | // We don't want to copy data around, so we do the following assembly manipulation: 76 | // Move the data pointer forward by msb, then store in the length slot (current length - msb) 77 | assembly { 78 | let current_len := mload(data) 79 | data := add(data, msb) 80 | mstore(data, sub(current_len, msb)) 81 | } 82 | } 83 | return data; 84 | } 85 | 86 | // Casts a bytes32 value into bytes memory string 87 | function bytes_to_big_num(bytes32 data) internal pure returns(bytes memory ptr) { 88 | 89 | assembly { 90 | ptr := mload(0x40) 91 | mstore(ptr, 0x20) 92 | mstore(add(ptr, 0x20), data) 93 | // Pesimestic update to free memory pointer 94 | mstore(0x40, add(mload(0x40), 0x40)) 95 | } 96 | 97 | // Removes any zeros which aren't needed 98 | ptr = trim(ptr); 99 | } 100 | 101 | // This function returns (4ab) % mod for big numbs 102 | function almost_mulmod(bytes memory a, bytes memory b, bytes memory mod) internal view returns(bytes memory c) { 103 | bytes memory part1 = bignum_expmod(modular_add(a, b), 2, mod); 104 | bytes memory part2 = bignum_expmod(modular_sub(a, b), 2, mod); 105 | // Returns (a+b)^2 - (a-b)^2 = 4ab 106 | return modular_sub(part1, part2); 107 | } 108 | 109 | // Uses the mod const in the contract and assumes that a < Mod, b < Mod 110 | // Ie that the inputs are already modular group memembers. 111 | function modular_add(bytes memory a, bytes memory b) internal view returns (bytes memory) { 112 | bytes memory result = big_add(a, b); 113 | if (lte(result, MODULUS) && !big_eq(result, MODULUS)) { 114 | return result; 115 | } else { 116 | // NOTE a + b where a < MOD, b < MOD => a+b < 2 MOD => a+b % mod = a+b - MOD 117 | return big_sub(result, MODULUS); 118 | } 119 | } 120 | 121 | function modular_sub(bytes memory a, bytes memory b) internal view returns(bytes memory) { 122 | if (lte(b, a)) { 123 | return big_sub(a, b); 124 | } else { 125 | return (big_sub(MODULUS, big_sub(b, a))); 126 | } 127 | } 128 | 129 | // Returns (a <= b); 130 | // Requires trimmed inputs 131 | function lte(bytes memory a, bytes memory b) internal pure returns (bool) { 132 | if (a.length < b.length) { 133 | return true; 134 | } 135 | if (a.length > b.length) { 136 | return false; 137 | } 138 | 139 | for (uint i = 0; i < a.length; i++) { 140 | // If the current byte of a is less than that of b then a is less than b 141 | if (a[i] < b[i]) { 142 | return true; 143 | } 144 | // If it's strictly more then b is greater 145 | if (a[i] > b[i]) { 146 | return false; 147 | } 148 | } 149 | // We hit this condition if a == b 150 | return true; 151 | } 152 | 153 | uint mask = 0x00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; 154 | // This big add function has performance on the order of the limb version, but 155 | // it worse because it chunks out limbs for as long as it can from the bytes and 156 | // when there isn't enough data for a 31 bit limb in either a or b it goes byte by byte 157 | // Preformance degrades to byte by byte when adding a full 2048 bit number to a small number. 158 | // It is best when adding two full sized 2048 bit numbers 159 | function big_add(bytes memory a, bytes memory b) internal view returns(bytes memory) { 160 | // a + b < 2*max(a, b) so this can't have more bytes than the max length + 1 161 | bytes memory c = new bytes(max(a.length, b.length) + 1); 162 | // The index from the back of the data arrays [since this is Big endian] 163 | uint current_index = 0; 164 | uint8 carry = 0; 165 | // This loop grabs large numbers from the byte array for as long as we can 166 | while (a.length - current_index > 31 && b.length - current_index > 31) { 167 | // Will have 31 bytes of a's next digits 168 | uint a_data; 169 | // Will have 31 bytes of b's next digits 170 | uint b_data; 171 | assembly { 172 | //Load from memory at the data location of a + a.length - (current_index - 32) 173 | // This can load a bit of extra data which will be masked off. 174 | a_data := mload(add(add(a, 0x20), sub(mload(a), add(current_index, 32)))) 175 | //Load from memory at the data location of b + b.length - (current_index - 32) 176 | b_data := mload(add(add(b, 0x20), sub(mload(b), add(current_index, 32)))) 177 | } 178 | a_data = a_data & mask; 179 | b_data = b_data & mask; 180 | // Add the input data and the carried data. 181 | // TODO - Limb overflow checks the implementation may break on a+b > 2^31*8 with carry != 0 182 | uint sum = a_data + b_data + carry; 183 | // Coerce solidity into giving me the first byte as a small number; 184 | carry = uint8(bytes1(bytes32(sum))); 185 | // Slice off the carry 186 | sum = sum & mask; 187 | // Store the sum-ed digits 188 | assembly { 189 | mstore(add(add(c, 0x20), sub(mload(c), add(current_index, 32))), sum) 190 | } 191 | current_index += 31; 192 | } 193 | 194 | // Now we go byte by byte 195 | while (current_index < max(a.length, b.length)) { 196 | uint16 a_data; 197 | if (current_index < a.length) { 198 | a_data = uint16(uint8(a[a.length - current_index-1])); 199 | } else { 200 | a_data = 0; 201 | } 202 | 203 | uint16 b_data; 204 | if (current_index < b.length) { 205 | b_data = uint16(uint8(b[b.length - current_index-1])); 206 | } else { 207 | b_data = 0; 208 | } 209 | 210 | uint16 sum = a_data + b_data + carry; 211 | c[c.length - current_index-1] = bytes1(uint8(sum)); 212 | carry = uint8(sum >> 8); 213 | current_index++; 214 | } 215 | c[0] = bytes1(carry); 216 | c = trim(c); 217 | return c; 218 | } 219 | 220 | function max(uint a, uint b) internal pure returns (uint) { 221 | return a > b ? a : b; 222 | } 223 | 224 | // This extra digit allows us to preform the subtraction without underflow 225 | uint max_set_digit = 0x0100000000000000000000000000000000000000000000000000000000000000; 226 | 227 | // This function reverts on underflows, and expects trimed data 228 | function big_sub(bytes memory a, bytes memory b) internal view returns(bytes memory) { 229 | require(a.length >= b.length, "Subtraction underflow"); 230 | // a - b =< a so this can't have more bytes than a 231 | bytes memory c = new bytes(a.length); 232 | // The index from the back of the data arrays [since this is Big endian] 233 | uint current_index = 0; 234 | uint8 carry = 0; 235 | // This loop grabs large numbers from the byte array for as long as we can 236 | while (a.length - current_index > 31 && b.length - current_index > 31) { 237 | // Will have 31 bytes of a's next digits 238 | uint a_data; 239 | // Will have 31 bytes of b's next digits 240 | uint b_data; 241 | assembly { 242 | //Load from memory at the data location of a + a.length - (current_index - 32) 243 | // This can load a bit of extra data which will be masked off. 244 | a_data := mload(add(add(a, 0x20), sub(mload(a), add(current_index, 32)))) 245 | //Load from memory at the data location of b + b.length - (current_index - 32) 246 | b_data := mload(add(add(b, 0x20), sub(mload(b), add(current_index, 32)))) 247 | } 248 | a_data = a_data & mask; 249 | b_data = b_data & mask; 250 | uint sub_digit; 251 | // We now check if we can sub b_data + carry from a_data 252 | if (a_data >= b_data + carry) { 253 | sub_digit = a_data - (b_data + carry); 254 | carry = 0; 255 | } else { 256 | // If not we add a one digit at the top of a, then sub 257 | sub_digit = (a_data + max_set_digit) - (b_data + carry); 258 | carry = 1; 259 | } 260 | 261 | // Store the sum-ed digits 262 | assembly { 263 | mstore(add(add(c, 0x20), sub(mload(c), add(current_index, 32))), sub_digit) 264 | } 265 | current_index += 31; 266 | } 267 | 268 | // Now we go byte by byte through the bytes of a 269 | while (current_index < a.length) { 270 | uint16 a_data = uint16(uint8(a[a.length - current_index-1])); 271 | 272 | // Since tighly packed this may implicly be zero without being set 273 | uint16 b_data; 274 | if (current_index < b.length) { 275 | b_data = uint16(uint8(b[b.length - current_index-1])); 276 | } else { 277 | b_data = 0; 278 | } 279 | 280 | uint sub_digit; 281 | // We now check if we can sub b_data + carry from a_data 282 | if (a_data >= b_data + carry) { 283 | sub_digit = a_data - (b_data + carry); 284 | carry = 0; 285 | } else { 286 | // If not we add a one digit at the top of a, then sub 287 | sub_digit = (a_data + 0x0100) - (b_data + carry); 288 | carry = 1; 289 | } 290 | 291 | c[c.length - current_index-1] = bytes1(uint8(sub_digit)); 292 | current_index++; 293 | } 294 | require(carry == 0, "Underflow error"); 295 | c = trim(c); 296 | return c; 297 | } 298 | 299 | // Cheap big number comparsion using hash 300 | // TODO - Verify that this is actually cheaper for the bitsize in question 301 | function big_eq(bytes memory a, bytes memory b) internal pure returns(bool) { 302 | return keccak256(abi.encodePacked(a)) == keccak256(abi.encodePacked(b)); 303 | } 304 | 305 | // Thanks to Dankrad Feist for the bignum exp, hash to prime, and prime test. 306 | // https://github.com/dankrad/rsa-bounty/blob/master/contract/rsa_bounty.sol 307 | 308 | uint256 constant prime_mask = 0x7fff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff_f000; 309 | 310 | // This function checks if: 311 | // (1) If h = Hash(input_random, y) 312 | // (1a) That h is equal to prime except at the 12 last bits and the most signifigant bit. 313 | // (1b) that the prime has msb 1 314 | // (2) That prime candidate passes the miller rabbin test with 28 round of randomly derived bases [derived from y] 315 | // TODO - consider adding blockhash to the random base derivation for extra security. 316 | function check_hash_to_prime(bytes32 input_random, bytes memory y, uint256 prime) public view { 317 | // Check p is correct result for hash-to-prime 318 | require(prime & prime_mask == uint(sha256(abi.encodePacked(input_random, y))) & prime_mask); 319 | require(prime > (1 << 255)); 320 | require(miller_rabin_test(prime)); 321 | } 322 | 323 | // Expmod for small operands 324 | function expmod(uint256 base, uint256 e, uint256 m) public view returns (uint o) { 325 | assembly { 326 | // Get free memory pointer 327 | let p := mload(0x40) 328 | // Store parameters for the Expmod (0x05) precompile 329 | mstore(p, 0x20) // Length of Base 330 | mstore(add(p, 0x20), 0x20) // Length of Exponent 331 | mstore(add(p, 0x40), 0x20) // Length of Modulus 332 | mstore(add(p, 0x60), base) // Base 333 | mstore(add(p, 0x80), e) // Exponent 334 | mstore(add(p, 0xa0), m) // Modulus 335 | 336 | // Call 0x05 (EXPMOD) precompile 337 | if iszero(staticcall(sub(gas(), 2000), 0x05, p, 0xc0, p, 0x20)) { 338 | revert(0, 0) 339 | } 340 | o := mload(p) 341 | } 342 | } 343 | 344 | // Expmod for bignum operands (encoded as bytes, only base and modulus) 345 | function bignum_expmod(bytes memory base, uint256 e, bytes memory m) public view returns (bytes memory o) { 346 | assembly { 347 | // Get free memory pointer 348 | let p := mload(0x40) 349 | 350 | // Get base length in bytes 351 | let bl := mload(base) 352 | // Get modulus length in bytes 353 | let ml := mload(m) 354 | 355 | // Store parameters for the Expmod (0x05) precompile 356 | mstore(p, bl) // Length of Base 357 | mstore(add(p, 0x20), 0x20) // Length of Exponent 358 | mstore(add(p, 0x40), ml) // Length of Modulus 359 | // Use Identity (0x04) precompile to memcpy the base 360 | if iszero(staticcall(10000, 0x04, add(base, 0x20), bl, add(p, 0x60), bl)) { 361 | revert(0, 0) 362 | } 363 | mstore(add(p, add(0x60, bl)), e) // Exponent 364 | // Use Identity (0x04) precompile to memcpy the modulus 365 | if iszero(staticcall(10000, 0x04, add(m, 0x20), ml, add(add(p, 0x80), bl), ml)) { 366 | revert(0, 0) 367 | } 368 | 369 | // Call 0x05 (EXPMOD) precompile 370 | if iszero(staticcall(sub(gas(), 2000), 0x05, p, add(add(0x80, bl), ml), add(p, 0x20), ml)) { 371 | revert(0, 0) 372 | } 373 | 374 | // Update free memory pointer 375 | mstore(0x40, add(add(p, ml), 0x20)) 376 | 377 | // Store correct bytelength at p. This means that with the output 378 | // of the Expmod precompile (which is stored as p + 0x20) 379 | // there is now a bytes array at location p 380 | mstore(p, ml) 381 | 382 | // Return p 383 | o := p 384 | } 385 | } 386 | 387 | uint256 constant miller_rabin_checks = 28; 388 | 389 | // Use the Miller-Rabin test to check whether n>3, odd is a prime 390 | function miller_rabin_test(uint256 n) public view returns (bool) { 391 | require(n > 3); 392 | require(n & 0x1 == 1); 393 | uint256 d = n - 1; 394 | uint256 r = 0; 395 | while(d & 0x1 == 0) { 396 | d /= 2; 397 | r += 1; 398 | } 399 | for(uint256 i = 0; i < miller_rabin_checks; i++) { 400 | // pick a pseudo-random integer a in the range [2, n − 2] 401 | uint256 a = (uint256(sha256(abi.encodePacked(n, i))) % (n - 3)) + 2; 402 | uint256 x = expmod(a, d, n); 403 | if(x == 1 || x == n - 1) { 404 | continue; 405 | } 406 | bool check_passed = false; 407 | for(uint256 j = 1; j < r; j++) { 408 | x = mulmod(x, x, n); 409 | if(x == n - 1) { 410 | check_passed = true; 411 | break; 412 | } 413 | } 414 | if(!check_passed) { 415 | return false; 416 | } 417 | } 418 | return true; 419 | } 420 | } 421 | -------------------------------------------------------------------------------- /contracts/VerifierTesting.sol: -------------------------------------------------------------------------------- 1 | pragma solidity ^0.6.4; 2 | 3 | import './Verifier.sol'; 4 | 5 | contract VerifierTesting is Verifier { 6 | function big_add_external(bytes calldata a, bytes calldata b) external view returns(bytes memory) { 7 | return big_add(a, b); 8 | } 9 | 10 | function big_sub_external(bytes calldata a, bytes calldata b) external view returns(bytes memory) { 11 | return big_sub(a, b); 12 | } 13 | 14 | function verify_vdf_proof_gas(bytes32 input_random, bytes memory y, bytes memory pi, uint256 iterations, uint256 prime) public returns(bool){ 15 | verify_vdf_proof(input_random, y, pi, iterations, prime); 16 | return true; 17 | } 18 | } -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "VDF", 3 | "version": "1.0.0", 4 | "description": "Ethereum VDF Verifier", 5 | "main": "index.js", 6 | "directories": { 7 | "test": "test" 8 | }, 9 | "dependencies": { 10 | "solc": "^0.6.4", 11 | "tslint-eslint-rules": "^5.4.0" 12 | }, 13 | "devDependencies": { 14 | "@0x/tslint-config": "^4.0.0", 15 | "@nomiclabs/buidler": "^1.2.0", 16 | "@nomiclabs/buidler-ethers": "^1.2.0", 17 | "@nomiclabs/buidler-waffle": "^1.2.0", 18 | "@types/chai": "^4.2.11", 19 | "@types/mocha": "^7.0.2", 20 | "@types/node": "^13.9.8", 21 | "buidler-typechain": "^0.0.5", 22 | "chai": "^4.2.0", 23 | "ethereum-waffle": "^2.4.0", 24 | "ethers": "^4.0.46", 25 | "husky": "^4.2.3", 26 | "prettier": "^1.19.1", 27 | "prettier-plugin-solidity": "^1.0.0-alpha.47", 28 | "solhint": "^2.3.1", 29 | "solhint-plugin-prettier": "0.0.4", 30 | "ts-generator": "^0.0.8", 31 | "ts-node": "^8.8.1", 32 | "tslint": "^5.20.1", 33 | "tslint-config-prettier": "^1.18.0", 34 | "typechain": "^1.0.5", 35 | "typechain-target-ethers": "^1.0.4", 36 | "typechain-target-truffle": "^1.0.2", 37 | "typechain-target-web3-v1": "^1.0.4", 38 | "typescript": "^3.8.3" 39 | }, 40 | "scripts": { 41 | "test": "npx buidler test", 42 | "build": "npx buidler compile && npx buidler typechain", 43 | "lint": "tslint --format stylish --project . && npm run-script solhint", 44 | "prettier": "npm run-script prettier:sol && npm run-script prettier:ts", 45 | "prettier:ts": "prettier --write '**/*.ts' --config .prettierrc", 46 | "prettier:sol": "prettier --write **/*.sol **/**/*.sol", 47 | "fix:ts": "tslint --fix --format stylish --project .", 48 | "solhint": "./node_modules/.bin/solhint -f table contracts/*.sol contracts/**/*.sol" 49 | }, 50 | "collaborators": [ 51 | "Alex Towle ", 52 | "Paul Vienhage " 53 | ], 54 | "license": "ISC" 55 | } 56 | -------------------------------------------------------------------------------- /proof_0x.json: -------------------------------------------------------------------------------- 1 | { 2 | "modulus": "25195908475657893494027183240048398571429282126204032027777137836043662020707595556264018525880784406918290641249515082189298559149176184502808489120072844992687392807287776735971418347270261896375014971824691165077613379859095700097330459748808428401797429100642458691817195118746121515172654632282216869987549182422433637259085141865462043576798423387184774447920739934236584823824281198163815010674810451660377306056201619676256133844143603833904414952634432190114657544454178424020924616515723350778707749817125772467962926386356373289912154831438167899885040445364023527381951378636564391212010397122822120720357", 3 | "t": "20000000000", 4 | "l": "85662111592862346263186698143453015874008011257636061396911716779587836621869", 5 | "pi": "9928420349723242112532164327531252469753597170604462735297790898248291966130083797050199155802056230484770939099553807108856710624153592270699078738112812683199308967251445539036382263882610826925814948358470438662969003408552842001205474967895497756841603524962892651799752908230633143831082367448104222367558977535571783695843999499831333467085379022556410054467079803435688966181316317427944163157962046345756936023590192430144403913257191940874898966527017376547838226639333469755613895107124622796673320983329726054850114322019381368685002828329777829437493203355689870594603880340235794321259879413721188274468", 6 | "r": "58331467442367014389447471084988597037858368477510582590579882476211655419860", 7 | "g": "11440827028973980734839007730550907915780281832104850997958208328182874869830", 8 | "y_orig": "6163680931915101617594995440077767914515844895061569549960705087686691592957713944827169044749589804665399086140523636322988287470159147391143497723742186015810671346561343864619553787522297164963360189291845068880442478922715848339383066294966320389471769559944408256131473390176498454896737794940533523064741355846474665957305029176622482018950674601629528061703730858730921631833484711947770541203318527860357224243004876905721642851532301263042353481451233091206702162312626551072846876957209131611873120616780876242383197079440685477763655067971904879472287242174884080314531138861162618654475360250987846273244", 9 | "y": "6163680931915101617594995440077767914515844895061569549960705087686691592957713944827169044749589804665399086140523636322988287470159147391143497723742186015810671346561343864619553787522297164963360189291845068880442478922715848339383066294966320389471769559944408256131473390176498454896737794940533523064741355846474665957305029176622482018950674601629528061703730858730921631833484711947770541203318527860357224243004876905721642851532301263042353481451233091206702162312626551072846876957209131611873120616780876242383197079440685477763655067971904879472287242174884080314531138861162618654475360250987846273244" 10 | } 11 | -------------------------------------------------------------------------------- /test/vdf_test.ts: -------------------------------------------------------------------------------- 1 | import {waffle} from '@nomiclabs/buidler'; 2 | import chai from 'chai'; 3 | import {deployContract, solidity} from 'ethereum-waffle'; 4 | import {utils, ethers} from 'ethers'; 5 | 6 | import VerifierTestingArtifact from '../artifacts/VerifierTesting.json'; 7 | import {VerifierTesting} from '../typechain/VerifierTesting'; 8 | 9 | chai.use(solidity); 10 | const {expect} = chai; 11 | 12 | describe('Verifier Testing', () => { 13 | let verifier: any; 14 | const init_hex = '0x0123456789abcded'; 15 | 16 | const provider = waffle.provider; 17 | const [wallet] = provider.getWallets(); 18 | 19 | before(async () => { 20 | verifier = (await deployContract( 21 | wallet, 22 | VerifierTestingArtifact, 23 | )) as VerifierTesting; 24 | }); 25 | 26 | it('Should add big numbs correctly', async () => { 27 | // This first test is basic but uses both parts of the function. 28 | const c = await verifier.big_add_external( 29 | '0x00ffffff6c9b26d064d9364d9364d9364d9364d9364d9364d9364d9364d9364e', 30 | '0x00ffffff6c9b26d064d9364d9364d9364d9364d9364d9364d9364d9364d9364e', 31 | ); 32 | expect(c).to.be.eq( 33 | '0x01fffffed9364da0c9b26c9b26c9b26c9b26c9b26c9b26c9b26c9b26c9b26c9c'.toLocaleLowerCase(), 34 | ); 35 | // We will randomly sample much larger numbs for more cases 36 | for (let i = 0; i < 10; i++) { 37 | // 256 bytes is the target big numb rsa size 38 | const a = utils.randomBytes(256); 39 | const b = utils.randomBytes(256); 40 | verifier.big_add_external(a, b).then((c: any) => { 41 | expect(c).to.be.eq( 42 | utils 43 | .bigNumberify(a) 44 | .add(utils.bigNumberify(b)) 45 | .toHexString(), 46 | ); 47 | }); 48 | } 49 | }); 50 | 51 | it('Should sub big numbs correctly', async () => { 52 | // This first test is basic but uses both parts of the function. 53 | const c = await verifier.big_sub_external( 54 | '0x9185cf46bc8ef7d6a2906b5db87c43611f40bc47bccd14d5606d89b5e35ca620', 55 | '0x8e819e9b4fcaf230255c4273059121d96e45da765348d66fabbb3fa0304a68dd', 56 | ); 57 | expect(c).to.be.eq( 58 | '0x030430ab6cc405a67d3428eab2eb2187b0fae1d169843e65b4b24a15b3123d43'.toLocaleLowerCase(), 59 | ); 60 | // We will randomly sample much larger numbs for more cases 61 | for (let i = 0; i < 10; i++) { 62 | // 256 bytes is the target big numb rsa size 63 | let a = utils.randomBytes(32); 64 | let b = utils.randomBytes(32); 65 | // We don't want underflow reverts 66 | if (utils.bigNumberify(a).lt(utils.bigNumberify(b))) { 67 | [a, b] = [b, a]; 68 | } 69 | verifier.big_sub_external(a, b).then((c: any) => { 70 | expect(c).to.be.eq( 71 | utils 72 | .bigNumberify(a) 73 | .sub(utils.bigNumberify(b)) 74 | .toHexString(), 75 | ); 76 | }); 77 | } 78 | }); 79 | 80 | it('Should validate a correct hash to prime', async () => { 81 | await verifier.check_hash_to_prime( 82 | '0xB8BA422C143FC4091BE420A7702CDD814B6D7DE7BBA7F19EC4F546B97691194F', 83 | '0x56F6638C8E6465BFF83B70B88EDEB590E8AC7D18AC03E9D6C3D4F0D6DD0D0D29422F9D8F6D38858A63498E76F6D8B45B05AB69C105E24FC60F6E4FF9184D63AABD3BBEE3C041251EBE2F89C9AE936643F51EB62C76BF5F07CF9A45081073AF0145C96472F3CF253C6E5D83E997455235B4D2EA36CEF284FC2B59A17472D479ECA7FE72E53D3FA7029110AD7536980CCBACF64DD819B6848A4A4A16D5B4CFF747CD6F61EA7F3055AEA2A72B2AED710113A00C53A85902752687795E96B3D3953AE0D8F067382242FFD789246D0B79FA2B6018B2E9B8642D2158659DACE5FB57AE1087C204B142137C9E5F5DB3694CFBA0393E641D10640DD12E313E11F00A5ED0', 84 | '0x84e07693b3c6f6ae1e9b128abebf2e743b5f68bf24ab3ff27947221b47f490a3', 85 | ); 86 | }); 87 | 88 | it('Should validate a correct proof', async () => { 89 | const result = await (await verifier.verify_vdf_proof_gas( 90 | // input random / g 91 | '0x194B4753D92469B4EC1C01AD36C38D53C75F32701B148D215D49A292284D9046', 92 | // y 93 | '0x30D364E0C51908B61E5CCBD924A27D1CE16B286038F5FD2052AAA9D29E146A3BE2261E64F487A063F9152DFE67259BF6B083AA08620FBD96D21F06AAF22BA3BF3CAB3AC4C95C3C10D440DFEF38DA3231E25FAEA7094BEA2E6ED28FA7C6EB16B88E5B16E17B876ABA9A397A18D01AA8A53144E0A47F442AE5A2074420CF5CF2C8C79343FF1ABF17F0AB24D77C428923781CDD08320DC269A2D9817F057BC0424A81C9CF0342D65895767541DC4F658074B78E48AB9B62B4AF6C676B1A0B6B197703838D99E41502010FD7A60D7E66447CF2EFC88F9ED57A3CC048860713D11DBE260DDF8A8BCB397B06C898CA90871481AB1713439021D78B19E4B0D26DDB88DC', 94 | // pi 95 | '0x4EA5F2F9B56E43F79F52199F6E01195E48844600D4CEA0215B78982702091462B70D9601D6F5EBF78EF2EDE8814F8F3D5C36C718559F658ADE8B3BBF37E7D2FA23A96F2E7F9EACC70C8C3678ED7C36E419F58A1E77EDA6BCF6A811D5CF021E24870FDD027351A93861BD69AA12CEF59AAF4CAD912733E5D84F292BF062E2530F24602A314FA7CE20D77843FD7CE02F43A721EA7245395CB25F99980DF6A64CCD2B2FF92CC96F93FEE9BB2F7FC1F0F11E39F3706CFF772008129A9601421BBB6F4FED13AB2F7CC401959C5EA6AC7E47B230C66E1730521AD8BDF68C9822F4970925A42A74797EED58CC845FD77DB63517368011982D424DABC07D211890D41124', 96 | // iterations / t 97 | 20000000000, 98 | // prime / l 99 | '0xBD63097802DC383264E04E795B649A4B50F10B7D9A6023EAC74B6DA9D49CB42D', 100 | )).wait(); 101 | console.log("The verifier took this much gas:"); 102 | console.log(result.gasUsed.toNumber()); 103 | }); 104 | }); 105 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "module": "commonjs", 5 | "strict": true, 6 | "esModuleInterop": true, 7 | "outDir": "dist", 8 | "resolveJsonModule": true 9 | }, 10 | "include": ["./scripts", "./test"], 11 | "files": [ 12 | "./buidler.config.ts", 13 | "./node_modules/@nomiclabs/buidler-ethers/src/type-extensions.d.ts", 14 | "node_modules/buidler-typechain/src/type-extensions.d.ts", 15 | "./node_modules/@nomiclabs/buidler-waffle/src/type-extensions.d.ts" 16 | ] 17 | } 18 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": ["@0x/tslint-config"], 3 | "rules": { 4 | "custom-no-magic-numbers": false 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /verifier.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | ########################################################################### 4 | # Copyright 2019 Supranational LLC 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # http://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | ########################################################################### 18 | 19 | # Comments refer to the paper "Efficient verifiable delay functions" by 20 | # Benjamin Wesolowski, specifically the 2/5/19 eprint update. 21 | # https://eprint.iacr.org/2018/623 22 | 23 | import hashlib 24 | import random 25 | import sympy 26 | import json 27 | 28 | ########################################################################### 29 | # Constants 30 | ########################################################################### 31 | 32 | # Size of the small prime. For RSA 1024 this would be around 168 bits. 33 | PRIME_BITS = 256 34 | PRIME_BYTES = PRIME_BITS // 8 35 | MOD_BITS = 2048 36 | 37 | proof = json.loads(open('proof_0x.json').read()) 38 | 39 | # 2048 bit RSA modulus - this is fixed for a long time 40 | modulus = int(proof['modulus']) 41 | 42 | ########################################################################### 43 | # Inputs 44 | ########################################################################### 45 | 46 | # VDF input taken from Ethereum block hash. This is "g" in the wesolowski 47 | # paper. 48 | # https://etherscan.io 49 | # eth block 9619000 50 | # We might want to send in a block number and take the block hash from the 51 | # chain if that is an option. 52 | #g = 83554654396998814025015691931508621990409003355162694699046114859281714059599 53 | g = int(proof['g']) 54 | 55 | # Number of iterated squares in the VDF. The VDF computes: 56 | # y = g**(2**t) 57 | # as described in Algorithm 1. This should be an input since it will 58 | # vary depending on use case. 59 | t = int(proof['t']) 60 | 61 | # Final VDF evaluation result. We probably don't need to send this in - 62 | # verification method 2 does not need it. 63 | y = int(proof['y']) 64 | 65 | # Small prime used to generate the proof. Step 1 in proof generation from 66 | # page 10 in the paper. Note we will look at more EVM efficient ways to 67 | # generate this. 68 | l = int(proof['l']) 69 | 70 | # Proof value. Step 2 on page 10 in the Wesolowski paper and Algorithm 1. 71 | pi = int(proof['pi']) 72 | 73 | def hash_input(g, y, desired_bits): 74 | #bytes = "{:x}*{:x}".format(g, y).encode() 75 | bytes_g = g.to_bytes(PRIME_BITS//8, byteorder='big') 76 | bytes_y = y.to_bytes(MOD_BITS//8, byteorder='big') 77 | bytes = bytes_g + bytes_y 78 | hash = hashlib.sha256(bytes).digest() 79 | h = int.from_bytes(hash, byteorder='big') 80 | 81 | mask = (1 << desired_bits) - 1 82 | return h & mask 83 | 84 | 85 | # Sample a prime from Primes(2k) as described on page 10 of the Wesolowski 86 | # paper. This function is not great for the EVM but there are ideas on 87 | # how to improve it. 88 | # Sample a prime 89 | # g - VDF input 90 | # y - VDF output 91 | def sample_prime(g, y, desired_bits): 92 | l = None 93 | 94 | mask = (1 << desired_bits) - 1 95 | bytes_g = g.to_bytes(PRIME_BITS//8, byteorder='big') 96 | bytes_y = y.to_bytes(MOD_BITS//8, byteorder='big') 97 | bytes = bytes_g + bytes_y 98 | #bytes = "{:x}*{:x}".format(g, y).encode() 99 | hash = hashlib.sha256(bytes).digest() 100 | l = int.from_bytes(hash, byteorder='big') 101 | 102 | while True: 103 | # Mask out all but desired number of bits 104 | l = l & mask 105 | # Set the top bit 106 | l = l | (1 << (desired_bits - 1)) 107 | 108 | if sympy.isprime(l): 109 | break 110 | 111 | # Number is not prime, increment and try again. 112 | l += 1 113 | 114 | return(l) 115 | 116 | def check_in_group(e): 117 | return not e > modulus//2 118 | 119 | def cast_to_group(e): 120 | if e > modulus//2: 121 | return modulus - e 122 | else: 123 | return e 124 | 125 | # ########################################################################### 126 | # # Proof verification Method 1 - Algorithm 2 in Wesolowski paper 127 | # ########################################################################### 128 | 129 | # In this approach we need to send y and pi to the verifier, each of which 130 | # are the RSA modulus size. An optimization is possible (below) where 131 | # we can transmit fewer bits. 132 | 133 | # Compute the sample prime. Since g is already a block hash we are using that 134 | # directly as the input. 135 | # l = sample_prime(g, y, PRIME_BITS) 136 | 137 | # # Compute r per the verification process 138 | r = pow(2, t, l) 139 | 140 | # # Verify the result 141 | if (pow(pi, l, modulus) * pow(g, r, modulus) % modulus) != y: 142 | print("ERROR: proof does not verify") 143 | else: 144 | print("Method 1 PASS!") 145 | exit() 146 | 147 | ########################################################################### 148 | # Proof verification Method 2 - reduced storage from section 4.2 from paper 149 | ########################################################################### 150 | 151 | # In this approach we send l (256 bits) and pi (2048 or 1024 bits) and 152 | # use them to recover y. This is probably the preferred approach. 153 | 154 | if not check_in_group(g): 155 | print("ERROR: input is not in the quotient group") 156 | 157 | if not check_in_group(pi): 158 | print("ERROR: proof is not in the quotient group") 159 | 160 | # Compute r and y per the verification process in 4.2 161 | r = cast_to_group(pow(2, t, l)) 162 | y = cast_to_group((pow(pi, l, modulus) * pow(g, r, modulus)) % modulus) 163 | 164 | if not check_in_group(y): 165 | print("ERROR: output is not in the quotient group") 166 | 167 | # Verify l 168 | mask = (1 << (PRIME_BITS - 1)) - 1 169 | mask ^= ((1 << 12) - 1) 170 | if l & mask != hash_input(g, y, PRIME_BITS) & mask: 171 | print("ERROR: l does not match the input hash") 172 | if l >> (PRIME_BITS - 1) == 0: 173 | print("ERROR: top bit of l is not set") 174 | if not sympy.isprime(l): 175 | print("ERROR: l is not prime") 176 | 177 | validate_l = sample_prime(g, y, PRIME_BITS) 178 | if validate_l != l: 179 | print("ERROR: proof does not verify - l does not match") 180 | else: 181 | print("Method 2 PASS!") 182 | 183 | 184 | --------------------------------------------------------------------------------