├── README.md ├── .gitignore ├── tests └── test_sim_fa.py ├── contracts ├── gates_fulladder4_generated.cairo └── sim.cairo └── LICENSE /README.md: -------------------------------------------------------------------------------- 1 | # Christopher 2 | A gate level simulator and gate level netlist standard specification in Cairo 3 | 4 | ### Proof of concept 5 | - `sim.cairo`: event-driven simulator using storage as queues 6 | - `gates_fulladder4_generated.cairo`: a generated contract representation for a 4b full adder circuit 7 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /tests/test_sim_fa.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import os 3 | from starkware.starknet.testing.starknet import Starknet 4 | import random 5 | 6 | @pytest.mark.asyncio 7 | async def test_queue(): 8 | starknet = await Starknet.empty() 9 | print() 10 | 11 | contract_sim = await starknet.deploy ('contracts/sim.cairo') 12 | print(f'> sim.cairo deployed.') 13 | 14 | TEST_GATES = 'gates_fulladder4_generated' 15 | contract_gates = await starknet.deploy (f'contracts/{TEST_GATES}.cairo') 16 | print(f'> {TEST_GATES}.cairo deployed.') 17 | print() 18 | 19 | seed = random.randrange(1,100) 20 | await contract_sim.admin_initialize_seed(seed).invoke() 21 | 22 | ret = await contract_gates.net_count().call() 23 | net_count = ret.result.net_count 24 | ret = await contract_gates.input_net_count().call() 25 | input_net_count = ret.result.input_net_count 26 | ret = await contract_gates.output_net_count().call() 27 | output_net_count = ret.result.output_net_count 28 | 29 | print('> Submitting gates to the simulator ...') 30 | await contract_sim.submit_gates_for_simulation(contract_gates.contract_address).invoke() 31 | print(' -> Done\n') 32 | 33 | # ret = await contract_sim.admin_get_event_queue_read_head().call() 34 | # eq_rd_head = ret.result.rd_idx 35 | # ret = await contract_sim.admin_get_event_queue_write_head().call() 36 | # eq_wr_head = ret.result.wr_idx 37 | 38 | # print(f'> Content of event_queue:') 39 | # for i in range(eq_rd_head, eq_wr_head): 40 | # ret = await contract_sim.admin_read_event_queue(i).call() 41 | # print(ret.result.event) 42 | # print() 43 | 44 | print(f'> Running simulation ...') 45 | ret_simulation = await contract_sim.run_simulation(contract_gates.contract_address).invoke() 46 | #print(ret.result) 47 | print(' -> Done\n') 48 | 49 | # print(f'> Content of net_table:') 50 | # for i in range(net_count): 51 | # ret = await contract_sim.admin_view_net_table(i).call() 52 | # print(f'{i} : {ret.result}') 53 | # print() 54 | 55 | ## retrieve input stimulus for A and B 56 | A = '' 57 | B = '' 58 | for i in range(input_net_count): 59 | #print(f'> querying {i}th of net table') 60 | ret = await contract_sim.admin_view_net_table(i).call() 61 | if i%2==0: 62 | #A += ret.result.net_val * 2**i 63 | A = str(ret.result.net_val) + A 64 | else: 65 | #B += ret.result.net_val * 2**i 66 | B = str(ret.result.net_val) + B 67 | A_int = int(A,2) 68 | B_int = int(B,2) 69 | print(f'> A=0x{A} ({A_int}), B=0x{B} ({B_int})') 70 | 71 | S = '' 72 | for i in range(output_net_count): 73 | idx = net_count-output_net_count+i 74 | #print(f'> querying {idx}th of net table') 75 | ret = await contract_sim.admin_view_net_table(idx).call() 76 | if idx%2==1: 77 | #S += ret.result.net_val * 2**i 78 | S = str(ret.result.net_val) + S 79 | elif idx==net_count-1: 80 | #S += ret.result.net_val * 2**i 81 | S = str(ret.result.net_val) + S 82 | S_int = int(S,2) 83 | print(f'> S=0x{S} ({S_int})') 84 | 85 | assert S_int == A_int + B_int, f'{S_int} != {A_int} + {B_int}' 86 | print(f'> {S_int} == {A_int} + {B_int}') 87 | print(' -> Test passed') 88 | print() 89 | 90 | print('Performance estimation:') 91 | print(f'> Latency: {ret_simulation.result.latency_unitless} (unitless)') 92 | print(f'> Area: {ret_simulation.result.area} (unitless)') 93 | print() 94 | 95 | 96 | # ret = await contract_sim.admin_get_event_queue_read_head().call() 97 | # eq_rd_head = ret.result.rd_idx 98 | # ret = await contract_sim.admin_get_event_queue_write_head().call() 99 | # eq_wr_head = ret.result.wr_idx 100 | 101 | # print(f'> Content of event_queue:') 102 | # for i in range(eq_rd_head, eq_wr_head): 103 | # ret = await contract_sim.admin_read_event_queue(i).call() 104 | # print(ret.result.event) 105 | # print() 106 | 107 | # ret = await contract_sim.admin_get_gate_queue_read_head().call() 108 | # gq_rd_head = ret.result.rd_idx 109 | # ret = await contract_sim.admin_get_gate_queue_write_head().call() 110 | # gq_wr_head = ret.result.wr_idx 111 | 112 | # print(f'> Content of gate_queue:') 113 | # for i in range(gq_rd_head, gq_wr_head): 114 | # ret = await contract_sim.admin_read_gate_queue(i).call() 115 | # print(ret.result) 116 | # print() -------------------------------------------------------------------------------- /contracts/gates_fulladder4_generated.cairo: -------------------------------------------------------------------------------- 1 | %lang starknet 2 | %builtins pedersen range_check 3 | 4 | from starkware.cairo.common.cairo_builtins import HashBuiltin 5 | from starkware.cairo.common.alloc import alloc 6 | 7 | ## Netlist: 8 | ## N0, N1 -> G0 (XOR) -> N17 9 | ## N0, N1 -> G1 (AND) -> N18 10 | ## N2, N3 -> G2 (XOR) -> N8 11 | ## N18, N8 -> G3 (XOR) -> N19 12 | ## N18, N8 -> G4 (AND) -> N9 13 | ## N2, N3 -> G5 (AND) -> N10 14 | ## N9, N10 -> G6 (OR) -> N20 15 | ## N4, N5 -> G7 (XOR) -> N11 16 | ## N20, N11 -> G8 (XOR) -> N21 17 | ## N20, N11 -> G9 (AND) -> N12 18 | ## N4, N5 -> G10 (AND) -> N13 19 | ## N12, N13 -> G11 (OR) -> N22 20 | ## N6, N7 -> G12 (XOR) -> N14 21 | ## N22, N14 -> G13 (XOR) -> N23 22 | ## N22, N14 -> G14 (AND) -> N15 23 | ## N6, N7 -> G15 (AND) -> N16 24 | ## N15, N16 -> G16 (OR) -> N24 25 | 26 | ## Constants viewable: 27 | const GATE_COUNT = 17 28 | @view 29 | func gate_count {} () -> (gate_count : felt): 30 | return (GATE_COUNT) 31 | end 32 | 33 | const NET_COUNT = 25 34 | @view 35 | func net_count {} () -> (net_count : felt): 36 | return (NET_COUNT) 37 | end 38 | 39 | const INPUT_NET_COUNT = 8 40 | @view 41 | func input_net_count {} () -> (input_net_count : felt): 42 | return (INPUT_NET_COUNT) 43 | end 44 | 45 | const OUTPUT_NET_COUNT = 8 46 | @view 47 | func output_net_count {} () -> (output_net_count : felt): 48 | return (OUTPUT_NET_COUNT) 49 | end 50 | 51 | ## Net value initialization: 52 | @view 53 | func init_net_values {range_check_ptr} () -> ( 54 | arr_len : felt, 55 | arr : felt* 56 | ): 57 | alloc_locals 58 | let (local arr) = alloc() 59 | assert [arr+0] = 2 60 | assert [arr+1] = 2 61 | assert [arr+2] = 2 62 | assert [arr+3] = 2 63 | assert [arr+4] = 2 64 | assert [arr+5] = 2 65 | assert [arr+6] = 2 66 | assert [arr+7] = 2 67 | assert [arr+8] = 2 68 | assert [arr+9] = 2 69 | assert [arr+10] = 2 70 | assert [arr+11] = 2 71 | assert [arr+12] = 2 72 | assert [arr+13] = 2 73 | assert [arr+14] = 2 74 | assert [arr+15] = 2 75 | assert [arr+16] = 2 76 | assert [arr+17] = 2 77 | assert [arr+18] = 2 78 | assert [arr+19] = 2 79 | assert [arr+20] = 2 80 | assert [arr+21] = 2 81 | assert [arr+22] = 2 82 | assert [arr+23] = 2 83 | assert [arr+24] = 2 84 | return (25, arr) 85 | end 86 | 87 | ## Gate index-to-type lookup: 88 | @view 89 | func gate_idx_to_typ {range_check_ptr} (gate_idx : felt) -> (gate_typ : felt): 90 | alloc_locals 91 | if gate_idx == 0: 92 | return (2) 93 | end 94 | if gate_idx == 1: 95 | return (1) 96 | end 97 | if gate_idx == 2: 98 | return (2) 99 | end 100 | if gate_idx == 3: 101 | return (2) 102 | end 103 | if gate_idx == 4: 104 | return (1) 105 | end 106 | if gate_idx == 5: 107 | return (1) 108 | end 109 | if gate_idx == 6: 110 | return (0) 111 | end 112 | if gate_idx == 7: 113 | return (2) 114 | end 115 | if gate_idx == 8: 116 | return (2) 117 | end 118 | if gate_idx == 9: 119 | return (1) 120 | end 121 | if gate_idx == 10: 122 | return (1) 123 | end 124 | if gate_idx == 11: 125 | return (0) 126 | end 127 | if gate_idx == 12: 128 | return (2) 129 | end 130 | if gate_idx == 13: 131 | return (2) 132 | end 133 | if gate_idx == 14: 134 | return (1) 135 | end 136 | if gate_idx == 15: 137 | return (1) 138 | end 139 | if gate_idx == 16: 140 | return (0) 141 | else: 142 | ## nonexistent gate index 143 | return (3) # 3 is an undefined gate type 144 | end 145 | end 146 | 147 | ## For querying fanout gates of a given net: 148 | @view 149 | func fanout_gate_given_net {range_check_ptr} ( 150 | net_idx : felt 151 | ) -> ( 152 | gate_idx_arr_len : felt, 153 | gate_idx_arr : felt* 154 | ): 155 | ## input felt: net index 156 | ## output felt: array of gate indices 157 | alloc_locals 158 | let (local gate_idx_arr) = alloc() 159 | 160 | if net_idx == 0: 161 | assert [gate_idx_arr + 0] = 1 162 | assert [gate_idx_arr + 1] = 0 163 | return (2, gate_idx_arr) 164 | end 165 | if net_idx == 1: 166 | assert [gate_idx_arr + 0] = 1 167 | assert [gate_idx_arr + 1] = 0 168 | return (2, gate_idx_arr) 169 | end 170 | if net_idx == 2: 171 | assert [gate_idx_arr + 0] = 5 172 | assert [gate_idx_arr + 1] = 2 173 | return (2, gate_idx_arr) 174 | end 175 | if net_idx == 3: 176 | assert [gate_idx_arr + 0] = 5 177 | assert [gate_idx_arr + 1] = 2 178 | return (2, gate_idx_arr) 179 | end 180 | if net_idx == 4: 181 | assert [gate_idx_arr + 0] = 10 182 | assert [gate_idx_arr + 1] = 7 183 | return (2, gate_idx_arr) 184 | end 185 | if net_idx == 5: 186 | assert [gate_idx_arr + 0] = 10 187 | assert [gate_idx_arr + 1] = 7 188 | return (2, gate_idx_arr) 189 | end 190 | if net_idx == 6: 191 | assert [gate_idx_arr + 0] = 12 192 | assert [gate_idx_arr + 1] = 15 193 | return (2, gate_idx_arr) 194 | end 195 | if net_idx == 7: 196 | assert [gate_idx_arr + 0] = 12 197 | assert [gate_idx_arr + 1] = 15 198 | return (2, gate_idx_arr) 199 | end 200 | if net_idx == 8: 201 | assert [gate_idx_arr + 0] = 3 202 | assert [gate_idx_arr + 1] = 4 203 | return (2, gate_idx_arr) 204 | end 205 | if net_idx == 9: 206 | assert [gate_idx_arr + 0] = 6 207 | return (1, gate_idx_arr) 208 | end 209 | if net_idx == 10: 210 | assert [gate_idx_arr + 0] = 6 211 | return (1, gate_idx_arr) 212 | end 213 | if net_idx == 11: 214 | assert [gate_idx_arr + 0] = 8 215 | assert [gate_idx_arr + 1] = 9 216 | return (2, gate_idx_arr) 217 | end 218 | if net_idx == 12: 219 | assert [gate_idx_arr + 0] = 11 220 | return (1, gate_idx_arr) 221 | end 222 | if net_idx == 13: 223 | assert [gate_idx_arr + 0] = 11 224 | return (1, gate_idx_arr) 225 | end 226 | if net_idx == 14: 227 | assert [gate_idx_arr + 0] = 13 228 | assert [gate_idx_arr + 1] = 14 229 | return (2, gate_idx_arr) 230 | end 231 | if net_idx == 15: 232 | assert [gate_idx_arr + 0] = 16 233 | return (1, gate_idx_arr) 234 | end 235 | if net_idx == 16: 236 | assert [gate_idx_arr + 0] = 16 237 | return (1, gate_idx_arr) 238 | end 239 | if net_idx == 17: 240 | return (0, gate_idx_arr) 241 | end 242 | if net_idx == 18: 243 | assert [gate_idx_arr + 0] = 3 244 | assert [gate_idx_arr + 1] = 4 245 | return (2, gate_idx_arr) 246 | end 247 | if net_idx == 19: 248 | return (0, gate_idx_arr) 249 | end 250 | if net_idx == 20: 251 | assert [gate_idx_arr + 0] = 8 252 | assert [gate_idx_arr + 1] = 9 253 | return (2, gate_idx_arr) 254 | end 255 | if net_idx == 21: 256 | return (0, gate_idx_arr) 257 | end 258 | if net_idx == 22: 259 | assert [gate_idx_arr + 0] = 13 260 | assert [gate_idx_arr + 1] = 14 261 | return (2, gate_idx_arr) 262 | end 263 | if net_idx == 23: 264 | return (0, gate_idx_arr) 265 | end 266 | if net_idx == 24: 267 | return (0, gate_idx_arr) 268 | else: 269 | ## nonexistent net index 270 | return (0, gate_idx_arr) 271 | end 272 | end 273 | 274 | ## Gate-to-ports lookup: 275 | @view 276 | func gate_ports_lookup {range_check_ptr} (gate_idx : felt) -> (vo_net_idx : felt, vi_1_net_idx : felt, vi_2_net_idx : felt): 277 | if gate_idx == 0: 278 | return (17,0,1) 279 | end 280 | if gate_idx == 1: 281 | return (18,0,1) 282 | end 283 | if gate_idx == 2: 284 | return (8,2,3) 285 | end 286 | if gate_idx == 3: 287 | return (19,18,8) 288 | end 289 | if gate_idx == 4: 290 | return (9,18,8) 291 | end 292 | if gate_idx == 5: 293 | return (10,2,3) 294 | end 295 | if gate_idx == 6: 296 | return (20,9,10) 297 | end 298 | if gate_idx == 7: 299 | return (11,4,5) 300 | end 301 | if gate_idx == 8: 302 | return (21,20,11) 303 | end 304 | if gate_idx == 9: 305 | return (12,20,11) 306 | end 307 | if gate_idx == 10: 308 | return (13,4,5) 309 | end 310 | if gate_idx == 11: 311 | return (22,12,13) 312 | end 313 | if gate_idx == 12: 314 | return (14,6,7) 315 | end 316 | if gate_idx == 13: 317 | return (23,22,14) 318 | end 319 | if gate_idx == 14: 320 | return (15,22,14) 321 | end 322 | if gate_idx == 15: 323 | return (16,6,7) 324 | end 325 | if gate_idx == 16: 326 | return (24,15,16) 327 | else: 328 | ## nonexistent gate index 329 | return (0,0,0) 330 | end 331 | end 332 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /contracts/sim.cairo: -------------------------------------------------------------------------------- 1 | %lang starknet 2 | %builtins pedersen range_check bitwise 3 | 4 | from starkware.cairo.common.cairo_builtins import BitwiseBuiltin 5 | from starkware.cairo.common.cairo_builtins import HashBuiltin 6 | from starkware.cairo.common.math import unsigned_div_rem, split_felt 7 | from starkware.cairo.common.math_cmp import is_not_zero 8 | from starkware.cairo.common.bitwise import bitwise_operations, bitwise_or, bitwise_and, bitwise_xor 9 | from starkware.cairo.common.alloc import alloc 10 | 11 | ## Event-driven simulator. ref: http://cs.baylor.edu/~maurer/aida/desauto/chapter3.pdf 12 | 13 | #################################### 14 | ########### Event Queue ############ 15 | #################################### 16 | 17 | struct Event: 18 | member net_idx : felt 19 | member new_val : felt 20 | end 21 | 22 | @storage_var 23 | func event_queue ( 24 | idx : felt 25 | ) -> ( 26 | event : Event 27 | ): 28 | end 29 | 30 | @storage_var 31 | func event_queue_read_head () -> ( 32 | rd_idx : felt 33 | ): 34 | end 35 | 36 | @storage_var 37 | func event_queue_write_head () -> ( 38 | wr_idx : felt 39 | ): 40 | end 41 | 42 | @view 43 | func admin_get_event_queue_read_head {syscall_ptr : felt*, pedersen_ptr : HashBuiltin*, range_check_ptr} () -> ( 44 | rd_idx : felt 45 | ): 46 | return event_queue_read_head.read() 47 | end 48 | 49 | @view 50 | func admin_get_event_queue_write_head {syscall_ptr : felt*, pedersen_ptr : HashBuiltin*, range_check_ptr} () -> ( 51 | wr_idx : felt 52 | ): 53 | return event_queue_write_head.read() 54 | end 55 | 56 | func _write_event_queue {syscall_ptr : felt*, pedersen_ptr : HashBuiltin*, range_check_ptr} ( 57 | event : Event 58 | ) -> (): 59 | let (wr_idx) = event_queue_write_head.read() 60 | event_queue.write(wr_idx, event) 61 | event_queue_write_head.write(wr_idx+1) 62 | return () 63 | end 64 | 65 | @view 66 | func admin_read_event_queue {syscall_ptr : felt*, pedersen_ptr : HashBuiltin*, range_check_ptr} ( 67 | idx : felt 68 | ) -> ( 69 | event : Event 70 | ): 71 | ## TODO: assert rd_idx < idx < wr_idx 72 | let (event) = event_queue.read(idx) 73 | return (event) 74 | end 75 | 76 | func _pop_event_queue {syscall_ptr : felt*, pedersen_ptr : HashBuiltin*, range_check_ptr} () -> ( 77 | event : Event 78 | ): 79 | let (rd_idx) = event_queue_read_head.read() 80 | let (event) = event_queue.read(rd_idx) 81 | event_queue_read_head.write(rd_idx+1) 82 | 83 | return (event) 84 | end 85 | 86 | 87 | #################################### 88 | ########### Gate Queue ############ 89 | #################################### 90 | 91 | struct Gate: 92 | member gate_idx : felt 93 | member gate_typ : felt 94 | end 95 | 96 | @storage_var 97 | func gate_queue ( 98 | idx : felt 99 | ) -> ( 100 | gate : Gate 101 | ): 102 | end 103 | 104 | @storage_var 105 | func gate_queue_read_head () -> ( 106 | rd_idx : felt 107 | ): 108 | end 109 | 110 | @storage_var 111 | func gate_queue_write_head () -> ( 112 | wr_idx : felt 113 | ): 114 | end 115 | 116 | @view 117 | func admin_get_gate_queue_read_head {syscall_ptr : felt*, pedersen_ptr : HashBuiltin*, range_check_ptr} () -> ( 118 | rd_idx : felt 119 | ): 120 | return gate_queue_read_head.read() 121 | end 122 | 123 | @view 124 | func admin_get_gate_queue_write_head {syscall_ptr : felt*, pedersen_ptr : HashBuiltin*, range_check_ptr} () -> ( 125 | wr_idx : felt 126 | ): 127 | return gate_queue_write_head.read() 128 | end 129 | 130 | func _write_gate_queue {syscall_ptr : felt*, pedersen_ptr : HashBuiltin*, range_check_ptr} ( 131 | gate : Gate 132 | ) -> (): 133 | let (wr_idx) = gate_queue_write_head.read() 134 | gate_queue.write(wr_idx, gate) 135 | gate_queue_write_head.write(wr_idx+1) 136 | return () 137 | end 138 | 139 | @view 140 | func admin_read_gate_queue {syscall_ptr : felt*, pedersen_ptr : HashBuiltin*, range_check_ptr} ( 141 | idx : felt 142 | ) -> ( 143 | gate : Gate 144 | ): 145 | ## TODO: assert rd_idx < idx < wr_idx 146 | let (gate) = gate_queue.read(idx) 147 | return (gate) 148 | end 149 | 150 | func _pop_gate_queue {syscall_ptr : felt*, pedersen_ptr : HashBuiltin*, range_check_ptr} () -> ( 151 | gate : Gate 152 | ): 153 | let (rd_idx) = gate_queue_read_head.read() 154 | let (gate) = gate_queue.read(rd_idx) 155 | gate_queue_read_head.write(rd_idx+1) 156 | 157 | return (gate) 158 | end 159 | 160 | #################################### 161 | ######### Gate Evaluation ########## 162 | #################################### 163 | 164 | ## evaluate gate output from input and gate-type 165 | func _gate_evaluation {syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, range_check_ptr, bitwise_ptr : BitwiseBuiltin*} ( 166 | gate_typ : felt, 167 | vi_1 : felt, 168 | vi_2 : felt 169 | ) -> ( 170 | vo : felt 171 | ): 172 | alloc_locals 173 | 174 | let (local result_and, local result_xor, local result_or) = bitwise_operations(vi_1, vi_2) 175 | let (local result_nand) = _invert(result_and) 176 | let (local result_not) = _invert(vi_1) 177 | let (local is_or) = _is_zero(gate_typ - 0) 178 | let (local is_and) = _is_zero(gate_typ - 1) 179 | let (local is_xor) = _is_zero(gate_typ - 2) 180 | let (local is_nand) = _is_zero(gate_typ - 3) 181 | let (local is_not) = _is_zero(gate_typ - 4) 182 | tempvar vo = result_or * is_or + result_and * is_and + result_xor * is_xor + result_nand * is_nand + result_not * is_not 183 | 184 | return (vo) 185 | end 186 | 187 | #################################### 188 | ##### gates contract interface ##### 189 | #################################### 190 | 191 | # The interface for the other function is defined. 192 | @contract_interface 193 | namespace IContractGates: 194 | func gate_count () -> (gate_count : felt): 195 | end 196 | 197 | func init_net_values () -> (arr_len : felt, arr : felt*): 198 | end 199 | 200 | func input_net_count () -> (input_net_count : felt): 201 | end 202 | 203 | func output_net_count () -> (output_net_count : felt): 204 | end 205 | 206 | func fanout_gate_given_net (net_idx : felt) -> (gate_idx_arr_len : felt, gate_idx_arr : felt*): 207 | end 208 | 209 | func gate_idx_to_typ (gate_idx : felt) -> (gate_typ : felt): 210 | end 211 | 212 | func gate_ports_lookup (gate_idx : felt) -> (vo_net_idx : felt, vi_1_net_idx : felt, vi_2_net_idx : felt): 213 | end 214 | end 215 | 216 | #################################### 217 | ############ Simulator ############# 218 | #################################### 219 | 220 | @storage_var 221 | func net_table ( 222 | net_idx : felt 223 | ) -> ( 224 | net_val : felt 225 | ): 226 | end 227 | 228 | @storage_var 229 | func gate_dict ( 230 | gate_idx : felt 231 | ) -> ( 232 | exist_in_gatequeue : felt 233 | ): 234 | end 235 | 236 | @view 237 | func admin_view_net_table {syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, range_check_ptr} ( 238 | net_idx : felt 239 | ) -> ( 240 | net_val : felt 241 | ): 242 | let (net_val) = net_table.read(net_idx) 243 | return (net_val) 244 | end 245 | 246 | ## TODO: could add a queue for submission-addresses, decoupling submission from simulation 247 | @external 248 | func submit_gates_for_simulation {syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, range_check_ptr, bitwise_ptr : BitwiseBuiltin*} ( 249 | gates_address : felt 250 | ) -> (): 251 | alloc_locals 252 | 253 | # initialize net table -- for now use submissions's init_net_values() 254 | let (local net_count : felt, local net_init_values : felt*) = IContractGates.init_net_values(gates_address) 255 | let (local input_net_count : felt) = IContractGates.input_net_count(gates_address) 256 | let (local output_net_count : felt) = IContractGates.output_net_count(gates_address) 257 | _recurse_populate_net_table(net_count, net_init_values, 0) 258 | 259 | # create random stimuli and expected output -- for now use a single constant stimulus - all one's 260 | let (local input_stimuli) = alloc() 261 | _recurse_populate_random(input_net_count, input_stimuli, 0) # populate the array input_stimuli, from 0 to input_net_count 262 | 263 | # for each in Stimuli (skipped for now) 264 | # initialize EQ with stimulus 265 | _recurse_init_event_queue(input_net_count, input_stimuli, 0) 266 | 267 | return () 268 | end 269 | 270 | @external 271 | func run_simulation {syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, range_check_ptr, bitwise_ptr : BitwiseBuiltin*} ( 272 | gates_address : felt 273 | ) -> (latency_unitless : felt, area : felt): 274 | alloc_locals 275 | 276 | # main loop 277 | let (latency_unitless) = _main_loop(gates_address) 278 | 279 | # area estimation 280 | let (area) = _area_estimation(gates_address) 281 | 282 | return (latency_unitless, area) 283 | end 284 | 285 | #################################### 286 | ##### Functions for recursion ###### 287 | #################################### 288 | 289 | func _recurse_populate_net_table {syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, range_check_ptr} ( 290 | len : felt, arr : felt*, idx : felt) -> (): 291 | alloc_locals 292 | 293 | if idx == len: 294 | return () 295 | end 296 | 297 | net_table.write(idx, [arr+idx]) 298 | _recurse_populate_net_table (len, arr, idx+1) 299 | return () 300 | end 301 | 302 | func _recurse_populate_random {syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, range_check_ptr, bitwise_ptr : BitwiseBuiltin*} ( 303 | len : felt, arr : felt*, idx : felt) -> (): 304 | alloc_locals 305 | 306 | if idx == len: 307 | return () 308 | end 309 | 310 | let (random_bit) = _get_1b_pseudorandom() 311 | assert [arr+idx] = random_bit 312 | _recurse_populate_random (len, arr, idx+1) 313 | return () 314 | end 315 | 316 | func _recurse_init_event_queue {syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, range_check_ptr} ( 317 | len : felt, arr : felt*, idx) -> (): 318 | alloc_locals 319 | 320 | if idx == len: 321 | return () 322 | end 323 | 324 | local new_val = [arr+idx] 325 | 326 | local syscall_ptr : felt* = syscall_ptr 327 | let (old_val) = net_table.read(idx) 328 | 329 | if new_val != old_val: 330 | _write_event_queue( Event(net_idx=idx, new_val=new_val) ) 331 | tempvar syscall_ptr = syscall_ptr 332 | tempvar pedersen_ptr = pedersen_ptr 333 | tempvar range_check_ptr = range_check_ptr 334 | else: 335 | tempvar syscall_ptr = syscall_ptr 336 | tempvar pedersen_ptr = pedersen_ptr 337 | tempvar range_check_ptr = range_check_ptr 338 | end 339 | 340 | _recurse_init_event_queue (len, arr, idx+1) 341 | return () 342 | end 343 | 344 | func _main_loop {syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, range_check_ptr, bitwise_ptr : BitwiseBuiltin*} ( 345 | gates_address : felt 346 | ) -> (latency_unitless : felt): 347 | alloc_locals 348 | 349 | ## clear GateDict 350 | let (local gate_count) = IContractGates.gate_count(gates_address) 351 | _recurse_clear_gate_dict(gate_count, 0) 352 | 353 | ## Event Loop (populate GateLoop) 354 | _recurse_event_loop(gates_address) 355 | 356 | ## Check GateQueue size 357 | let (gq_rd_head) = gate_queue_read_head.read() 358 | let (gq_wr_head) = gate_queue_write_head.read() 359 | tempvar gq_size = gq_wr_head - gq_rd_head 360 | let (local bool_gq_is_not_empty) = is_not_zero(gq_size) 361 | 362 | ## Gate Loop (run if GateQueue is not empty) 363 | _recurse_gate_loop(gates_address) 364 | 365 | ## Check if EventQueue is empty 366 | let (eq_rd_head) = event_queue_read_head.read() 367 | let (eq_wr_head) = event_queue_write_head.read() 368 | tempvar eq_size = eq_wr_head - eq_rd_head 369 | if eq_size == 0: 370 | return (bool_gq_is_not_empty) ## this assume the submission has at least one gate. TODO handle exceptions 371 | end 372 | 373 | let (rest_of_latency) = _main_loop(gates_address) 374 | return (bool_gq_is_not_empty + rest_of_latency) ## this assume the submission has at least one gate. TODO handle exceptions 375 | end 376 | 377 | func _recurse_clear_gate_dict {syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, range_check_ptr} ( 378 | len : felt, idx : felt) -> (): 379 | alloc_locals 380 | 381 | if idx == len: 382 | return () 383 | end 384 | 385 | gate_dict.write(idx, 0) 386 | _recurse_clear_gate_dict (len, idx+1) 387 | return () 388 | end 389 | 390 | func _recurse_event_loop {syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, range_check_ptr} (gates_address : felt) -> (): 391 | 392 | alloc_locals 393 | 394 | let (eq_rd_head) = event_queue_read_head.read() 395 | let (eq_wr_head) = event_queue_write_head.read() 396 | tempvar eq_size = eq_wr_head - eq_rd_head 397 | if eq_size == 0: 398 | return () 399 | end 400 | 401 | ## Pop EventQueue 402 | let (local event : Event) = _pop_event_queue() 403 | 404 | ## Update NetTable with event 405 | net_table.write(event.net_idx, event.new_val) 406 | 407 | ## Find all fanout gates of event's net using submitted contract's fanout_gate_given_net() 408 | let ( 409 | gate_idx_arr_len : felt, gate_idx_arr : felt* 410 | ) = IContractGates.fanout_gate_given_net(gates_address, event.net_idx) 411 | 412 | ## loop over gate_idx_arr, convert each gate_idx to gate_typ using submitted contract's gate_idx_to_typ() 413 | _recurse_update_gate_queue (gates_address, gate_idx_arr_len, gate_idx_arr, 0) 414 | 415 | ## recurse 416 | _recurse_event_loop(gates_address) 417 | return () 418 | end 419 | 420 | func _recurse_update_gate_queue {syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, range_check_ptr} ( 421 | gates_address : felt, len : felt, arr : felt*, idx) -> (): 422 | alloc_locals 423 | 424 | if idx == len: 425 | return () 426 | end 427 | 428 | local gate_idx = [arr+idx] 429 | 430 | local syscall_ptr : felt* = syscall_ptr 431 | let (exist_in_gate_queue) = gate_dict.read(gate_idx) 432 | 433 | if exist_in_gate_queue == 0: 434 | let (gate_typ) = IContractGates.gate_idx_to_typ(gates_address, gate_idx) 435 | _write_gate_queue( Gate(gate_idx=gate_idx, gate_typ=gate_typ) ) 436 | tempvar syscall_ptr = syscall_ptr 437 | tempvar pedersen_ptr = pedersen_ptr 438 | tempvar range_check_ptr = range_check_ptr 439 | else: 440 | tempvar syscall_ptr = syscall_ptr 441 | tempvar pedersen_ptr = pedersen_ptr 442 | tempvar range_check_ptr = range_check_ptr 443 | end 444 | 445 | _recurse_update_gate_queue (gates_address, len, arr, idx+1) 446 | return () 447 | end 448 | 449 | func _recurse_gate_loop {syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, range_check_ptr, bitwise_ptr : BitwiseBuiltin*} ( 450 | gates_address : felt 451 | ) -> (): 452 | 453 | alloc_locals 454 | 455 | ################ 456 | ## Pseudocode ## 457 | ################ 458 | ## for G in GQ: 459 | ## vo = NT.read(G's output net_idx) 460 | ## vi = NT.read(G's input net_idx) 461 | ## vo_ = G's function (vi) 462 | ## if vo != vo_: 463 | ## EQ.write(G's output net_idx, vo_) 464 | 465 | let (gq_rd_head) = gate_queue_read_head.read() 466 | let (gq_wr_head) = gate_queue_write_head.read() 467 | tempvar gq_size = gq_wr_head - gq_rd_head 468 | if gq_size == 0: 469 | return () 470 | end 471 | 472 | ## Pop GQ 473 | let (local gate : Gate) = _pop_gate_queue() 474 | 475 | ## Retrieve gate's in/out net indices from submitted contract using gate_ports_lookup() 476 | let (vo_net_idx, vi_1_net_idx, vi_2_net_idx) = IContractGates.gate_ports_lookup(gates_address, gate.gate_idx) 477 | 478 | ## Get the before-value of gate's output 479 | let (local vo) = net_table.read(vo_net_idx) 480 | 481 | ## Get the values of gate's input 482 | let (local vi_1) = net_table.read(vi_1_net_idx) 483 | let (local vi_2) = net_table.read(vi_2_net_idx) 484 | 485 | ## Evaluate the after-value of gate's output 486 | let (local vo_) = _gate_evaluation (gate.gate_typ, vi_1, vi_2) 487 | 488 | ## Write to EQ if gate's output changes 489 | tempvar vo_diff = vo - vo_ 490 | if vo_diff != 0: 491 | _write_event_queue( Event(net_idx=vo_net_idx, new_val=vo_) ) 492 | tempvar syscall_ptr = syscall_ptr 493 | tempvar pedersen_ptr = pedersen_ptr 494 | tempvar range_check_ptr = range_check_ptr 495 | else: 496 | tempvar syscall_ptr = syscall_ptr 497 | tempvar pedersen_ptr = pedersen_ptr 498 | tempvar range_check_ptr = range_check_ptr 499 | end 500 | 501 | ## Recurse 502 | _recurse_gate_loop (gates_address) 503 | return () 504 | end 505 | 506 | func _area_estimation {syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, range_check_ptr, bitwise_ptr : BitwiseBuiltin*} ( 507 | gates_address : felt 508 | ) -> (area : felt): 509 | alloc_locals 510 | 511 | let (local gate_count) = IContractGates.gate_count(gates_address) 512 | let (area) = _recurse_estimate_area(gates_address, gate_count, 0) 513 | 514 | return (area) 515 | end 516 | 517 | func _recurse_estimate_area {syscall_ptr: felt*, pedersen_ptr: HashBuiltin*, range_check_ptr} ( 518 | gates_address : felt, len : felt, idx : felt) -> (total_area : felt): 519 | alloc_locals 520 | 521 | if idx == len: 522 | return (0) 523 | end 524 | 525 | let (gate_typ) = IContractGates.gate_idx_to_typ(gates_address, idx) 526 | 527 | let (local is_or) = _is_zero(gate_typ - 0) 528 | let (local is_and) = _is_zero(gate_typ - 1) 529 | let (local is_xor) = _is_zero(gate_typ - 2) 530 | let (local is_nand) = _is_zero(gate_typ - 3) 531 | let (local is_not) = _is_zero(gate_typ - 4) 532 | local area = is_or * 2 + is_and * 2 + is_xor * 2 + is_nand * 2 + is_not * 1 533 | 534 | let (rest_area) = _recurse_estimate_area (gates_address, len, idx+1) 535 | tempvar total_area = area + rest_area 536 | 537 | return (total_area) 538 | end 539 | 540 | ################# 541 | 542 | # Utiliy function that inverts input 0<->1 543 | func _invert {range_check_ptr} (value) -> (res): 544 | if value == 0: 545 | return (res=1) 546 | else: 547 | return (res=0) 548 | end 549 | end 550 | 551 | # Utility function that wraps and inverts is_not_zero() 552 | func _is_zero {range_check_ptr} (value) -> (res): 553 | let (temp) = is_not_zero(value) 554 | let (temp_inv) = _invert(temp) 555 | return (res = temp_inv) 556 | end 557 | 558 | # Utility functions for pseudorandom number generation 559 | 560 | @storage_var 561 | func entropy_seed( 562 | ) -> ( 563 | value : felt 564 | ): 565 | end 566 | 567 | @external 568 | func admin_initialize_seed{ 569 | syscall_ptr : felt*, 570 | pedersen_ptr : HashBuiltin*, 571 | range_check_ptr 572 | }(seed : felt) -> (): 573 | 574 | entropy_seed.write(seed) 575 | 576 | return () 577 | end 578 | 579 | ## PRBS-7; ref: https://en.wikipedia.org/wiki/Pseudorandom_binary_sequence 580 | func _get_1b_pseudorandom{ 581 | syscall_ptr : felt*, 582 | pedersen_ptr : HashBuiltin*, 583 | range_check_ptr, 584 | bitwise_ptr : BitwiseBuiltin* 585 | }() -> (num : felt): 586 | alloc_locals 587 | 588 | let (local a) = entropy_seed.read() 589 | 590 | let (local a_rightshift_6, _) = unsigned_div_rem(a, 64) 591 | let (local a_rightshift_5, _) = unsigned_div_rem(a, 32) 592 | local a_leftshirt_1 = a * 2 593 | 594 | ## random bit = ((a >> 6) ^ (a >> 5)) & 1 595 | let (newbit_) = bitwise_xor(a_rightshift_6, a_rightshift_5) 596 | let (local newbit) = bitwise_and(newbit_, 1) 597 | 598 | ## next a = ((a << 1) | newbit) & 0x7f 599 | let (a_next_) = bitwise_or(a_leftshirt_1, newbit) 600 | let (a_next) = bitwise_and(a_next_, 127) 601 | entropy_seed.write(a_next) 602 | 603 | return (newbit) 604 | end 605 | --------------------------------------------------------------------------------