├── .github ├── NIGHTLY_CANARY_DIED.md └── workflows │ ├── nightly-canary.yml │ ├── pull-request-title.yml │ ├── release.yml │ └── test.yml ├── .gitignore ├── .release-please-manifest.json ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE ├── Nargo.toml ├── README.md ├── release-please-config.json └── src ├── lib.nr └── utils.nr /.github/NIGHTLY_CANARY_DIED.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Tests fail on latest Nargo nightly release" 3 | assignees: TomAFrench 4 | --- 5 | 6 | The tests on this Noir project have started failing when using the latest nightly release of the Noir compiler. This likely means that there have been breaking changes for which this project needs to be updated to take into account. 7 | 8 | Check the [{{env.WORKFLOW_NAME}}]({{env.WORKFLOW_URL}}) workflow for details. -------------------------------------------------------------------------------- /.github/workflows/nightly-canary.yml: -------------------------------------------------------------------------------- 1 | name: Noir Nightly Canary 2 | 3 | on: 4 | schedule: 5 | # Run a check at 9 AM UTC 6 | - cron: "0 9 * * *" 7 | 8 | env: 9 | CARGO_TERM_COLOR: always 10 | 11 | permissions: 12 | issues: write 13 | 14 | jobs: 15 | test: 16 | name: Test on Nargo ${{matrix.toolchain}} 17 | runs-on: ubuntu-latest 18 | steps: 19 | - name: Checkout sources 20 | uses: actions/checkout@v4 21 | 22 | - name: Install Nargo 23 | uses: noir-lang/noirup@v0.1.3 24 | with: 25 | toolchain: nightly 26 | 27 | - name: Run Noir tests 28 | run: nargo test 29 | 30 | - name: Alert on dead canary 31 | uses: JasonEtco/create-an-issue@v2 32 | if: ${{ failure() }} 33 | env: 34 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 35 | WORKFLOW_NAME: ${{ github.workflow }} 36 | WORKFLOW_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} 37 | with: 38 | update_existing: true 39 | filename: .github/NIGHTLY_CANARY_DIED.md 40 | -------------------------------------------------------------------------------- /.github/workflows/pull-request-title.yml: -------------------------------------------------------------------------------- 1 | name: Pull Request 2 | 3 | on: 4 | merge_group: 5 | pull_request_target: 6 | types: 7 | - opened 8 | - reopened 9 | - edited 10 | - synchronize 11 | 12 | permissions: 13 | pull-requests: read 14 | 15 | jobs: 16 | conventional-title: 17 | name: Validate PR title is Conventional Commit 18 | runs-on: ubuntu-latest 19 | steps: 20 | - name: Check title 21 | if: github.event_name == 'pull_request_target' 22 | uses: amannn/action-semantic-pull-request@v5 23 | env: 24 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 25 | with: 26 | types: | 27 | fix 28 | feat 29 | chore 30 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Release 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | jobs: 9 | release-please: 10 | name: Create Release 11 | outputs: 12 | release-pr: ${{ steps.release.outputs.pr }} 13 | tag-name: ${{ steps.release.outputs.tag_name }} 14 | runs-on: ubuntu-latest 15 | steps: 16 | - name: Run release-please 17 | id: release 18 | uses: google-github-actions/release-please-action@v3 19 | with: 20 | token: ${{ secrets.GITHUB_TOKEN }} 21 | command: manifest 22 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Noir tests 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | pull_request: 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | MINIMUM_NOIR_VERSION: v0.36.0 12 | 13 | jobs: 14 | noir-version-list: 15 | name: Query supported Noir versions 16 | runs-on: ubuntu-latest 17 | outputs: 18 | noir_versions: ${{ steps.get_versions.outputs.versions }} 19 | 20 | steps: 21 | - name: Get supported Noir versions 22 | id: get_versions 23 | run: | 24 | # gh returns the Noir releases in reverse chronological order so we keep all releases published after the minimum supported version. 25 | VERSIONS=$(gh release list -R noir-lang/noir --exclude-pre-releases --json tagName -q 'map(.tagName) | index(env.MINIMUM_NOIR_VERSION) as $index | if $index then .[0:$index+1] else [env.MINIMUM_NOIR_VERSION] end') 26 | echo "versions=$VERSIONS" 27 | echo "versions=$VERSIONS" >> $GITHUB_OUTPUT 28 | env: 29 | GH_TOKEN: ${{ github.token }} 30 | 31 | test: 32 | needs: [noir-version-list] 33 | name: Test on Nargo ${{matrix.toolchain}} 34 | runs-on: ubuntu-latest 35 | strategy: 36 | fail-fast: false 37 | matrix: 38 | toolchain: ${{ fromJson( needs.noir-version-list.outputs.noir_versions )}} 39 | include: 40 | - toolchain: nightly 41 | steps: 42 | - name: Checkout sources 43 | uses: actions/checkout@v4 44 | 45 | - name: Install Nargo 46 | uses: noir-lang/noirup@v0.1.3 47 | with: 48 | toolchain: ${{ matrix.toolchain }} 49 | 50 | - name: Run Noir tests 51 | run: nargo test 52 | 53 | format: 54 | runs-on: ubuntu-latest 55 | steps: 56 | - name: Checkout sources 57 | uses: actions/checkout@v4 58 | 59 | - name: Install Nargo 60 | uses: noir-lang/noirup@v0.1.3 61 | with: 62 | toolchain: ${{ env.MINIMUM_NOIR_VERSION }} 63 | 64 | - name: Run formatter 65 | run: nargo fmt --check 66 | 67 | # This is a job which depends on all test jobs and reports the overall status. 68 | # This allows us to add/remove test jobs without having to update the required workflows. 69 | tests-end: 70 | name: Noir End 71 | runs-on: ubuntu-latest 72 | # We want this job to always run (even if the dependant jobs fail) as we want this job to fail rather than skipping. 73 | if: ${{ always() }} 74 | needs: 75 | - test 76 | - format 77 | 78 | steps: 79 | - name: Report overall success 80 | run: | 81 | if [[ $FAIL == true ]]; then 82 | exit 1 83 | else 84 | exit 0 85 | fi 86 | env: 87 | # We treat any cancelled, skipped or failing jobs as a failure for the workflow as a whole. 88 | FAIL: ${{ contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') || contains(needs.*.result, 'skipped') }} 89 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | **/.DS_Store 3 | .vscode 4 | -------------------------------------------------------------------------------- /.release-please-manifest.json: -------------------------------------------------------------------------------- 1 | {".":"0.3.2"} 2 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## [0.3.2](https://github.com/noir-lang/noir_string_search/compare/v0.3.1...v0.3.2) (2025-03-03) 4 | 5 | 6 | ### Features 7 | 8 | * Added `BoundedVec` type conversion ([#14](https://github.com/noir-lang/noir_string_search/issues/14)) ([0758014](https://github.com/noir-lang/noir_string_search/commit/0758014e7dedf29da9feb0af391f2cd981bc24b0)) 9 | 10 | 11 | ### Bug Fixes 12 | 13 | * Add pub keyword for public methods ([#25](https://github.com/noir-lang/noir_string_search/issues/25)) ([c0a0fc9](https://github.com/noir-lang/noir_string_search/commit/c0a0fc985bc1ea0b37ea2c9cd1e9eb0a041d207a)) 14 | 15 | ## [0.3.1](https://github.com/noir-lang/noir_string_search/compare/v0.3.0...v0.3.1) (2025-02-25) 16 | 17 | 18 | ### Bug Fixes 19 | 20 | * Fixed the out of range index bug ([#21](https://github.com/noir-lang/noir_string_search/issues/21)) ([2e25be4](https://github.com/noir-lang/noir_string_search/commit/2e25be4636ab2111d98d08338fb02ea6f866ca6a)) 21 | 22 | ## [0.3.0](https://github.com/noir-lang/noir_string_search/compare/v0.2.0...v0.3.0) (2024-12-04) 23 | 24 | 25 | ### ⚠ BREAKING CHANGES 26 | 27 | * update to Noir 0.36.0 ([#10](https://github.com/noir-lang/noir_string_search/issues/10)) 28 | 29 | ### Features 30 | 31 | * Update to Noir 0.36.0 ([#10](https://github.com/noir-lang/noir_string_search/issues/10)) ([2fbf54f](https://github.com/noir-lang/noir_string_search/commit/2fbf54f093698e138ba51273ff449290e41e4451)) 32 | 33 | ## [0.2.0](https://github.com/noir-lang/noir_string_search/compare/v0.1.0...v0.2.0) (2024-10-04) 34 | 35 | 36 | ### ⚠ BREAKING CHANGES 37 | 38 | * bump minimum noir version to 0.34.0 39 | 40 | ### Features 41 | 42 | * Bump minimum noir version to 0.34.0 ([a0a7b98](https://github.com/noir-lang/noir_string_search/commit/a0a7b9818657da7d447dec43b625c6d2748934ea)) 43 | 44 | 45 | ### Bug Fixes 46 | 47 | * Remove prints ([c2c03c4](https://github.com/noir-lang/noir_string_search/commit/c2c03c45004b3eaa931f0cb007cd92023d3f745a)) 48 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | Thank you for your interest in contributing! We value your contributions. 🙏 4 | 5 | This guide will discuss how the team handles [Commits](#commits), [Pull Requests](#pull-requests), [Releases](#releases), the [Changelog](#changelog), and [Response time](#response-time). 6 | 7 | **Note:** We won't force external contributors to follow this verbatim, but following these guidelines definitely helps us in accepting your contributions. 8 | 9 | ## Commits 10 | 11 | We want to keep our commits small and focused. This allows for easily reviewing individual commits and/or splitting up pull requests when they grow too big. Additionally, this allows us to merge smaller changes quicker. 12 | 13 | When committing, it's often useful to use the `git add -p` workflow to decide on what parts of the changeset to stage for commit. 14 | 15 | ## Pull Requests 16 | 17 | Before you create a pull request, search for any issues related to the change you are making. If none exist already, create an issue that thoroughly describes the problem that you are trying to solve. These are used to inform reviewers of the original intent and should be referenced via the pull request template. 18 | 19 | Pull Requests should be focused on the specific change they are working towards. If prerequisite work is required to complete the original pull request, that work should be submitted as a separate pull request. 20 | 21 | This strategy avoids scenarios where pull requests grow too large/out-of-scope and don't get proper reviews—we want to avoid "LGTM, I trust you" reviews. 22 | 23 | ### Conventional Commits 24 | 25 | We use [Conventional Commits](https://www.conventionalcommits.org/en/v1.0.0/) naming conventions for PRs, which help with releases and changelogs. Please use the following format for PR titles: 26 | 27 | ``` 28 | [optional scope]: 29 | ``` 30 | 31 | Generally, we want to only use the three primary types defined by the specification: 32 | 33 | - `feat:` - This should be the most used type, as most work we are doing in the project are new features. Commits using this type will always show up in the Changelog. 34 | - `fix:` - When fixing a bug, we should use this type. Commits using this type will always show up in the Changelog. 35 | - `chore:` - The least used type, these are not included in the Changelog unless they are breaking changes. But remain useful for an understandable commit history. 36 | 37 | #### Breaking Changes 38 | 39 | Annotating BREAKING CHANGES is extremely important to our release process and versioning. To mark a commit as breaking, we add the ! character after the type, but before the colon. For example: 40 | 41 | ``` 42 | feat!: Rename nargo build to nargo check (#693) 43 | ``` 44 | 45 | ``` 46 | feat(nargo)!: Enforce minimum rustc version 47 | ``` 48 | 49 | #### Scopes 50 | 51 | Scopes significantly improve the Changelog, so we want to use a scope whenever possible. If we are only changing one part of the project, we can use the name of the crate, like (nargo) or (noirc_driver). If a change touches multiple parts of the codebase, there might be a better scope, such as using (syntax) for new language features. 52 | 53 | ``` 54 | feat(nargo): Add support for wasm backend (#234) 55 | ``` 56 | 57 | ``` 58 | feat(syntax): Implement String data type (#123) 59 | ``` 60 | 61 | ### Typos and other small changes 62 | 63 | Significant changes, like new features or important bug fixes, typically have a more pronounced impact on the project’s overall development. For smaller fixes, such as typos, we encourage you to report them as Issues instead of opening PRs. This approach helps us manage our resources effectively and ensures that every change contributes meaningfully to the project. PRs involving such smaller fixes will likely be closed and incorporated in PRs authored by the core team. 64 | 65 | ### Reviews 66 | 67 | For any repository in the organization, we require code review & approval by **one** team member before the changes are merged, as enforced by GitHub branch protection. Non-breaking pull requests may be merged at any time. Breaking pull requests should only be merged when the team has general agreement of the changes and is preparing a breaking release. 68 | 69 | ### Documentation 70 | 71 | Breaking changes must be documented, either through adding/updating existing docs or README.md. 72 | 73 | ## Releases 74 | 75 | Releases are managed by [Release Please](https://github.com/googleapis/release-please) which runs in a GitHub Action whenever a commit is made on the master branch. 76 | 77 | Release Please parses Conventional Commit messages and opens (or updates) a pull request against the master branch that contains updates to the versions & Changelog within the project. If it doesn't detect any breaking change commits, it will only increment the "patch" version; however, if it detects a breaking change commit, it will increment the "minor" version number to indicate a breaking release. 78 | 79 | When we are ready to release the version, we approve and squash merge the release pull request into master. Release Please will detect this merge and generate the appropriate tags for the release. Additional release steps may be triggered inside the GitHub Action to automate other parts of the release process. 80 | 81 | There is no strict release cadence, but a new release is usually cut every 1 to 2 months. 82 | 83 | ## Changelog 84 | 85 | The Changelog is automatically managed by Release Please and informed by the Conventional Commits (as discussed above). 86 | 87 | ## Response time 88 | 89 | The team will respond to issues and PRs within 1 week from submission. 90 | -------------------------------------------------------------------------------- /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. -------------------------------------------------------------------------------- /Nargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "noir_string_search" 3 | type = "lib" 4 | authors = [""] 5 | compiler_version = ">=0.36.0" 6 | 7 | [dependencies] 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # noir_string_search 2 | 3 | A noir library that can be used to prove that a given "needle" substring is present within a larger "haystack" string. 4 | 5 | Features: 6 | 7 | - Both the needle and haystack string can have variable runtime lengths (up to a defined maximum) 8 | - Efficient implementation ~2 gates per haystack byte, ~5 gates per needle byte 9 | - Both needle and haystack strings can be dynamically constructed in-circuit if required 10 | 11 | ## Noir version compatibility 12 | 13 | This library is tested with all Noir stable releases from v0.36.0. 14 | 15 | ## Typedefs 16 | 17 | Multiple type definitions represent different hardcoded maximum lengths for the needle/haystack: 18 | 19 | ``` 20 | Haystack types ranging from 32 max bytes to 16,384 max bytes 21 | StringBody32 22 | StringBody64 23 | StringBody128 24 | StringBody256 25 | StringBody512 26 | StringBody1024 27 | StringBody2048 28 | StringBody4096 29 | StringBody8192 30 | StringBody16384 31 | ``` 32 | 33 | ``` 34 | Needle types ranging from 32 bytes to 1,024 max bytes 35 | SubString32 36 | SubString64 37 | SubString128 38 | SubString256 39 | SubString512 40 | SubString1024 41 | ``` 42 | 43 | ## Usage 44 | 45 | ### Basic usage 46 | 47 | ```rust 48 | let haystack_text = "the quick brown fox jumped over the lazy dog".as_bytes(); 49 | let needle_text = " the lazy dog".as_bytes(); 50 | 51 | let haystack: StringBody64 = StringBody::new(haystack_text, haystack_text.len()); 52 | let needle: SubString32 = SubString::new(needle_text, needle_text.len()); 53 | 54 | let (result, match_position): (bool, u32) = haystack.substring_match(needle); 55 | ``` 56 | 57 | ### Dynamic needle construction 58 | 59 | ```rust 60 | fn validate_account(padded_email_text: [u8; 8192], padded_username: [u8; 100], username_length: u32) { 61 | 62 | let needle_text_init = "account recovery for".as_bytes(); 63 | 64 | let needle_start: SubString32 = SubString::new(needle_text_init, needle_text_init.len()); 65 | let needle_end: SubString128 = SubString::new(padded_username, username_length); 66 | // use concat_into because SubString128 > SubString32 67 | let needle = needle_start.concat_into(needle_end); 68 | 69 | let haystack: StringBody8192 = StringBody::new(padded_email_text, 8192); 70 | let (result, match_position): (bool, u32) = haystack.substring_match(needle); 71 | } 72 | ``` 73 | 74 | ### Costs 75 | 76 | Matching a SubString128 with a StringBody1024 costs 6,630 gates (as of noir 0.32.0 and bb 0.46.1) 77 | 78 | Gate breakdown: 79 | 80 | - 2,740 gates: constructing a 14-bit range table 81 | - 1,280 gates: constructing a 1,024 size `u8` array 82 | - 160 gates: constructing a 128 size `u8` array 83 | - 2,444 gates: string matching algorithm 84 | 85 | Some rough measurements: 86 | 87 | | Haystack Bytes | Needle Bytes | Total Cost | Cost minus range table and byte array init costs | 88 | | -------------- | ------------ | ---------- | ------------------------------------------------ | 89 | | 1,024 | 128 | 6,630 | 2,444 | 90 | | 1,024 | 256 | 7,633 | 3,293 | 91 | | 2,048 | 128 | 8,471 | 3,011 | 92 | | 2,048 | 256 | 9,474 | 3,854 | 93 | 94 | Extrapolating from this table for some very rough estimates: costs for `substring_match` (excluding range table and byte array init costs) are ~6.5 gates per needle byte, ~0.5 gates per haystack byte and a ~1,100 gate constant cost. 95 | -------------------------------------------------------------------------------- /release-please-config.json: -------------------------------------------------------------------------------- 1 | { 2 | "release-type": "simple", 3 | "bump-minor-pre-major": true, 4 | "bump-patch-for-minor-pre-major": true, 5 | "pull-request-title-pattern": "chore: Release ${version}", 6 | "group-pull-request-title-pattern": "chore: Release ${version}", 7 | "packages": { 8 | ".": { 9 | "release-type": "simple", 10 | "include-component-in-tag": false 11 | } 12 | }, 13 | "plugins": [ 14 | "sentence-case" 15 | ] 16 | } 17 | -------------------------------------------------------------------------------- /src/lib.nr: -------------------------------------------------------------------------------- 1 | mod utils; 2 | 3 | pub use utils::{conditional_select, DebugRandomEngine}; 4 | use std::collections::bounded_vec::BoundedVec; 5 | 6 | /** 7 | * @brief represents a byte-array of up to MaxBytes, that is used as a "haystack" array, 8 | * where we want to validate a substring "needle" is present in the "haystack" 9 | * @details the "body" parameter contains some input bytes, zero-padded to the nearest multiple of 31 10 | * We pack "bytes" into 31-byte "chunks", as this is the maximum number of bytes we can fit 11 | * into a field element without overflowing. 12 | * TODO: once we can derive generics via arithmetic on other generics, we want this "31" parameter 13 | * to be defined by the backend being used instead of being hardcoded to 31 14 | * 15 | * @note We perform this 31-byte packing because it dramatically reduces the number of constraints required for substring matching. See (chicken) 16 | * 17 | * @tparam MaxBytes: the maximum number of bytes that StringBody can contain 18 | * @tparam MaxPaddedBytes: the maximum number of bytes after zero-padding to the nearest multiple of 31 19 | * @tparam PaddedChunks: the number of 31-byte chunks needed to represent MaxPaddedBytes 20 | **/ 21 | pub struct StringBody { 22 | pub body: [u8; MaxPaddedBytes], 23 | chunks: [Field; PaddedChunks], 24 | pub byte_length: u32, 25 | } 26 | 27 | /** 28 | * @brief represents a byte-array of up to MaxBytes, that is used as a "needle" array, 29 | * where we want to validate a substring "needle" is present in the "haystack" 30 | * @tparam MaxBytes: the maximum number of bytes that StringBody can contain 31 | * @tparam MaxPaddedBytes: the maximum number of bytes after zero-padding to the nearest multiple of 31 32 | * @tparam PaddedChunksMinusOne: the number of 31-byte chunks needed to represent MaxPaddedBytes minus one! 33 | * 34 | * @note PaddedChunksMinusOne is because we are going to do the following: 35 | * 1. align the SubString bytes according to the StringBody bytes being matched against 36 | * 2. split the aligned bytes into 31-byte chunks. The 1st and last chunks might contain 37 | * fewer than 31 bytes due to the above alignment 38 | * 3. validate the aligned-byte-chunks match the StringBody byte chunks 39 | * To account for the fact that the 1st and last chunks might have fewer bytes we treat those separately 40 | * The param PaddedChunksMinusOne is the number of 31-byte chunks required to represent SubString *EXCLUDING* the initial and final chunks 41 | */ 42 | pub struct SubString { 43 | pub body: [u8; MaxPaddedBytes], 44 | pub byte_length: u32, 45 | } 46 | 47 | pub type StringBody32 = StringBody<62, 2, 32>; 48 | pub type StringBody64 = StringBody<93, 3, 64>; 49 | pub type StringBody128 = StringBody<155, 5, 128>; 50 | pub type StringBody256 = StringBody<279, 9, 256>; 51 | pub type StringBody512 = StringBody<527, 17, 512>; 52 | pub type StringBody1024 = StringBody<1054, 34, 1024>; 53 | pub type StringBody2048 = StringBody<2077, 67, 2048>; 54 | pub type StringBody4096 = StringBody<4123, 133, 4096>; 55 | pub type StringBody8192 = StringBody<8215, 265, 8192>; 56 | pub type StringBody16384 = StringBody<16399, 529, 16384>; 57 | 58 | pub type SubString32 = SubString<62, 1, 32>; 59 | pub type SubString64 = SubString<93, 2, 64>; 60 | pub type SubString128 = SubString<155, 4, 128>; 61 | pub type SubString256 = SubString<279, 8, 256>; 62 | pub type SubString512 = SubString<527, 16, 512>; 63 | pub type SubString1024 = SubString<1054, 33, 1024>; 64 | 65 | pub trait SubStringTrait { 66 | fn match_chunks( 67 | self, 68 | haystack: [Field; HaystackChunks], 69 | num_bytes_in_first_chunk: u32, 70 | body_chunk_offset: u32, 71 | num_full_chunks: u32, 72 | ); 73 | 74 | fn len(self) -> u32; 75 | fn get(self, idx: u32) -> u8; 76 | fn get_body(self) -> [u8]; 77 | } 78 | 79 | // ###################################################### 80 | // S U B S T R I N G 81 | // ###################################################### 82 | impl SubString { 83 | 84 | /** 85 | * @brief construct a SubString object from an input byte array 86 | * @details the input byte array must have a number of bytes less than or equal to MaxBytes 87 | **/ 88 | pub fn new(input: [u8; InputBytes], input_length: u32) -> Self { 89 | assert(MaxBytes <= MaxPaddedBytes); 90 | assert(input_length <= MaxBytes); 91 | assert(InputBytes <= MaxBytes); 92 | let mut body: [u8; MaxPaddedBytes] = [0; MaxPaddedBytes]; 93 | for i in 0..InputBytes { 94 | body[i] = input[i]; 95 | } 96 | SubString { body, byte_length: input_length } 97 | } 98 | 99 | /** 100 | * @brief concatenate two SubString objects together 101 | * @details each SubString can have different MaxBytes sizes, however we need OtherBytes <= MaxBytes 102 | * (use concat_into for cases where this is not the case) 103 | **/ 104 | pub fn concat( 105 | self, 106 | other: SubString, 107 | ) -> Self { 108 | assert( 109 | OtherPaddedBytes <= MaxPaddedBytes, 110 | "SubString::concat. SubString being concatted has larger max length. Try calling concat_into", 111 | ); 112 | assert( 113 | self.byte_length + other.byte_length <= MaxPaddedBytes, 114 | "SubString::concat, concatenated string exceeds MaxPaddedBytes", 115 | ); 116 | let mut body = self.body; 117 | let offset: u32 = self.byte_length; 118 | for i in 0..MaxPaddedBytes { 119 | if (i + offset < MaxPaddedBytes) { 120 | body[i + offset] = other.body[i]; 121 | } 122 | } 123 | SubString { body, byte_length: self.byte_length + other.byte_length } 124 | } 125 | 126 | /** 127 | * @brief concatenate two SubString objects together. Return type has OtherPaddedBytes max bytes 128 | * @details each SubString can have different MaxBytes sizes, however we need MaxBytes <= OtherBytes 129 | * (use concat for cases where this is not the case) 130 | **/ 131 | pub fn concat_into( 132 | self, 133 | other: SubString, 134 | ) -> SubString { 135 | assert( 136 | MaxPaddedBytes <= OtherPaddedBytes, 137 | "SubString::concat_into. SubString being concat has larger max length. Try calling concat", 138 | ); 139 | assert( 140 | self.byte_length + other.byte_length <= OtherPaddedBytes, 141 | "SubString::concat_into, concatenated string exceeds MaxPaddedBytes", 142 | ); 143 | let mut body: [u8; OtherPaddedBytes] = [0; OtherPaddedBytes]; 144 | for i in 0..MaxBytes { 145 | body[i] = self.body[i]; 146 | } 147 | 148 | let offset: u32 = self.byte_length; 149 | for i in 0..OtherPaddedBytes { 150 | if (i + offset < OtherPaddedBytes) { 151 | body[i + offset] = other.body[i]; 152 | } 153 | } 154 | SubString { body, byte_length: self.byte_length + other.byte_length } 155 | } 156 | } 157 | 158 | impl SubStringTrait for SubString { 159 | 160 | fn len(self) -> u32 { 161 | self.byte_length 162 | } 163 | fn get(self, idx: u32) -> u8 { 164 | self.body[idx] 165 | } 166 | fn get_body(self) -> [u8] { 167 | let x = self.body.as_slice(); 168 | x 169 | } 170 | 171 | /** 172 | * @brief given some `haystack` 31-byte chunks, validate that there exist `num_full_chunks` 173 | * in the SubString, starting at byte position `starting_needle_byte`. 174 | * The selected chunks must be equal to the haystack chunks starting at `starting_haystack_chunk` 175 | **/ 176 | fn match_chunks( 177 | self, 178 | haystack: [Field; HaystackChunks], 179 | starting_needle_byte: u32, 180 | starting_haystack_chunk: u32, 181 | num_full_chunks: u32, 182 | ) { 183 | let mut substring_chunks: [Field; PaddedChunksMinusOne] = [0; PaddedChunksMinusOne]; 184 | // pack the substring into 31 byte chunks. 185 | // This is fairly expensive as we need a ROM table to access the SubString.body 186 | // which is 2 gates per byte 187 | for i in 0..PaddedChunksMinusOne { 188 | let mut slice: Field = 0; 189 | for j in 0..31 { 190 | slice *= 256; 191 | let substring_idx = starting_needle_byte + (i * 31) + j; 192 | let mut byte = self.body[substring_idx]; 193 | slice += byte as Field; 194 | } 195 | std::as_witness(slice); 196 | substring_chunks[i] = slice; 197 | } 198 | // iterate over the needle chunks and validate they match the haystack chunks 199 | for i in 0..PaddedChunksMinusOne { 200 | let predicate = i < num_full_chunks; 201 | let lhs = substring_chunks[i]; 202 | let rhs = haystack[predicate as u32 * (i + starting_haystack_chunk)]; 203 | assert(predicate as Field * (lhs - rhs) == 0); 204 | } 205 | } 206 | } 207 | 208 | impl From> for SubString { 209 | fn from(input: BoundedVec) -> Self { 210 | Self::new(input.storage(), input.len() as u32) 211 | } 212 | } 213 | 214 | // ###################################################### 215 | // S T R I N G B O D Y 216 | // ###################################################### 217 | impl StringBody { 218 | 219 | /** 220 | * @brief construct a StringBody object from an input byte array 221 | * @details the input byte array must have a number of bytes less than or equal to MaxBytes 222 | **/ 223 | pub fn new(data: [u8; InputBytes], length: u32) -> Self { 224 | assert(length <= MaxBytes); 225 | assert(length <= InputBytes); 226 | let mut body: [u8; MaxPaddedBytes] = [0; MaxPaddedBytes]; 227 | for i in 0..InputBytes { 228 | body[i] = data[i]; 229 | } 230 | StringBody { body, chunks: compute_chunks(body), byte_length: length } 231 | } 232 | 233 | /** 234 | * @brief Validate a substring exists in the StringBody. Returns a success flag and the position within the StringBody that the match was found 235 | **/ 236 | pub fn substring_match(self, substring: NeedleSubString) -> (bool, u32) 237 | where 238 | NeedleSubString: SubStringTrait, 239 | { 240 | // use unconstrained function to determine: 241 | // a: is the substring present in the body text 242 | // b: the position of the first match in the body text 243 | let position: u32 = unsafe { 244 | // Safety: The rest of this function checks this. 245 | utils::search( 246 | self.body, 247 | substring.get_body(), 248 | self.byte_length, 249 | substring.len(), 250 | ) 251 | }; 252 | 253 | assert( 254 | position + substring.len() <= self.byte_length, 255 | "substring not present in main text (match found if a padding text included. is main text correctly formatted?)", 256 | ); 257 | let substring_length = substring.len(); 258 | 259 | // chunk_index = which 31-byte haystack chunk does the needle begin in? 260 | let chunk_index: u32 = position / 31; 261 | // chunk_offset = how many haystack bytes are present in the 1st haystack chunk? 262 | let chunk_offset: u32 = position % 31; 263 | // how many needle bytes are in 1st haystack chunk? 264 | let num_bytes_in_first_chunk: u32 = 31 - chunk_offset; 265 | let mut starting_needle_byte_index_of_final_chunk: u32 = 0; 266 | let mut chunk_index_of_final_haystack_chunk_with_matching_needle_bytes: u32 = 0; 267 | let mut num_full_chunks = 0; 268 | 269 | // is there only one haystack chunk that contains needle bytes? 270 | let merge_initial_final_needle_chunks = substring_length < num_bytes_in_first_chunk; 271 | 272 | // if the above is false... 273 | if (!merge_initial_final_needle_chunks) { 274 | // compute how many full 31-byte haystack chunks contain 31 needle bytes 275 | num_full_chunks = (substring_length - num_bytes_in_first_chunk) / 31; 276 | // for the final haystack chunk that contains needle bytes, where in the needle does this chunk begin? 277 | starting_needle_byte_index_of_final_chunk = 278 | num_full_chunks * 31 + num_bytes_in_first_chunk; 279 | 280 | // what is the index of the final haystack chunk that contains needle bytes? 281 | chunk_index_of_final_haystack_chunk_with_matching_needle_bytes = 282 | num_full_chunks + chunk_index + 1; 283 | } else { 284 | starting_needle_byte_index_of_final_chunk = 0; 285 | // if the needle bytes does NOT span more than 1 haystack chunk, 286 | // the final haystack index will be the same as the initial haystack index 287 | chunk_index_of_final_haystack_chunk_with_matching_needle_bytes = chunk_index; 288 | } 289 | 290 | // To minimize the number of comparisons between the haystack bytes and the needle bytes, 291 | // we pack both the haystack bytes and needle bytes into 31-byte Field "chunks" and compare chunks. 292 | // To do this correctly, we need to align the needle chunks with the haystack chunks 293 | /* 294 | e.g. consider a toy example where we pack 3 bytes into a chunk 295 | haystack: [VWXZYABCDEQRSTU] 296 | needle: [ABCDE] 297 | when constructing needle chunks, we need to align according to where the needle is located in the haystack 298 | haystack chunks: [VWX] [ZYA] [BCD] [EQR] [STU] 299 | _.. ... .__ 300 | processed needle chunks: [ZYA] [BCD] [EQR] 301 | a "_" symbole means that a chunk byte has been sourced from the haystack bytes, 302 | a "." symbol means a byte is sourced from the needle bytes 303 | Both the initial and final chunks of the processed needle are "composite" constructions. 304 | If chunk byte index < `position` or is > `position + needle length", byte is sourced from haystack, otherwise byte is sourced from needle 305 | The way we execute this in code is to define an "initial" needle chunk and a "final" needle chunk. 306 | Num needle bytes in initial chunk = position % 31 307 | Num needle bytes in final chunk = (needle_length - (position % 31)) % 31 308 | If needle_length < 31 then the "initial" and "final" chunks 309 | are actually the *same* chunk and we must perform a merge operation 310 | (see later in algo for comments) 311 | */ 312 | // instead of directly reading haystack bytes, we derive the bytes from the haystack chunks. 313 | // This way we don't have to instantiate the haystack bytes as a ROM table, which would cost 2 * haystack.length gates 314 | let offset_to_first_needle_byte_in_chunk: u32 = chunk_offset; 315 | let initial_haystack_chunk = self.chunks[chunk_index]; 316 | let final_haystack_chunk = 317 | self.chunks[chunk_index_of_final_haystack_chunk_with_matching_needle_bytes]; 318 | 319 | let initial_body_bytes: [u8; 31] = initial_haystack_chunk.to_be_bytes(); 320 | let final_body_bytes: [u8; 31] = final_haystack_chunk.to_be_bytes(); 321 | 322 | // When defining the initial chunk bytes, we can represent as Field elements as we are deriving values from known bytes. 323 | // This saves us a few gates 324 | let mut initial_chunk: [Field; 31] = [0; 31]; 325 | let mut final_chunk: [Field; 31] = [0; 31]; 326 | for i in 0..31 { 327 | // if i < offset_to_first_needle_byte_in_chunk, we read from the haystack 328 | // otherwise we read from the needle 329 | // n.b. this can be done with an if statement, but the following code produces fewer constraints 330 | let idx: u32 = i; 331 | let predicate = i < offset_to_first_needle_byte_in_chunk; 332 | let lhs: Field = initial_body_bytes[i] as Field; 333 | // if i < offset_to_first_needle_byte_in_chunk then `idx - offset_to_first_needle_byte_in_chunk` is negative 334 | // to ensure we access array correctly we need to set the lookup index to 0 if predicate = 0 335 | let substring_idx = if predicate { 336 | 0 337 | } else { 338 | idx - offset_to_first_needle_byte_in_chunk 339 | }; 340 | let rhs: Field = substring.get(substring_idx) as Field; 341 | let byte: Field = predicate as Field * (lhs - rhs) + rhs; 342 | initial_chunk[i] = byte; 343 | } 344 | 345 | // If `merge_initial_final_needle_chunks = true`, `final_chunk` will contain the full needle data, 346 | // this requires some complex logic to determine where we are sourcing the needle bytes from. 347 | // Either they come from the `initial_chunk`, the haystack bytes or the substring bytes. 348 | for i in 0..31 { 349 | let mut lhs_index = starting_needle_byte_index_of_final_chunk + i; 350 | let predicate = lhs_index < substring_length; 351 | /* 352 | | merge_initial_final_needle_chunks | predicate | byte_source | 353 | | false | false | body_bytes[i] | 354 | | false | true | substring[lhs_idx] | 355 | | true | false | body_bytes[i] | 356 | | true | true | initial_chunk[lhs_index] | 357 | NOTE: if `merge = true` and `predicate = true`, we read from `initial_chunk` to short-circuit some extra logic. 358 | if `initial_chunk` did not exist, then we would need to validate whether `i < offset_to_first_needle_byte_in_chunk`. 359 | if true, the byte source would be body_bytes, otherwise the source would be substring bytes 360 | */ 361 | let substring_idx = (predicate as u32) * lhs_index; 362 | let byte_from_substring = substring.get(substring_idx) as Field; 363 | let byte_from_initial_chunk = initial_chunk[i] as Field; 364 | let byte_from_haystack = final_body_bytes[i] as Field; 365 | 366 | // TODO: find out why this cuts 1 gate per iteration 367 | std::as_witness(byte_from_initial_chunk); 368 | 369 | let p = predicate as Field; 370 | let m = merge_initial_final_needle_chunks as Field; 371 | // p * (m * (a - b) + (b - c)) + c 372 | let ab = byte_from_initial_chunk - byte_from_substring; 373 | std::as_witness(ab); 374 | let bc = byte_from_substring - byte_from_haystack; 375 | let t0 = m * ab + bc; 376 | let destination_byte = p * t0 + byte_from_haystack; 377 | 378 | final_chunk[i] = destination_byte; 379 | } 380 | 381 | // TODO: moving this above the previous code block adds 31 gates. find out why? :/ 382 | let mut initial_needle_chunk: Field = 0; 383 | let mut final_needle_chunk: Field = 0; 384 | 385 | // Construct the initial and final needle chunks from the byte arrays we previously built. 386 | // Validate they match the initial and final haystack chunks 387 | for i in 0..31 { 388 | initial_needle_chunk *= 256; 389 | initial_needle_chunk += initial_chunk[i]; 390 | final_needle_chunk *= 256; 391 | final_needle_chunk += final_chunk[i]; 392 | } 393 | 394 | std::as_witness(initial_needle_chunk); 395 | std::as_witness(final_needle_chunk); 396 | 397 | initial_needle_chunk = merge_initial_final_needle_chunks as Field 398 | * (final_needle_chunk - initial_needle_chunk) 399 | + initial_needle_chunk; 400 | assert(initial_needle_chunk == initial_haystack_chunk); 401 | assert(final_needle_chunk == final_haystack_chunk); 402 | 403 | // Step 3: Construct needle chunks (for all but the 1st and last chunks) and validate they match the haystack chunks. 404 | // This part is much simpler as we know that all bytes in the chunk are sourced from the needle chunk. 405 | // NOTE: If we chose to not pack bytes into 31-byte chunks, the string matching algorithm would be simpler but more expensive. 406 | // Instead of matching chunks with each other, we would match individual byte values. 407 | // i.e. the number of iterations in this loop would be 31x greater 408 | // each loop iteration would also require a predicate, to check whether the byte index was within the needle range or not 409 | // Combined these two operations would add about 10 gates per loop iteration, 410 | // combined with a 31x iteration length would make this algorithm much more costly than the chunked variant 411 | let body_chunk_offset = chunk_index + 1; 412 | substring.match_chunks( 413 | self.chunks, 414 | num_bytes_in_first_chunk, 415 | body_chunk_offset, 416 | num_full_chunks, 417 | ); 418 | (true, position) 419 | } 420 | } 421 | 422 | impl From> for StringBody { 423 | fn from(input: BoundedVec) -> Self { 424 | Self::new(input.storage(), input.len() as u32) 425 | } 426 | } 427 | 428 | /// Given an input byte array, convert into 31-byte chunks 429 | /// 430 | /// Cost: ~0.5 gates per byte 431 | fn compute_chunks( 432 | body: [u8; MaxPaddedBytes], 433 | ) -> [Field; PaddedChunks] { 434 | let mut chunks: [Field; PaddedChunks] = [0; PaddedChunks]; 435 | for i in 0..PaddedChunks { 436 | let mut limb: Field = 0; 437 | for j in 0..31 { 438 | limb *= 256; 439 | limb += body[i * 31 + j] as Field; 440 | } 441 | chunks[i] = limb; 442 | std::as_witness(chunks[i]); 443 | } 444 | chunks 445 | } 446 | 447 | #[test] 448 | fn test() { 449 | let haystack_text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." 450 | .as_bytes(); 451 | let needle_text = " dolor in reprehenderit in voluptate velit esse".as_bytes(); 452 | 453 | let mut haystack: StringBody512 = StringBody::new(haystack_text, haystack_text.len()); 454 | let mut needle: SubString64 = SubString::new(needle_text, needle_text.len()); 455 | 456 | let result = haystack.substring_match(needle); 457 | assert(result.0 == true); 458 | } 459 | 460 | #[test] 461 | fn test_small_needle() { 462 | let haystack_text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." 463 | .as_bytes(); 464 | let needle_text = "olor".as_bytes(); 465 | let mut haystack: StringBody512 = StringBody::new(haystack_text, haystack_text.len()); 466 | let mut needle: SubString32 = SubString::new(needle_text, needle_text.len()); 467 | 468 | let result = haystack.substring_match(needle); 469 | assert(result.0 == true); 470 | } 471 | 472 | #[test] 473 | fn test_needle_aligned_on_byte_boundary() { 474 | let haystack_text = "the quick brown fox jumped over the lazy dog".as_bytes(); 475 | let needle_text = " the lazy dog".as_bytes(); 476 | 477 | let mut haystack: StringBody256 = StringBody::new(haystack_text, haystack_text.len()); 478 | let mut needle: SubString256 = SubString::new(needle_text, needle_text.len()); 479 | 480 | let result = haystack.substring_match(needle); 481 | assert(result.0 == true); 482 | } 483 | 484 | #[test] 485 | fn test_needle_haystack_equal_size() { 486 | let haystack_text = 487 | "the quick brown fox jumped over the lazy dog lorem ipsum blahhhh".as_bytes(); 488 | let needle_text = "the quick brown fox jumped over the lazy dog lorem ipsum blahhhh".as_bytes(); 489 | 490 | let mut haystack: StringBody64 = StringBody::new(haystack_text, haystack_text.len()); 491 | let mut needle: SubString64 = SubString::new(needle_text, needle_text.len()); 492 | 493 | let result = haystack.substring_match(needle); 494 | assert(result.0 == true); 495 | } 496 | 497 | #[test] 498 | fn test_concat() { 499 | let email_text = "account recovery for Bartholomew Fibblesworth".as_bytes(); 500 | let username = "Bartholomew Fibblesworth".as_bytes(); 501 | let mut padded_email_text: [u8; 256] = [0; 256]; 502 | let mut padded_username: [u8; 100] = [0; 100]; 503 | for i in 0..username.len() { 504 | padded_username[i] = username[i]; 505 | } 506 | for i in 0..email_text.len() { 507 | padded_email_text[i] = email_text[i]; 508 | } 509 | let needle_text_init = "account recovery for ".as_bytes(); 510 | 511 | let needle_start: SubString128 = SubString::new(needle_text_init, needle_text_init.len()); 512 | let needle_end: SubString128 = SubString::new(padded_username, username.len()); 513 | let needle = needle_start.concat(needle_end); 514 | 515 | for i in 0..45 { 516 | assert(needle.body[i] == email_text[i]); 517 | } 518 | 519 | let haystack: StringBody256 = StringBody::new(padded_email_text, 200); 520 | let (result, _): (bool, u32) = haystack.substring_match(needle); 521 | assert(result == true); 522 | } 523 | 524 | #[test] 525 | fn test_concat_into() { 526 | let email_text = "account recovery for Bartholomew Fibblesworth".as_bytes(); 527 | let username = "Bartholomew Fibblesworth".as_bytes(); 528 | let mut padded_email_text: [u8; 256] = [0; 256]; 529 | let mut padded_username: [u8; 100] = [0; 100]; 530 | for i in 0..username.len() { 531 | padded_username[i] = username[i]; 532 | } 533 | for i in 0..email_text.len() { 534 | padded_email_text[i] = email_text[i]; 535 | } 536 | let needle_text_init = "account recovery for ".as_bytes(); 537 | 538 | let needle_start: SubString32 = SubString::new(needle_text_init, needle_text_init.len()); 539 | let needle_end: SubString128 = SubString::new(padded_username, username.len()); 540 | let needle = needle_start.concat_into(needle_end); 541 | 542 | for i in 0..45 { 543 | assert(needle.body[i] == email_text[i]); 544 | } 545 | 546 | let haystack: StringBody256 = StringBody::new(padded_email_text, 200); 547 | let (result, _): (bool, u32) = haystack.substring_match(needle); 548 | assert(result == true); 549 | } 550 | 551 | #[test] 552 | unconstrained fn test_partial_match() { 553 | let mut Engine = DebugRandomEngine { seed: 0 }; 554 | let mut foo: [u8; 1024] = Engine.get_random_bytes(); 555 | let mut bar: [u8; 128] = [0; 128]; 556 | for i in 0..128 { 557 | bar[i] = foo[i + 123]; 558 | } 559 | let position = utils::search(foo, bar.as_slice(), 1024, 128); 560 | 561 | assert(position == 123); 562 | } 563 | 564 | #[test] 565 | fn test_substring_from_bounded_vec() { 566 | let haystack_text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." 567 | .as_bytes(); 568 | let needle_text = " dolor in reprehenderit in voluptate velit esse".as_bytes(); 569 | 570 | let mut haystack: StringBody512 = BoundedVec::from(haystack_text).into(); 571 | let mut needle: SubString64 = BoundedVec::from(needle_text).into(); 572 | 573 | let result = haystack.substring_match(needle); 574 | assert(result.0 == true); 575 | } 576 | 577 | #[test] 578 | fn test_string_body_from_bounded_vec() { 579 | let haystack_text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." 580 | .as_bytes(); 581 | 582 | let mut haystack: StringBody512 = BoundedVec::from(haystack_text).into(); 583 | let needle_text = " dolor in reprehenderit in voluptate velit esse".as_bytes(); 584 | let mut needle: SubString64 = BoundedVec::from(needle_text).into(); 585 | 586 | let result = haystack.substring_match(needle); 587 | assert(result.0 == true); 588 | } 589 | 590 | #[test] 591 | fn regression_20() { 592 | let haystack: [u8; 128] = [ 593 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x29, 0x92, 0x00, 0x55, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 594 | 0x6e, 0x00, 0x00, 0x00, 0x00, 0x57, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x84, 595 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 596 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 597 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 598 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 599 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5a, 0x00, 0x00, 0x00, 0x00, 0x00, 600 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 601 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 602 | ]; 603 | 604 | let needle: [u8; 32] = [ 605 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 606 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 607 | 0x00, 0x00, 608 | ]; 609 | let needle_len: u32 = 0x20; 610 | let id_haystack: StringBody128 = StringBody::new(haystack, 128); 611 | let pk_needle: SubString32 = SubString::new(needle, needle_len); 612 | let (result, _): (bool, u32) = id_haystack.substring_match(pk_needle); 613 | assert(result); 614 | } 615 | -------------------------------------------------------------------------------- /src/utils.nr: -------------------------------------------------------------------------------- 1 | pub unconstrained fn search( 2 | haystack: [u8; N], 3 | needle: [u8], 4 | haystack_length: u32, 5 | needle_length: u32, 6 | ) -> u32 { 7 | assert(needle_length > 0, "needle length of size 0 not supported"); 8 | assert(haystack_length > 0, "haystack length of size 0 not supported"); 9 | let mut found = false; 10 | let mut found_index: u32 = 0; 11 | for i in 0..haystack_length - needle_length + 1 { 12 | if (found == true) { 13 | break; 14 | } 15 | for j in 0..needle_length { 16 | if haystack[i + j] != needle[j] { 17 | break; 18 | } else if (j == needle_length - 1) { 19 | found = true; 20 | } 21 | if (found == true) { 22 | found_index = i; 23 | break; 24 | } 25 | } 26 | } 27 | assert(found == true, "utils::search could not find needle in haystack"); 28 | found_index 29 | } 30 | 31 | unconstrained fn __conditional_select(lhs: u8, rhs: u8, predicate: bool) -> u8 { 32 | if (predicate) { 33 | lhs 34 | } else { 35 | rhs 36 | } 37 | } 38 | 39 | pub fn conditional_select(lhs: u8, rhs: u8, predicate: bool) -> u8 { 40 | // Safety: This is all just a very verbose `if (predicate) { lhs } else { rhs }` 41 | // formulated as `rhs + (lhs - rhs) * predicate` 42 | unsafe { 43 | let result = __conditional_select(lhs, rhs, predicate); 44 | let result_f = result as Field; 45 | let lhs_f = lhs as Field; 46 | let rhs_f = rhs as Field; 47 | 48 | let diff = lhs_f - rhs_f; 49 | std::as_witness(diff); 50 | assert_eq((predicate as Field) * diff + rhs_f, result_f); 51 | result 52 | } 53 | } 54 | 55 | pub struct DebugRandomEngine { 56 | pub seed: Field, 57 | } 58 | 59 | impl DebugRandomEngine { 60 | unconstrained fn get_random_32_bytes(&mut self) -> [u8; 32] { 61 | self.seed += 1; 62 | let input: [u8; 32] = self.seed.to_be_bytes(); 63 | let hash: [u8; 32] = std::hash::blake3(input); 64 | hash 65 | } 66 | unconstrained fn get_random_field(&mut self) -> Field { 67 | let hash = self.get_random_32_bytes(); 68 | let mut result: Field = 0; 69 | for i in 0..32 { 70 | result *= 256; 71 | result += hash[i] as Field; 72 | } 73 | result 74 | } 75 | 76 | pub unconstrained fn get_random_bytes(&mut self) -> [u8; NBytes] { 77 | let num_chunks = (NBytes / 32) + ((NBytes % 32) != 0) as u32; 78 | 79 | let mut result: [u8; NBytes] = [0; NBytes]; 80 | for i in 0..num_chunks - 1 { 81 | let bytes = self.get_random_32_bytes(); 82 | for j in 0..32 { 83 | result[i * 32 + j] = bytes[j]; 84 | } 85 | } 86 | 87 | let bytes = self.get_random_32_bytes(); 88 | for j in 0..(NBytes - (num_chunks - 1) * 32) { 89 | result[(num_chunks - 1) * 32 + j] = bytes[j]; 90 | } 91 | result 92 | } 93 | } 94 | --------------------------------------------------------------------------------