diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 784988b0ce8..e81ede7199d 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,37 +1,23 @@ # Description - - - ## Problem\* - - Resolves ## Summary\* - - - -## Documentation - -- [ ] This PR requires documentation updates when merged. - - - [ ] I will submit a noir-lang/docs PR. - - +## Additional Context - - [ ] I will request for and support Dev Rel's help in documenting this PR. - - -## Additional Context +## Documentation\* - +Check one: +- [ ] No documentation needed. +- [ ] Documentation included in this PR. +- [ ] **[Exceptional Case]** Documentation to be submitted in a separate PR. # PR Checklist\* diff --git a/.github/workflows/auto-pr-rebuild-script.yml b/.github/workflows/auto-pr-rebuild-script.yml index 5e46e46ed4c..d81c9820c3e 100644 --- a/.github/workflows/auto-pr-rebuild-script.yml +++ b/.github/workflows/auto-pr-rebuild-script.yml @@ -1,13 +1,41 @@ name: Rebuild ACIR artifacts on: + pull_request: push: branches: - master jobs: + check-artifacts-requested: + name: Check if artifacts should be published + runs-on: ubuntu-22.04 + outputs: + publish: ${{ steps.check.outputs.publish }} + + steps: + - name: Check if artifacts should be published + id: check + uses: actions/github-script@v6 + with: + github-token: ${{ secrets.GITHUB_TOKEN }} + script: | + const { REF_NAME } = process.env; + if (REF_NAME == "master") { + return true; + } + + const labels = context.payload.pull_request.labels.map(label => label.name); + return labels.includes('publish-acir'); + result-encoding: string + env: + REF_NAME: ${{ github.ref_name }} + build-nargo: + name: Build nargo binary runs-on: ubuntu-22.04 + needs: [check-artifacts-requested] + if: ${{ needs.check-artifacts-requested.outputs.publish == true }} strategy: matrix: target: [x86_64-unknown-linux-gnu] @@ -17,7 +45,7 @@ jobs: uses: actions/checkout@v4 - name: Setup toolchain - uses: dtolnay/rust-toolchain@1.66.0 + uses: dtolnay/rust-toolchain@1.71.1 - uses: Swatinem/rust-cache@v2 with: @@ -42,6 +70,7 @@ jobs: retention-days: 3 auto-pr-rebuild-script: + name: Rebuild ACIR artifacts needs: [build-nargo] runs-on: ubuntu-latest @@ -71,10 +100,19 @@ jobs: chmod +x ./rebuild.sh ./rebuild.sh + - name: Upload ACIR artifacts + uses: actions/upload-artifact@v3 + with: + name: acir-artifacts + path: ./tooling/nargo_cli/tests/acir_artifacts + retention-days: 10 + - name: Check for changes in acir_artifacts directory id: check_changes + if: ${{ github.ref_name }} == "master" run: | git diff --quiet tooling/nargo_cli/tests/acir_artifacts/ || echo "::set-output name=changes::true" + - name: Create or Update PR if: steps.check_changes.outputs.changes == 'true' diff --git a/.github/workflows/build-aztec-feature-flag.yml b/.github/workflows/build-aztec-feature-flag.yml new file mode 100644 index 00000000000..888a88a7f88 --- /dev/null +++ b/.github/workflows/build-aztec-feature-flag.yml @@ -0,0 +1,45 @@ +name: Build with aztec feature flag + +on: + pull_request: + merge_group: + push: + branches: + - master + +# This will cancel previous runs when a branch or PR is updated +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.ref || github.run_id }} + cancel-in-progress: true + +jobs: + build-aztec-feature-flag: + name: Test on ${{ matrix.os }} + runs-on: ${{ matrix.runner }} + timeout-minutes: 30 + + strategy: + fail-fast: false + matrix: + include: + - os: ubuntu + runner: ubuntu-latest + target: x86_64-unknown-linux-gnu + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup toolchain + uses: dtolnay/rust-toolchain@1.71.1 + with: + targets: ${{ matrix.target }} + + - uses: Swatinem/rust-cache@v2 + with: + key: ${{ matrix.target }} + cache-on-failure: true + save-if: ${{ github.event_name != 'merge_group' }} + + - name: Build with feature flag + run: cargo build --features="noirc_frontend/aztec" diff --git a/.github/workflows/build-docs.yml b/.github/workflows/build-docs.yml index 23ae0e409e9..cdebb2b8bcc 100644 --- a/.github/workflows/build-docs.yml +++ b/.github/workflows/build-docs.yml @@ -2,12 +2,6 @@ name: Build docs on: pull_request: - paths: - - 'docs/**' - types: - - opened - - synchronize - - labeled jobs: add_label: @@ -53,7 +47,7 @@ jobs: }) } - deploy_docs: + build_and_deploy: runs-on: ubuntu-latest permissions: pull-requests: write @@ -62,81 +56,32 @@ jobs: steps: - name: Checkout code uses: actions/checkout@v2 - - - name: Netlify deploy - run: | - BRANCH_NAME=$(echo "${{ github.head_ref || github.ref }}" | sed -e "s#refs/[^/]*/##") - curl -X POST -d {} "https://api.netlify.com/build_hooks/${{ secrets.NETLIFY_BUILD_HOOK }}?trigger_branch=$BRANCH_NAME" - - name: Get deploy preview - id: get_deploy_preview - run: | - BRANCH_NAME=$(echo "${{ github.head_ref || github.ref }}" | sed -e "s#refs/[^/]*/##") - curl -X GET "https://api.netlify.com/api/v1/sites/${{ secrets.NETLIFY_SITE_ID }}/deploys?branch=$BRANCH_NAME" > deploy.json - echo "::set-output name=deploy_url::$(cat deploy.json | jq -r '.[0].deploy_ssl_url')" - - - name: Add PR Comment - uses: mshick/add-pr-comment@v2 - with: - message: | - Hey @${{ github.event.pull_request.user.login }}! 🙌 - - I'm the deployment bot for Noir Docs, and I've got some updates for you: - - ## Deployment Status - Your latest changes are being deployed for preview! 🚀 - - Click the badge to see logs 🧐 - - [![Netlify Status](https://api.netlify.com/api/v1/badges/${{ secrets.NETLIFY_SITE_ID }}/deploy-status?branch=${{ github.head_ref || github.ref }})](https://app.netlify.com/sites/noir-docs-v2/deploys) - - If you have any questions about this process, refer to our contribution guide or feel free to ask around. - - - - name: Check on deploy status - uses: ./.github/actions/docs/build-status - id: check_deploy_status - with: - branch-name: ${{ github.head_ref || github.ref }} - site-id: ${{ secrets.NETLIFY_SITE_ID }} - continue-on-error: true - - - - name: Debugging - print deploy_status - run: echo "${{ steps.check_deploy_status.outputs.deploy_status }}" - - - - name: Change PR Comment for Successful Deployment - if: steps.check_deploy_status.outputs.deploy_status == 'success' - uses: mshick/add-pr-comment@v2 + + - name: Setup Node.js + uses: actions/setup-node@v2 with: - message-success: | - ![It's Alive!](https://i.imgflip.com/82hw5n.jpg) - - I'm a bot, beep boop 🤖 - - ## Deployment Status: Success! - [![Netlify Status](https://api.netlify.com/api/v1/badges/${{ secrets.NETLIFY_SITE_ID }}/deploy-status?branch=${{ github.head_ref || github.ref }})](https://app.netlify.com/sites/noir-docs-v2/deploys) - - ## Preview - - 🌐 [View Deployment Preview](${{ steps.get_deploy_preview.outputs.deploy_url }}) - + node-version: '18' - - - name: Change PR Comment for Failed Deployment - if: steps.check_deploy_status.outputs.deploy_status == 'failure' - uses: mshick/add-pr-comment@v2 + - name: Install dependencies + run: yarn + + - name: Build docs + run: yarn workspace docs build + + - name: Remove pre-releases + working-directory: docs + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: yarn setStable + + - name: Deploy to Netlify + uses: nwtgck/actions-netlify@v2.1 with: - message: | - ![docs CI troll](https://i.imgflip.com/82ht8f.jpg) - - I'm a bot, beep boop 🤖 - - ## Deployment Status: Failed ❌ - Deployment didn't succeed. Please check logs below and resolve the issue 🧐 - - [![Netlify Status](https://api.netlify.com/api/v1/badges/${{ secrets.NETLIFY_SITE_ID }}/deploy-status?branch=${{ github.head_ref || github.ref }})](https://app.netlify.com/sites/noir-docs-v2/deploys) - - - name: Fail the workflow if deployment failed - if: steps.check_deploy_status.outputs.deploy_status == 'failure' - run: exit 1 + publish-dir: './docs/build' + github-token: ${{ secrets.GITHUB_TOKEN }} + enable-github-deployment: false + deploy-message: "Deploy from GitHub Actions for PR ${{ github.event.number }}" + env: + NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }} + NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }} + timeout-minutes: 1 diff --git a/.github/workflows/formatting.yml b/.github/workflows/formatting.yml index 758547e2d7a..97736e2415e 100644 --- a/.github/workflows/formatting.yml +++ b/.github/workflows/formatting.yml @@ -32,7 +32,7 @@ jobs: uses: actions/checkout@v4 - name: Setup toolchain - uses: dtolnay/rust-toolchain@1.67.0 + uses: dtolnay/rust-toolchain@1.71.1 with: targets: ${{ matrix.target }} components: clippy, rustfmt diff --git a/.github/workflows/gates_report.yml b/.github/workflows/gates_report.yml index e2d6bdd56b7..41a68c65852 100644 --- a/.github/workflows/gates_report.yml +++ b/.github/workflows/gates_report.yml @@ -18,7 +18,7 @@ jobs: uses: actions/checkout@v4 - name: Setup toolchain - uses: dtolnay/rust-toolchain@1.66.0 + uses: dtolnay/rust-toolchain@1.71.1 - uses: Swatinem/rust-cache@v2 with: diff --git a/.github/workflows/publish-acvm.yml b/.github/workflows/publish-acvm.yml index 3f4641a690c..ded669f13d0 100644 --- a/.github/workflows/publish-acvm.yml +++ b/.github/workflows/publish-acvm.yml @@ -18,9 +18,7 @@ jobs: ref: ${{ inputs.acvm-ref }} - name: Setup toolchain - uses: dtolnay/rust-toolchain@master - with: - toolchain: 1.66.0 + uses: dtolnay/rust-toolchain@1.71.1 # These steps are in a specific order so crate dependencies are updated first - name: Publish acir_field diff --git a/.github/workflows/publish-docs.yml b/.github/workflows/publish-docs.yml new file mode 100644 index 00000000000..4c20c9181db --- /dev/null +++ b/.github/workflows/publish-docs.yml @@ -0,0 +1,57 @@ +name: Publish Docs + +on: + workflow_dispatch: + inputs: + tag: + description: The tag to build Docs for + required: false + +jobs: + publish-docs: + runs-on: ubuntu-latest + if: ${{ inputs.tag != '' }} + permissions: + pull-requests: write + steps: + - name: Checkout sources + uses: actions/checkout@v4 + with: + ref: ${{ inputs.tag }} + + - name: Setup Node.js + uses: actions/setup-node@v2 + with: + node-version: '18' + + - name: Install Yarn + run: npm install -g yarn + + - name: Install Yarn dependencies + run: yarn + + - name: Cut a new version + working-directory: ./docs + run: yarn docusaurus docs:version ${{ inputs.tag }} + + - name: Remove pre-releases + id: get_version + run: | + cd docs && yarn setStable + + - name: Build docs + run: yarn workspace docs build + + - name: Deploy to Netlify + uses: nwtgck/actions-netlify@v2.1 + with: + publish-dir: './docs/build' + production-branch: master + production-deploy: true + github-token: ${{ secrets.GITHUB_TOKEN }} + enable-github-deployment: false + deploy-message: "Deploy from GitHub Actions for tag ${{ inputs.tag }}" + env: + NETLIFY_AUTH_TOKEN: ${{ secrets.NETLIFY_AUTH_TOKEN }} + NETLIFY_SITE_ID: ${{ secrets.NETLIFY_SITE_ID }} + timeout-minutes: 1 diff --git a/.github/workflows/publish-nargo.yml b/.github/workflows/publish-nargo.yml index 840dca2f289..59d4fe4cc48 100644 --- a/.github/workflows/publish-nargo.yml +++ b/.github/workflows/publish-nargo.yml @@ -45,7 +45,7 @@ jobs: echo "MACOSX_DEPLOYMENT_TARGET=$(xcrun -sdk macosx$(sw_vers -productVersion) --show-sdk-platform-version)" >> $GITHUB_ENV - name: Setup toolchain - uses: dtolnay/rust-toolchain@1.67.0 + uses: dtolnay/rust-toolchain@1.71.1 with: targets: ${{ matrix.target }} @@ -128,7 +128,7 @@ jobs: ref: ${{ inputs.tag || env.GITHUB_REF }} - name: Setup toolchain - uses: dtolnay/rust-toolchain@1.67.0 + uses: dtolnay/rust-toolchain@1.71.1 with: targets: ${{ matrix.target }} @@ -177,6 +177,7 @@ jobs: repo_token: ${{ secrets.GITHUB_TOKEN }} file: ./nargo-${{ matrix.target }}.tar.gz asset_name: nargo-${{ matrix.target }}.tar.gz + prerelease: true overwrite: true tag: ${{ inputs.tag || 'nightly' }} # This will fail if `inputs.tag` is not a tag (e.g. testing a branch) @@ -198,4 +199,4 @@ jobs: overwrite: true tag: ${{ format('{0}-{1}', 'nightly', steps.date.outputs.date) }} - \ No newline at end of file + diff --git a/.github/workflows/recrawler.yml b/.github/workflows/recrawler.yml new file mode 100644 index 00000000000..ee832e273a1 --- /dev/null +++ b/.github/workflows/recrawler.yml @@ -0,0 +1,22 @@ +name: Algolia Recrawl +on: + push: + branches: [ master ] + workflow_dispatch: + +jobs: + algolia_recrawl: + name: Algolia Recrawl + runs-on: ubuntu-latest + steps: + - name: Algolia crawler creation and crawl + uses: algolia/algoliasearch-crawler-github-actions@v1.1.0 + id: algolia_crawler + with: + crawler-user-id: ${{ secrets.CRAWLER_USER_ID }} + crawler-api-key: ${{ secrets.CRAWLER_API_KEY }} + algolia-app-id: ${{ secrets.ALGOLIA_APP_ID }} + algolia-api-key: ${{ secrets.ALGOLIA_API_KEY }} + site-url: 'https://noir-lang.org/' + crawler-name: noir-lang + override-config: false diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2786bc32970..d785eefbc14 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -77,4 +77,20 @@ jobs: workflow: publish-es-packages.yml ref: master token: ${{ secrets.NOIR_REPO_TOKEN }} - inputs: '{ "noir-ref": "${{ needs.release-please.outputs.tag-name }}", "npm-tag": "latest" }' \ No newline at end of file + inputs: '{ "noir-ref": "${{ needs.release-please.outputs.tag-name }}", "npm-tag": "latest" }' + + + publish-docs: + name: Publish docs + needs: [release-please] + if: ${{ needs.release-please.outputs.tag-name }} + runs-on: ubuntu-latest + steps: + - name: Dispatch to publish workflow + uses: benc-uk/workflow-dispatch@v1 + with: + workflow: publish-docs.yml + repo: noir-lang/noir + ref: master + token: ${{ secrets.GITHUB_TOKEN }} + inputs: '{ "tag": "${{ needs.release-please.outputs.tag-name }}"}' diff --git a/.github/workflows/test-abi_wasm.yml b/.github/workflows/test-abi_wasm.yml index 7fecb66fd7f..adc229b6b88 100644 --- a/.github/workflows/test-abi_wasm.yml +++ b/.github/workflows/test-abi_wasm.yml @@ -15,23 +15,17 @@ concurrency: jobs: build: runs-on: ubuntu-latest - env: - CACHED_PATH: /tmp/nix-cache steps: - name: Checkout sources uses: actions/checkout@v3 - name: Setup Nix - uses: cachix/install-nix-action@v22 + uses: ./.github/actions/nix with: - nix_path: nixpkgs=channel:nixos-23.05 - github_access_token: ${{ secrets.GITHUB_TOKEN }} - - - uses: cachix/cachix-action@v12 - with: - name: barretenberg - authToken: "${{ secrets.CACHIX_AUTH_TOKEN }}" + github-token: ${{ secrets.GITHUB_TOKEN }} + nix-cache-name: ${{ vars.NIX_CACHE_NAME }} + cachix-auth-token: ${{ secrets.CACHIXAUTHTOKEN }} - name: Build noirc_abi_wasm run: | diff --git a/.github/workflows/test-acvm-js.yml b/.github/workflows/test-acvm-js.yml index c69f4995198..9e17be5a26f 100644 --- a/.github/workflows/test-acvm-js.yml +++ b/.github/workflows/test-acvm-js.yml @@ -19,15 +19,12 @@ jobs: - name: Checkout sources uses: actions/checkout@v4 - - uses: cachix/install-nix-action@v20 + - name: Setup Nix + uses: ./.github/actions/nix with: - nix_path: nixpkgs=channel:nixos-22.11 - github_access_token: ${{ secrets.GITHUB_TOKEN }} - - - uses: cachix/cachix-action@v12 - with: - name: barretenberg - authToken: "${{ secrets.CACHIX_AUTH_TOKEN }}" + github-token: ${{ secrets.GITHUB_TOKEN }} + nix-cache-name: ${{ vars.NIX_CACHE_NAME }} + cachix-auth-token: ${{ secrets.CACHIXAUTHTOKEN }} - name: Build acvm-js run: | diff --git a/.github/workflows/test-integration.yml b/.github/workflows/test-integration.yml index f3bb953f676..fee606ee619 100644 --- a/.github/workflows/test-integration.yml +++ b/.github/workflows/test-integration.yml @@ -19,7 +19,7 @@ jobs: uses: actions/checkout@v4 - name: Setup toolchain - uses: dtolnay/rust-toolchain@1.66.0 + uses: dtolnay/rust-toolchain@1.71.1 - uses: Swatinem/rust-cache@v2 with: @@ -43,41 +43,50 @@ jobs: path: ./dist/* retention-days: 3 - build-wasm: + build-acvm-js: runs-on: ubuntu-latest - env: - CACHED_PATH: /tmp/nix-cache - steps: - name: Checkout sources uses: actions/checkout@v4 - name: Setup Nix - uses: cachix/install-nix-action@v22 + uses: ./.github/actions/nix with: - nix_path: nixpkgs=channel:nixos-23.05 - github_access_token: ${{ secrets.GITHUB_TOKEN }} + github-token: ${{ secrets.GITHUB_TOKEN }} + nix-cache-name: ${{ vars.NIX_CACHE_NAME }} + cachix-auth-token: ${{ secrets.CACHIXAUTHTOKEN }} + + - name: Build acvm-js + run: | + nix build -L .#acvm_js - - uses: cachix/cachix-action@v12 + - name: Dereference symlink + run: echo "UPLOAD_PATH=$(readlink -f result/acvm_js)" >> $GITHUB_ENV + + - name: Upload artifact + uses: actions/upload-artifact@v3 with: - name: barretenberg - authToken: "${{ secrets.CACHIX_AUTH_TOKEN }}" + name: acvm-js + path: ${{ env.UPLOAD_PATH }} + retention-days: 3 - - name: Build wasm package - run: | - nix build -L .#noir_wasm + build-wasm: + runs-on: ubuntu-latest - - name: Export cache from nix store - if: ${{ steps.cache.outputs.cache-hit != 'true' && github.event_name != 'merge_group' }} - run: | - nix copy --to "file://${{ env.CACHED_PATH }}?compression=zstd¶llel-compression=true" .#noir-wasm-cargo-artifacts + steps: + - name: Checkout sources + uses: actions/checkout@v4 - - uses: actions/cache/save@v3 - # Don't create cache entries for the merge queue. - if: ${{ steps.cache.outputs.cache-hit != 'true' && github.event_name != 'merge_group' }} + - name: Setup Nix + uses: ./.github/actions/nix with: - path: ${{ env.CACHED_PATH }} - key: ${{ steps.cache.outputs.cache-primary-key }} + github-token: ${{ secrets.GITHUB_TOKEN }} + nix-cache-name: ${{ vars.NIX_CACHE_NAME }} + cachix-auth-token: ${{ secrets.CACHIXAUTHTOKEN }} + + - name: Build wasm package + run: | + nix build -L .#noir_wasm - name: Dereference symlink run: echo "UPLOAD_PATH=$(readlink -f ./result/noir_wasm)" >> $GITHUB_ENV @@ -91,40 +100,17 @@ jobs: build-noirc: runs-on: ubuntu-latest - env: - CACHED_PATH: /tmp/nix-cache steps: - name: Checkout sources uses: actions/checkout@v3 - name: Setup Nix - uses: cachix/install-nix-action@v22 - with: - nix_path: nixpkgs=channel:nixos-23.05 - github_access_token: ${{ secrets.GITHUB_TOKEN }} - - - uses: cachix/cachix-action@v12 - with: - name: barretenberg - authToken: "${{ secrets.CACHIX_AUTH_TOKEN }}" - - - name: Restore nix store cache - uses: actions/cache/restore@v3 - id: cache + uses: ./.github/actions/nix with: - path: ${{ env.CACHED_PATH }} - key: ${{ runner.os }}-flake-abi-wasm-${{ hashFiles('*.lock') }} - - # Based on https://github.com/marigold-dev/deku/blob/b5016f0cf4bf6ac48db9111b70dd7fb49b969dfd/.github/workflows/build.yml#L26 - - name: Copy cache into nix store - if: steps.cache.outputs.cache-hit == 'true' - # We don't check the signature because we're the one that created the cache - run: | - for narinfo in ${{ env.CACHED_PATH }}/*.narinfo; do - path=$(head -n 1 "$narinfo" | awk '{print $2}') - nix copy --no-check-sigs --from "file://${{ env.CACHED_PATH }}" "$path" - done + github-token: ${{ secrets.GITHUB_TOKEN }} + nix-cache-name: ${{ vars.NIX_CACHE_NAME }} + cachix-auth-token: ${{ secrets.CACHIXAUTHTOKEN }} - name: Build noirc_abi_wasm run: | @@ -132,18 +118,6 @@ jobs: cp -r ./result/noirc_abi_wasm/nodejs ./tooling/noirc_abi_wasm cp -r ./result/noirc_abi_wasm/web ./tooling/noirc_abi_wasm - - name: Export cache from nix store - if: ${{ steps.cache.outputs.cache-hit != 'true' && github.event_name != 'merge_group' }} - run: | - nix copy --to "file://${{ env.CACHED_PATH }}?compression=zstd¶llel-compression=true" .#noirc-abi-wasm-cargo-artifacts - - - uses: actions/cache/save@v3 - # Don't create cache entries for the merge queue. - if: ${{ steps.cache.outputs.cache-hit != 'true' && github.event_name != 'merge_group' }} - with: - path: ${{ env.CACHED_PATH }} - key: ${{ steps.cache.outputs.cache-primary-key }} - - name: Dereference symlink run: echo "UPLOAD_PATH=$(readlink -f ./result/noirc_abi_wasm)" >> $GITHUB_ENV @@ -156,7 +130,7 @@ jobs: test-solidity-verifier: runs-on: ubuntu-latest - needs: [build-wasm, build-nargo, build-noirc] + needs: [build-acvm-js, build-wasm, build-nargo, build-noirc] env: CACHED_PATH: /tmp/nix-cache @@ -170,13 +144,19 @@ jobs: name: nargo path: ./nargo - - name: Download wasm package artifact + - name: Download acvm_js package artifact + uses: actions/download-artifact@v3 + with: + name: acvm-js + path: ./acvm-repo/acvm_js + + - name: Download noir_wasm package artifact uses: actions/download-artifact@v3 with: name: noir_wasm path: ./compiler/wasm - - name: Download noirc package artifact + - name: Download noirc_abi package artifact uses: actions/download-artifact@v3 with: name: noirc_abi_wasm @@ -196,22 +176,9 @@ jobs: - name: Install Playwright uses: ./.github/actions/install-playwright - - name: Install jq - run: sudo apt-get install jq - - - name: Install wasm-bindgen-cli - uses: taiki-e/install-action@v2 - with: - tool: wasm-bindgen-cli@0.2.86 - - - name: Install wasm-opt - run: | - npm i wasm-opt -g - - name: Setup `integration-tests` run: | yarn workspace @noir-lang/source-resolver build - yarn workspace @noir-lang/acvm_js build yarn workspace @noir-lang/types build yarn workspace @noir-lang/backend_barretenberg build yarn workspace @noir-lang/noir_js build diff --git a/.github/workflows/test-noir-js.yml b/.github/workflows/test-noir-js.yml index 8f1862bdfdc..e74f2ee6015 100644 --- a/.github/workflows/test-noir-js.yml +++ b/.github/workflows/test-noir-js.yml @@ -21,7 +21,7 @@ jobs: uses: ./.github/actions/setup - name: Setup toolchain - uses: dtolnay/rust-toolchain@1.66.0 + uses: dtolnay/rust-toolchain@1.71.1 with: targets: wasm32-unknown-unknown diff --git a/.github/workflows/test-noir_wasm.yml b/.github/workflows/test-noir_wasm.yml index 6bc8b70a1f4..caafe6b91db 100644 --- a/.github/workflows/test-noir_wasm.yml +++ b/.github/workflows/test-noir_wasm.yml @@ -23,7 +23,7 @@ jobs: uses: actions/checkout@v4 - name: Setup toolchain - uses: dtolnay/rust-toolchain@1.67.0 + uses: dtolnay/rust-toolchain@1.71.1 - uses: Swatinem/rust-cache@v2 with: @@ -49,23 +49,17 @@ jobs: build-wasm: runs-on: ubuntu-latest - env: - CACHED_PATH: /tmp/nix-cache steps: - name: Checkout sources uses: actions/checkout@v4 - name: Setup Nix - uses: cachix/install-nix-action@v22 + uses: ./.github/actions/nix with: - nix_path: nixpkgs=channel:nixos-23.05 - github_access_token: ${{ secrets.GITHUB_TOKEN }} - - - uses: cachix/cachix-action@v12 - with: - name: barretenberg - authToken: "${{ secrets.CACHIX_AUTH_TOKEN }}" + github-token: ${{ secrets.GITHUB_TOKEN }} + nix-cache-name: ${{ vars.NIX_CACHE_NAME }} + cachix-auth-token: ${{ secrets.CACHIXAUTHTOKEN }} - name: Build wasm package run: | diff --git a/.github/workflows/test-rust-workspace.yml b/.github/workflows/test-rust-workspace.yml index 06b4ade6e9b..eccd7585fcf 100644 --- a/.github/workflows/test-rust-workspace.yml +++ b/.github/workflows/test-rust-workspace.yml @@ -31,7 +31,7 @@ jobs: uses: actions/checkout@v4 - name: Setup toolchain - uses: dtolnay/rust-toolchain@1.67.0 + uses: dtolnay/rust-toolchain@1.71.1 with: targets: ${{ matrix.target }} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index bc2acd40829..9cbbeeb677f 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -187,7 +187,7 @@ In the docs folder, you'll find the current, unreleased version, which we call ` While the versioning is intended to be managed by the core maintainers, we feel it's important for external contributors to understand why and how is it maintained. To bump to a new version, run the following command, replacing with the intended version: ```bash -npm run docusaurus docs:version +yarn docusaurus docs:version ``` This should create a new version by copying the docs folder and the sidebars.js file to the relevant folders, as well as adding this version to versions.json. diff --git a/Cargo.lock b/Cargo.lock index 45a198ba0ba..cb154189431 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7,6 +7,7 @@ name = "acir" version = "0.30.0" dependencies = [ "acir_field", + "base64", "bincode", "brillig", "flate2", @@ -2079,6 +2080,7 @@ dependencies = [ "bitmaps", "rand_core", "rand_xoshiro", + "serde", "sized-chunks", "typenum", "version_check", @@ -2415,7 +2417,6 @@ name = "nargo" version = "0.18.0" dependencies = [ "acvm", - "base64", "codespan-reporting", "fm", "iter-extended", @@ -2498,6 +2499,7 @@ dependencies = [ "fm", "nargo", "noirc_frontend", + "semver", "serde", "thiserror", "toml", @@ -2546,6 +2548,7 @@ dependencies = [ "codespan-reporting", "easy-repl", "nargo", + "noirc_errors", "noirc_printable_type", "owo-colors", "thiserror", @@ -2575,7 +2578,7 @@ dependencies = [ [[package]] name = "noir_lsp_wasm" -version = "0.16.0" +version = "0.18.0" dependencies = [ "acvm", "async-lsp", @@ -2645,11 +2648,11 @@ name = "noirc_driver" version = "0.18.0" dependencies = [ "acvm", - "base64", "build-data", "clap", "fm", "fxhash", + "iter-extended", "noirc_abi", "noirc_errors", "noirc_evaluator", @@ -2682,6 +2685,7 @@ dependencies = [ "noirc_errors", "noirc_frontend", "num-bigint", + "serde", "thiserror", ] @@ -3705,9 +3709,9 @@ dependencies = [ [[package]] name = "semver" -version = "1.0.18" +version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b0293b4b29daaf487284529cc2f5675b8e57c61f70167ba415a463651fd6a918" +checksum = "836fa6a3e1e547f9a2c4040802ec865b5d85f4014efe00555d7090a3dcaa1090" dependencies = [ "serde", ] diff --git a/Cargo.toml b/Cargo.toml index 1c0d7101ecc..5131ca1eed6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -48,9 +48,29 @@ license = "MIT OR Apache-2.0" repository = "https://github.com/noir-lang/noir/" [workspace.dependencies] + +# ACVM workspace dependencies +acir = { path = "acvm-repo/acir", default-features = false } +acvm = { path = "acvm-repo/acvm" } +acir_field = { path = "acvm-repo/acir_field", default-features = false } +stdlib = { package = "acvm_stdlib", path = "acvm-repo/stdlib", default-features = false } +brillig = { path = "acvm-repo/brillig", default-features = false } +brillig_vm = { path = "acvm-repo/brillig_vm", default-features = false } +acvm_blackbox_solver = { path = "acvm-repo/blackbox_solver", default-features = false } +barretenberg_blackbox_solver = { path = "acvm-repo/barretenberg_blackbox_solver", default-features = false } + +# Noir compiler workspace dependencies arena = { path = "compiler/utils/arena" } fm = { path = "compiler/fm" } iter-extended = { path = "compiler/utils/iter-extended" } +noirc_driver = { path = "compiler/noirc_driver" } +noirc_errors = { path = "compiler/noirc_errors" } +noirc_evaluator = { path = "compiler/noirc_evaluator" } +noirc_frontend = { path = "compiler/noirc_frontend" } +noirc_printable_type = { path = "compiler/noirc_printable_type" } +noir_wasm = { path = "compiler/wasm" } + +# Noir tooling workspace dependencies nargo = { path = "tooling/nargo" } nargo_fmt = { path = "tooling/nargo_fmt" } nargo_cli = { path = "tooling/nargo_cli" } @@ -60,12 +80,22 @@ noir_lsp_wasm = { path = "tooling/lsp_wasm" } noir_debugger = { path = "tooling/debugger" } noirc_abi = { path = "tooling/noirc_abi" } bb_abstraction_leaks = { path = "tooling/bb_abstraction_leaks" } -noirc_driver = { path = "compiler/noirc_driver" } -noirc_errors = { path = "compiler/noirc_errors" } -noirc_evaluator = { path = "compiler/noirc_evaluator" } -noirc_frontend = { path = "compiler/noirc_frontend" } -noirc_printable_type = { path = "compiler/noirc_printable_type" } -noir_wasm = { path = "compiler/wasm" } + +# LSP +async-lsp = { version = "0.0.5", default-features = false } +lsp-types = "0.94.1" +tower = "0.4" + +# Wasm +wasm-bindgen = { version = "=0.2.86", features = ["serde-serialize"] } +wasm-bindgen-test = "0.3.36" +wasm-bindgen-futures = "0.4.36" +console_error_panic_hook = "0.1.7" +gloo-utils = { version = "0.1", features = ["serde"] } +js-sys = "0.3.62" +getrandom = "0.2" + + cfg-if = "1.0.0" clap = { version = "4.3.19", features = ["derive"] } codespan = { version = "0.11.1", features = ["serialization"] } @@ -81,25 +111,13 @@ serde_json = "1.0" smol_str = { version = "0.1.17", features = ["serde"] } thiserror = "1.0.21" toml = "0.7.2" -tower = "0.4" url = "2.2.0" -wasm-bindgen = { version = "=0.2.86", features = ["serde-serialize"] } -wasm-bindgen-test = "0.3.33" -js-sys = "0.3.62" base64 = "0.21.2" fxhash = "0.2.1" -acir = { path = "acvm-repo/acir", default-features = false } -acvm = { path = "acvm-repo/acvm" } -acir_field = { path = "acvm-repo/acir_field", default-features = false } -stdlib = { package = "acvm_stdlib", path = "acvm-repo/stdlib", default-features = false } -brillig = { path = "acvm-repo/brillig", default-features = false } -brillig_vm = { path = "acvm-repo/brillig_vm", default-features = false } -acvm_blackbox_solver = { path = "acvm-repo/blackbox_solver", default-features = false } -barretenberg_blackbox_solver = { path = "acvm-repo/barretenberg_blackbox_solver", default-features = false } - +build-data = "0.1.3" bincode = "1.3.3" - hex = "0.4.2" +const_format = "0.2.30" num-bigint = "0.4" num-traits = "0.2" diff --git a/README.md b/README.md index 202d8f9904d..c48c9110187 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ Concretely the following items are on the road map: ## Minimum Rust version -This crate's minimum supported rustc version is 1.67.0. +This crate's minimum supported rustc version is 1.71.1. ## Working on this project diff --git a/acvm-repo/acir/Cargo.toml b/acvm-repo/acir/Cargo.toml index af6429a3a3d..871f7c514c1 100644 --- a/acvm-repo/acir/Cargo.toml +++ b/acvm-repo/acir/Cargo.toml @@ -19,6 +19,7 @@ serde.workspace = true thiserror.workspace = true flate2 = "1.0.24" bincode.workspace = true +base64.workspace = true [dev-dependencies] serde_json = "1.0" diff --git a/acvm-repo/acir/src/circuit/mod.rs b/acvm-repo/acir/src/circuit/mod.rs index 3171cb57d16..99ab389e31e 100644 --- a/acvm-repo/acir/src/circuit/mod.rs +++ b/acvm-repo/acir/src/circuit/mod.rs @@ -9,9 +9,10 @@ use thiserror::Error; use std::{io::prelude::*, num::ParseIntError, str::FromStr}; +use base64::Engine; use flate2::Compression; +use serde::{de::Error as DeserializationError, Deserialize, Deserializer, Serialize, Serializer}; -use serde::{Deserialize, Serialize}; use std::collections::BTreeSet; #[derive(Clone, PartialEq, Eq, Serialize, Deserialize, Default)] @@ -125,7 +126,7 @@ impl Circuit { PublicInputs(public_inputs) } - pub fn write(&self, writer: W) -> std::io::Result<()> { + fn write(&self, writer: W) -> std::io::Result<()> { let buf = bincode::serialize(self).unwrap(); let mut encoder = flate2::write::GzEncoder::new(writer, Compression::default()); encoder.write_all(&buf)?; @@ -133,13 +134,46 @@ impl Circuit { Ok(()) } - pub fn read(reader: R) -> std::io::Result { + fn read(reader: R) -> std::io::Result { let mut gz_decoder = flate2::read::GzDecoder::new(reader); let mut buf_d = Vec::new(); gz_decoder.read_to_end(&mut buf_d)?; bincode::deserialize(&buf_d) .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidInput, err)) } + + pub fn serialize_circuit(circuit: &Circuit) -> Vec { + let mut circuit_bytes: Vec = Vec::new(); + circuit.write(&mut circuit_bytes).expect("expected circuit to be serializable"); + circuit_bytes + } + + pub fn deserialize_circuit(serialized_circuit: &[u8]) -> std::io::Result { + Circuit::read(serialized_circuit) + } + + // Serialize and base64 encode circuit + pub fn serialize_circuit_base64(circuit: &Circuit, s: S) -> Result + where + S: Serializer, + { + let circuit_bytes = Circuit::serialize_circuit(circuit); + let encoded_b64 = base64::engine::general_purpose::STANDARD.encode(circuit_bytes); + s.serialize_str(&encoded_b64) + } + + // Deserialize and base64 decode circuit + pub fn deserialize_circuit_base64<'de, D>(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let bytecode_b64: String = serde::Deserialize::deserialize(deserializer)?; + let circuit_bytes = base64::engine::general_purpose::STANDARD + .decode(bytecode_b64) + .map_err(D::Error::custom)?; + let circuit = Self::deserialize_circuit(&circuit_bytes).map_err(D::Error::custom)?; + Ok(circuit) + } } impl std::fmt::Display for Circuit { @@ -229,9 +263,8 @@ mod tests { }; fn read_write(circuit: Circuit) -> (Circuit, Circuit) { - let mut bytes = Vec::new(); - circuit.write(&mut bytes).unwrap(); - let got_circuit = Circuit::read(&*bytes).unwrap(); + let bytes = Circuit::serialize_circuit(&circuit); + let got_circuit = Circuit::deserialize_circuit(&bytes).unwrap(); (circuit, got_circuit) } @@ -277,7 +310,7 @@ mod tests { encoder.write_all(bad_circuit).unwrap(); encoder.finish().unwrap(); - let deserialization_result = Circuit::read(&*zipped_bad_circuit); + let deserialization_result = Circuit::deserialize_circuit(&zipped_bad_circuit); assert!(deserialization_result.is_err()); } } diff --git a/acvm-repo/acir/tests/test_program_serialization.rs b/acvm-repo/acir/tests/test_program_serialization.rs index 2a25129df48..ff69ba34437 100644 --- a/acvm-repo/acir/tests/test_program_serialization.rs +++ b/acvm-repo/acir/tests/test_program_serialization.rs @@ -42,8 +42,7 @@ fn addition_circuit() { ..Circuit::default() }; - let mut bytes = Vec::new(); - circuit.write(&mut bytes).unwrap(); + let bytes = Circuit::serialize_circuit(&circuit); let expected_serialization: Vec = vec![ 31, 139, 8, 0, 0, 0, 0, 0, 0, 255, 173, 144, 187, 13, 192, 32, 12, 68, 249, 100, 32, 27, @@ -73,8 +72,7 @@ fn fixed_base_scalar_mul_circuit() { ..Circuit::default() }; - let mut bytes = Vec::new(); - circuit.write(&mut bytes).unwrap(); + let bytes = Circuit::serialize_circuit(&circuit); let expected_serialization: Vec = vec![ 31, 139, 8, 0, 0, 0, 0, 0, 0, 255, 77, 138, 91, 10, 0, 48, 12, 194, 178, 215, 215, 46, 189, @@ -101,8 +99,7 @@ fn pedersen_circuit() { ..Circuit::default() }; - let mut bytes = Vec::new(); - circuit.write(&mut bytes).unwrap(); + let bytes = Circuit::serialize_circuit(&circuit); let expected_serialization: Vec = vec![ 31, 139, 8, 0, 0, 0, 0, 0, 0, 255, 93, 138, 9, 10, 0, 64, 8, 2, 103, 15, 250, 255, 139, @@ -143,8 +140,7 @@ fn schnorr_verify_circuit() { ..Circuit::default() }; - let mut bytes = Vec::new(); - circuit.write(&mut bytes).unwrap(); + let bytes = Circuit::serialize_circuit(&circuit); let expected_serialization: Vec = vec![ 31, 139, 8, 0, 0, 0, 0, 0, 0, 255, 77, 210, 87, 78, 2, 1, 20, 134, 209, 177, 247, 222, 123, @@ -197,8 +193,7 @@ fn simple_brillig_foreign_call() { ..Circuit::default() }; - let mut bytes = Vec::new(); - circuit.write(&mut bytes).unwrap(); + let bytes = Circuit::serialize_circuit(&circuit); let expected_serialization: Vec = vec![ 31, 139, 8, 0, 0, 0, 0, 0, 0, 255, 173, 143, 49, 10, 64, 33, 12, 67, 99, 63, 124, 60, 142, @@ -271,8 +266,7 @@ fn complex_brillig_foreign_call() { ..Circuit::default() }; - let mut bytes = Vec::new(); - circuit.write(&mut bytes).unwrap(); + let bytes = Circuit::serialize_circuit(&circuit); let expected_serialization: Vec = vec![ 31, 139, 8, 0, 0, 0, 0, 0, 0, 255, 213, 83, 219, 10, 128, 48, 8, 117, 174, 139, 159, 179, @@ -310,8 +304,7 @@ fn memory_op_circuit() { return_values: PublicInputs([Witness(4)].into()), ..Circuit::default() }; - let mut bytes = Vec::new(); - circuit.write(&mut bytes).unwrap(); + let bytes = Circuit::serialize_circuit(&circuit); let expected_serialization: Vec = vec![ 31, 139, 8, 0, 0, 0, 0, 0, 0, 255, 213, 146, 49, 14, 0, 32, 8, 3, 139, 192, 127, 240, 7, diff --git a/acvm-repo/acvm/src/pwg/mod.rs b/acvm-repo/acvm/src/pwg/mod.rs index 1022ad13800..6016d0d1f3e 100644 --- a/acvm-repo/acvm/src/pwg/mod.rs +++ b/acvm-repo/acvm/src/pwg/mod.rs @@ -193,6 +193,10 @@ impl<'a, B: BlackBoxFunctionSolver> ACVM<'a, B> { status } + pub fn get_status(&self) -> &ACVMStatus { + &self.status + } + /// Sets the VM status to [ACVMStatus::Failure] using the provided `error`. /// Returns the new status. fn fail(&mut self, error: OpcodeResolutionError) -> ACVMStatus { diff --git a/acvm-repo/acvm_js/Cargo.toml b/acvm-repo/acvm_js/Cargo.toml index b63b0b7be6e..c224b029726 100644 --- a/acvm-repo/acvm_js/Cargo.toml +++ b/acvm-repo/acvm_js/Cargo.toml @@ -21,22 +21,23 @@ cfg-if = "1.0.0" [target.'cfg(target_arch = "wasm32")'.dependencies] acvm = { path = "../acvm", default-features = false } barretenberg_blackbox_solver = { path = "../barretenberg_blackbox_solver", default-features = false } -wasm-bindgen = { version = "0.2.86", features = ["serde-serialize"] } -wasm-bindgen-futures = "0.4.36" +wasm-bindgen.workspace = true +wasm-bindgen-futures.workspace = true +console_error_panic_hook.workspace = true +gloo-utils.workspace = true +js-sys.workspace = true + serde = { version = "1.0.136", features = ["derive"] } log = "0.4.17" wasm-logger = "0.2.0" -console_error_panic_hook = "0.1.7" -gloo-utils = { version = "0.1", features = ["serde"] } -js-sys.workspace = true const-str = "0.5.5" [build-dependencies] -build-data = "0.1.3" +build-data.workspace = true pkg-config = "0.3" [dev-dependencies] -wasm-bindgen-test = "0.3.36" +wasm-bindgen-test.workspace = true [features] default = ["bn254"] diff --git a/acvm-repo/acvm_js/src/execute.rs b/acvm-repo/acvm_js/src/execute.rs index ebbfc4297c3..81e2a11ed5a 100644 --- a/acvm-repo/acvm_js/src/execute.rs +++ b/acvm-repo/acvm_js/src/execute.rs @@ -64,7 +64,8 @@ pub async fn execute_circuit_with_black_box_solver( foreign_call_handler: ForeignCallHandler, ) -> Result { console_error_panic_hook::set_once(); - let circuit: Circuit = Circuit::read(&*circuit).expect("Failed to deserialize circuit"); + let circuit: Circuit = + Circuit::deserialize_circuit(&circuit).expect("Failed to deserialize circuit"); let mut acvm = ACVM::new(&solver.0, &circuit.opcodes, initial_witness.into()); diff --git a/acvm-repo/acvm_js/src/public_witness.rs b/acvm-repo/acvm_js/src/public_witness.rs index 46e4b788772..8dc66c435b3 100644 --- a/acvm-repo/acvm_js/src/public_witness.rs +++ b/acvm-repo/acvm_js/src/public_witness.rs @@ -30,7 +30,8 @@ pub fn get_return_witness( witness_map: JsWitnessMap, ) -> Result { console_error_panic_hook::set_once(); - let circuit: Circuit = Circuit::read(&*circuit).expect("Failed to deserialize circuit"); + let circuit: Circuit = + Circuit::deserialize_circuit(&circuit).expect("Failed to deserialize circuit"); let witness_map = WitnessMap::from(witness_map); let return_witness = @@ -50,7 +51,8 @@ pub fn get_public_parameters_witness( solved_witness: JsWitnessMap, ) -> Result { console_error_panic_hook::set_once(); - let circuit: Circuit = Circuit::read(&*circuit).expect("Failed to deserialize circuit"); + let circuit: Circuit = + Circuit::deserialize_circuit(&circuit).expect("Failed to deserialize circuit"); let witness_map = WitnessMap::from(solved_witness); let public_params_witness = @@ -70,7 +72,8 @@ pub fn get_public_witness( solved_witness: JsWitnessMap, ) -> Result { console_error_panic_hook::set_once(); - let circuit: Circuit = Circuit::read(&*circuit).expect("Failed to deserialize circuit"); + let circuit: Circuit = + Circuit::deserialize_circuit(&circuit).expect("Failed to deserialize circuit"); let witness_map = WitnessMap::from(solved_witness); let public_witness = diff --git a/acvm-repo/barretenberg_blackbox_solver/Cargo.toml b/acvm-repo/barretenberg_blackbox_solver/Cargo.toml index c189c11cd10..2f81a52db74 100644 --- a/acvm-repo/barretenberg_blackbox_solver/Cargo.toml +++ b/acvm-repo/barretenberg_blackbox_solver/Cargo.toml @@ -34,12 +34,12 @@ wasmer = { version = "3.3", default-features = false, features = [ "js-default", ] } -getrandom = { version = "0.2", features = ["js"] } -wasm-bindgen-futures = "0.4.36" +getrandom = { workspace = true, features = ["js"] } +wasm-bindgen-futures.workspace = true js-sys.workspace = true [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -getrandom = "0.2" +getrandom.workspace = true wasmer = "3.3" [build-dependencies] diff --git a/acvm-repo/barretenberg_blackbox_solver/src/wasm/pedersen.rs b/acvm-repo/barretenberg_blackbox_solver/src/wasm/pedersen.rs index c19554eb6bc..c816e5b4d1b 100644 --- a/acvm-repo/barretenberg_blackbox_solver/src/wasm/pedersen.rs +++ b/acvm-repo/barretenberg_blackbox_solver/src/wasm/pedersen.rs @@ -57,8 +57,7 @@ impl Pedersen for Barretenberg { #[test] fn pedersen_hash_to_point() -> Result<(), Error> { let barretenberg = Barretenberg::new(); - let (x, y) = barretenberg - .encrypt(vec![FieldElement::from(1 as u128), FieldElement::from(1 as u128)], 1)?; + let (x, y) = barretenberg.encrypt(vec![FieldElement::one(), FieldElement::one()], 1)?; let expected_x = FieldElement::from_hex( "0x12afb43195f5c621d1d2cabb5f629707095c5307fd4185a663d4e80bb083e878", ) diff --git a/compiler/integration-tests/circuits/main/Nargo.toml b/compiler/integration-tests/circuits/main/Nargo.toml index 664e817cc84..cc5a0a357fa 100644 --- a/compiler/integration-tests/circuits/main/Nargo.toml +++ b/compiler/integration-tests/circuits/main/Nargo.toml @@ -2,6 +2,4 @@ name = "main" type = "bin" authors = [""] -compiler_version = "0.9.0" - [dependencies] diff --git a/compiler/integration-tests/circuits/recursion/Nargo.toml b/compiler/integration-tests/circuits/recursion/Nargo.toml index 5469c07c7de..276ba1b34e0 100644 --- a/compiler/integration-tests/circuits/recursion/Nargo.toml +++ b/compiler/integration-tests/circuits/recursion/Nargo.toml @@ -2,6 +2,4 @@ name = "recursion" type = "bin" authors = [""] -compiler_version = "0.9.0" - [dependencies] diff --git a/compiler/integration-tests/circuits/recursion/src/main.nr b/compiler/integration-tests/circuits/recursion/src/main.nr index ffa3ccef90e..bc1f3e76d1d 100644 --- a/compiler/integration-tests/circuits/recursion/src/main.nr +++ b/compiler/integration-tests/circuits/recursion/src/main.nr @@ -6,15 +6,9 @@ fn main( public_inputs : [Field; 1], key_hash : Field, input_aggregation_object : [Field; 16], -) -> pub [Field;16]{ +) -> pub [Field; 16] { let vk : [Field] = verification_key; let p : [Field] = proof; let pi : [Field] = public_inputs; - std::verify_proof( - vk, - p, - pi, - key_hash, - input_aggregation_object - ) + std::verify_proof(vk, p, pi, key_hash, input_aggregation_object) } diff --git a/compiler/integration-tests/test/browser/compile_prove_verify.test.ts b/compiler/integration-tests/test/browser/compile_prove_verify.test.ts index f2063c5e4b0..95a1aa502ad 100644 --- a/compiler/integration-tests/test/browser/compile_prove_verify.test.ts +++ b/compiler/integration-tests/test/browser/compile_prove_verify.test.ts @@ -3,7 +3,7 @@ import { Logger } from 'tslog'; import * as TOML from 'smol-toml'; import { initializeResolver } from '@noir-lang/source-resolver'; -import newCompiler, { compile, init_log_level as compilerLogLevel } from '@noir-lang/noir_wasm'; +import newCompiler, { CompiledProgram, compile, init_log_level as compilerLogLevel } from '@noir-lang/noir_wasm'; import { Noir } from '@noir-lang/noir_js'; import { InputMap } from '@noir-lang/noirc_abi'; import { BarretenbergBackend } from '@noir-lang/backend_barretenberg'; @@ -32,7 +32,7 @@ const suite = Mocha.Suite.create(mocha.suite, 'Noir end to end test'); suite.timeout(60 * 20e3); //20mins -async function getCircuit(noirSource: string) { +function getCircuit(noirSource: string): CompiledProgram { // eslint-disable-next-line @typescript-eslint/no-unused-vars initializeResolver((id: string) => { logger.debug('source-resolver: resolving:', id); @@ -40,7 +40,12 @@ async function getCircuit(noirSource: string) { }); // We're ignoring this in the resolver but pass in something sensible. - return compile('/main.nr'); + const result = compile('/main.nr'); + if (!('program' in result)) { + throw new Error('Compilation failed'); + } + + return result.program; } test_cases.forEach((testInfo) => { @@ -51,11 +56,11 @@ test_cases.forEach((testInfo) => { const noir_source = await getFile(`${base_relative_path}/${test_case}/src/main.nr`); - let noir_program; + let noir_program: CompiledProgram; try { - noir_program = await getCircuit(noir_source); + noir_program = getCircuit(noir_source); - expect(await noir_program, 'Compile output ').to.be.an('object'); + expect(noir_program, 'Compile output ').to.be.an('object'); } catch (e) { expect(e, 'Compilation Step').to.not.be.an('error'); throw e; diff --git a/compiler/integration-tests/test/browser/recursion.test.ts b/compiler/integration-tests/test/browser/recursion.test.ts index 6a5592bca67..dbf74882654 100644 --- a/compiler/integration-tests/test/browser/recursion.test.ts +++ b/compiler/integration-tests/test/browser/recursion.test.ts @@ -3,7 +3,7 @@ import { expect } from '@esm-bundle/chai'; import { TEST_LOG_LEVEL } from '../environment.js'; import { Logger } from 'tslog'; import { initializeResolver } from '@noir-lang/source-resolver'; -import newCompiler, { compile, init_log_level as compilerLogLevel } from '@noir-lang/noir_wasm'; +import newCompiler, { CompiledProgram, compile, init_log_level as compilerLogLevel } from '@noir-lang/noir_wasm'; import { acvm, abi, Noir } from '@noir-lang/noir_js'; import * as TOML from 'smol-toml'; @@ -26,7 +26,7 @@ const base_relative_path = '../../../../..'; const circuit_main = 'compiler/integration-tests/circuits/main'; const circuit_recursion = 'compiler/integration-tests/circuits/recursion'; -async function getCircuit(noirSource: string) { +function getCircuit(noirSource: string): CompiledProgram { // eslint-disable-next-line @typescript-eslint/no-unused-vars initializeResolver((id: string) => { logger.debug('source-resolver: resolving:', id); @@ -34,7 +34,12 @@ async function getCircuit(noirSource: string) { }); // We're ignoring this in the resolver but pass in something sensible. - return compile('./main.nr'); + const result = compile('/main.nr'); + if (!('program' in result)) { + throw new Error('Compilation failed'); + } + + return result.program; } describe('It compiles noir program code, receiving circuit bytes and abi object.', () => { @@ -50,7 +55,7 @@ describe('It compiles noir program code, receiving circuit bytes and abi object. }); it('Should generate valid inner proof for correct input, then verify proof within a proof', async () => { - const main_program = await getCircuit(circuit_main_source); + const main_program = getCircuit(circuit_main_source); const main_inputs: InputMap = TOML.parse(circuit_main_toml) as InputMap; const main_backend = new BarretenbergBackend(main_program); diff --git a/compiler/integration-tests/test/node/smart_contract_verifier.test.ts b/compiler/integration-tests/test/node/smart_contract_verifier.test.ts index 038c692220f..738bc2df8dd 100644 --- a/compiler/integration-tests/test/node/smart_contract_verifier.test.ts +++ b/compiler/integration-tests/test/node/smart_contract_verifier.test.ts @@ -33,7 +33,12 @@ test_cases.forEach((testInfo) => { const noir_source_path = resolve(`${base_relative_path}/${test_case}/src/main.nr`); - const noir_program = compile(noir_source_path); + const compileResult = compile(noir_source_path); + if (!('program' in compileResult)) { + throw new Error('Compilation failed'); + } + + const noir_program = compileResult.program; const backend = new BarretenbergBackend(noir_program); const program = new Noir(noir_program, backend); diff --git a/compiler/noirc_driver/Cargo.toml b/compiler/noirc_driver/Cargo.toml index f1c120e1687..09044b39323 100644 --- a/compiler/noirc_driver/Cargo.toml +++ b/compiler/noirc_driver/Cargo.toml @@ -8,7 +8,7 @@ license.workspace = true # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [build-dependencies] -build-data = "0.1.3" +build-data.workspace = true [dependencies] clap.workspace = true @@ -17,7 +17,7 @@ noirc_frontend.workspace = true noirc_evaluator.workspace = true noirc_abi.workspace = true acvm.workspace = true +iter-extended.workspace = true fm.workspace = true serde.workspace = true -base64.workspace = true fxhash.workspace = true diff --git a/compiler/noirc_driver/src/contract.rs b/compiler/noirc_driver/src/contract.rs index da097d4cb86..ae55d239cf3 100644 --- a/compiler/noirc_driver/src/contract.rs +++ b/compiler/noirc_driver/src/contract.rs @@ -5,9 +5,9 @@ use acvm::acir::circuit::Circuit; use fm::FileId; use noirc_abi::{Abi, ContractEvent}; use noirc_errors::debug_info::DebugInfo; +use noirc_evaluator::errors::SsaReport; use super::debug::DebugFile; -use crate::program::{deserialize_circuit, serialize_circuit}; /// Describes the types of smart contract functions that are allowed. /// Unlike the similar enum in noirc_frontend, 'open' and 'unconstrained' @@ -42,6 +42,7 @@ pub struct CompiledContract { pub events: Vec, pub file_map: BTreeMap, + pub warnings: Vec, } /// Each function in the contract will be compiled @@ -60,7 +61,10 @@ pub struct ContractFunction { pub abi: Abi, - #[serde(serialize_with = "serialize_circuit", deserialize_with = "deserialize_circuit")] + #[serde( + serialize_with = "Circuit::serialize_circuit_base64", + deserialize_with = "Circuit::deserialize_circuit_base64" + )] pub bytecode: Circuit, pub debug: DebugInfo, diff --git a/compiler/noirc_driver/src/lib.rs b/compiler/noirc_driver/src/lib.rs index f8908efc596..ec7a5091ffd 100644 --- a/compiler/noirc_driver/src/lib.rs +++ b/compiler/noirc_driver/src/lib.rs @@ -4,8 +4,8 @@ #![warn(clippy::semicolon_if_nothing_returned)] use clap::Args; -use debug::filter_relevant_files; use fm::FileId; +use iter_extended::vecmap; use noirc_abi::{AbiParameter, AbiType, ContractEvent}; use noirc_errors::{CustomDiagnostic, FileDiagnostic}; use noirc_evaluator::errors::RuntimeError; @@ -22,6 +22,8 @@ mod contract; mod debug; mod program; +use debug::filter_relevant_files; + pub use contract::{CompiledContract, ContractFunction, ContractFunctionType}; pub use debug::DebugFile; pub use program::CompiledProgram; @@ -68,13 +70,6 @@ pub type ErrorsAndWarnings = Vec; /// Helper type for connecting a compilation artifact to the errors or warnings which were produced during compilation. pub type CompilationResult = Result<(T, Warnings), ErrorsAndWarnings>; -// This is here for backwards compatibility -// with the restricted version which only uses one file -pub fn compile_file(context: &mut Context, root_file: &Path) -> CompilationResult { - let crate_id = prepare_crate(context, root_file); - compile_main(context, crate_id, &CompileOptions::default(), None, true) -} - /// Adds the file from the file system at `Path` to the crate graph as a root file pub fn prepare_crate(context: &mut Context, file_name: &Path) -> CrateId { let path_to_std_lib_file = Path::new(STD_CRATE_NAME).join("lib.nr"); @@ -164,22 +159,24 @@ pub fn compile_main( cached_program: Option, force_compile: bool, ) -> CompilationResult { - let (_, warnings) = check_crate(context, crate_id, options.deny_warnings)?; + let (_, mut warnings) = check_crate(context, crate_id, options.deny_warnings)?; - let main = match context.get_main_function(&crate_id) { - Some(m) => m, - None => { - // TODO(#2155): This error might be a better to exist in Nargo - let err = CustomDiagnostic::from_message( - "cannot compile crate into a program as it does not contain a `main` function", - ) - .in_file(FileId::default()); - return Err(vec![err]); - } - }; + let main = context.get_main_function(&crate_id).ok_or_else(|| { + // TODO(#2155): This error might be a better to exist in Nargo + let err = CustomDiagnostic::from_message( + "cannot compile crate into a program as it does not contain a `main` function", + ) + .in_file(FileId::default()); + vec![err] + })?; let compiled_program = compile_no_check(context, options, main, cached_program, force_compile) .map_err(FileDiagnostic::from)?; + let compilation_warnings = vecmap(compiled_program.warnings.clone(), FileDiagnostic::from); + if options.deny_warnings && !compilation_warnings.is_empty() { + return Err(compilation_warnings); + } + warnings.extend(compilation_warnings); if options.print_acir { println!("Compiled ACIR for main (unoptimized):"); @@ -259,6 +256,7 @@ fn compile_contract_inner( ) -> Result { let mut functions = Vec::new(); let mut errors = Vec::new(); + let mut warnings = Vec::new(); for contract_function in &contract.functions { let function_id = contract_function.function_id; let is_entry_point = contract_function.is_entry_point; @@ -280,6 +278,7 @@ fn compile_contract_inner( continue; } }; + warnings.extend(function.warnings); let modifiers = context.def_interner.function_modifiers(&function_id); let func_type = modifiers .contract_function_type @@ -315,17 +314,16 @@ fn compile_contract_inner( functions, file_map, noir_version: NOIR_ARTIFACT_VERSION_STRING.to_string(), + warnings, }) } else { Err(errors) } } -/// Compile the current crate. Assumes self.check_crate is called beforehand! +/// Compile the current crate using `main_function` as the entrypoint. /// -/// This function also assumes all errors in experimental_create_circuit and create_circuit -/// are not warnings. -#[allow(deprecated)] +/// This function assumes [`check_crate`] is called beforehand. pub fn compile_no_check( context: &Context, options: &CompileOptions, @@ -336,18 +334,18 @@ pub fn compile_no_check( let program = monomorphize(main_function, &context.def_interner); let hash = fxhash::hash64(&program); + let hashes_match = cached_program.as_ref().map_or(false, |program| program.hash == hash); // If user has specified that they want to see intermediate steps printed then we should // force compilation even if the program hasn't changed. - if !(force_compile || options.print_acir || options.show_brillig || options.show_ssa) { - if let Some(cached_program) = cached_program { - if hash == cached_program.hash { - return Ok(cached_program); - } - } + let force_compile = + force_compile || options.print_acir || options.show_brillig || options.show_ssa; + + if !force_compile && hashes_match { + return Ok(cached_program.expect("cache must exist for hashes to match")); } - let (circuit, debug, abi) = + let (circuit, debug, abi, warnings) = create_circuit(context, program, options.show_ssa, options.show_brillig)?; let file_map = filter_relevant_files(&[debug.clone()], &context.file_manager); @@ -359,5 +357,6 @@ pub fn compile_no_check( abi, file_map, noir_version: NOIR_ARTIFACT_VERSION_STRING.to_string(), + warnings, }) } diff --git a/compiler/noirc_driver/src/program.rs b/compiler/noirc_driver/src/program.rs index fe991567180..8d509d3bf68 100644 --- a/compiler/noirc_driver/src/program.rs +++ b/compiler/noirc_driver/src/program.rs @@ -3,10 +3,9 @@ use std::collections::BTreeMap; use acvm::acir::circuit::Circuit; use fm::FileId; -use base64::Engine; use noirc_errors::debug_info::DebugInfo; -use serde::{de::Error as DeserializationError, ser::Error as SerializationError}; -use serde::{Deserialize, Deserializer, Serialize, Serializer}; +use noirc_evaluator::errors::SsaReport; +use serde::{Deserialize, Serialize}; use super::debug::DebugFile; @@ -19,31 +18,13 @@ pub struct CompiledProgram { /// Used to short-circuit compilation in the case of the source code not changing since the last compilation. pub hash: u64, - #[serde(serialize_with = "serialize_circuit", deserialize_with = "deserialize_circuit")] + #[serde( + serialize_with = "Circuit::serialize_circuit_base64", + deserialize_with = "Circuit::deserialize_circuit_base64" + )] pub circuit: Circuit, pub abi: noirc_abi::Abi, pub debug: DebugInfo, pub file_map: BTreeMap, -} - -pub(crate) fn serialize_circuit(circuit: &Circuit, s: S) -> Result -where - S: Serializer, -{ - let mut circuit_bytes: Vec = Vec::new(); - circuit.write(&mut circuit_bytes).map_err(S::Error::custom)?; - - let encoded_b64 = base64::engine::general_purpose::STANDARD.encode(circuit_bytes); - s.serialize_str(&encoded_b64) -} - -pub(crate) fn deserialize_circuit<'de, D>(deserializer: D) -> Result -where - D: Deserializer<'de>, -{ - let bytecode_b64: String = serde::Deserialize::deserialize(deserializer)?; - let circuit_bytes = - base64::engine::general_purpose::STANDARD.decode(bytecode_b64).map_err(D::Error::custom)?; - let circuit = Circuit::read(&*circuit_bytes).map_err(D::Error::custom)?; - Ok(circuit) + pub warnings: Vec, } diff --git a/compiler/noirc_evaluator/Cargo.toml b/compiler/noirc_evaluator/Cargo.toml index d70c9d3179e..c9f5f28478b 100644 --- a/compiler/noirc_evaluator/Cargo.toml +++ b/compiler/noirc_evaluator/Cargo.toml @@ -16,4 +16,5 @@ fxhash.workspace = true iter-extended.workspace = true thiserror.workspace = true num-bigint = "0.4" -im = "15.1" +im = { version = "15.1", features = ["serde"] } +serde.workspace = true diff --git a/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_block.rs b/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_block.rs index 4b83d21a702..18fd822b07d 100644 --- a/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_block.rs +++ b/compiler/noirc_evaluator/src/brillig/brillig_gen/brillig_block.rs @@ -18,6 +18,7 @@ use acvm::brillig_vm::brillig::HeapVector; use acvm::FieldElement; use fxhash::{FxHashMap as HashMap, FxHashSet as HashSet}; use iter_extended::vecmap; +use num_bigint::BigUint; use super::brillig_black_box::convert_black_box_call; use super::brillig_block_variables::BlockVariables; @@ -554,6 +555,25 @@ impl<'block> BrilligBlock<'block> { value_variable, ); } + Instruction::RangeCheck { value, max_bit_size, assert_message } => { + let left = self.convert_ssa_register_value(*value, dfg); + let max = BigUint::from(2_u128).pow(*max_bit_size); + let right = self.brillig_context.allocate_register(); + self.brillig_context.const_instruction( + right, + FieldElement::from_be_bytes_reduce(&max.to_bytes_be()).into(), + ); + + let brillig_binary_op = BrilligBinaryOp::Integer { + op: BinaryIntOp::LessThan, + bit_size: max_bit_size + 1, + }; + let condition = self.brillig_context.allocate_register(); + self.brillig_context.binary_instruction(left, right, condition, brillig_binary_op); + self.brillig_context.constrain_instruction(condition, assert_message.clone()); + self.brillig_context.deallocate_register(condition); + self.brillig_context.deallocate_register(right); + } _ => todo!("ICE: Instruction not supported {instruction:?}"), }; diff --git a/compiler/noirc_evaluator/src/errors.rs b/compiler/noirc_evaluator/src/errors.rs index 58d13c0affd..2429ca9e194 100644 --- a/compiler/noirc_evaluator/src/errors.rs +++ b/compiler/noirc_evaluator/src/errors.rs @@ -13,6 +13,7 @@ use noirc_errors::{CustomDiagnostic as Diagnostic, FileDiagnostic}; use thiserror::Error; use crate::ssa::ir::{dfg::CallStack, types::NumericType}; +use serde::{Deserialize, Serialize}; #[derive(Debug, PartialEq, Eq, Clone, Error)] pub enum RuntimeError { @@ -53,6 +54,37 @@ fn format_failed_constraint(message: &Option) -> String { } } +#[derive(Debug, Clone, Serialize, Deserialize)] +pub enum SsaReport { + Warning(InternalWarning), +} + +impl From for FileDiagnostic { + fn from(error: SsaReport) -> FileDiagnostic { + match error { + SsaReport::Warning(warning) => { + let InternalWarning::ReturnConstant { ref call_stack } = warning; + let call_stack = vecmap(call_stack, |location| *location); + let file_id = call_stack.last().map(|location| location.file).unwrap_or_default(); + let message = warning.to_string(); + let location = call_stack.last().expect("Expected RuntimeError to have a location"); + let diagnostic = Diagnostic::simple_warning( + message, + "constant value".to_string(), + location.span, + ); + diagnostic.in_file(file_id).with_call_stack(call_stack) + } + } + } +} + +#[derive(Debug, PartialEq, Eq, Clone, Error, Serialize, Deserialize)] +pub enum InternalWarning { + #[error("Returning a constant value is not allowed")] + ReturnConstant { call_stack: CallStack }, +} + #[derive(Debug, PartialEq, Eq, Clone, Error)] pub enum InternalError { #[error("ICE: Both expressions should have degree<=1")] @@ -69,8 +101,6 @@ pub enum InternalError { UndeclaredAcirVar { call_stack: CallStack }, #[error("ICE: Expected {expected:?}, found {found:?}")] UnExpected { expected: String, found: String, call_stack: CallStack }, - #[error("Returning a constant value is not allowed")] - ReturnConstant { call_stack: CallStack }, } impl RuntimeError { @@ -83,8 +113,7 @@ impl RuntimeError { | InternalError::MissingArg { call_stack, .. } | InternalError::NotAConstant { call_stack, .. } | InternalError::UndeclaredAcirVar { call_stack } - | InternalError::UnExpected { call_stack, .. } - | InternalError::ReturnConstant { call_stack, .. }, + | InternalError::UnExpected { call_stack, .. }, ) | RuntimeError::FailedConstraint { call_stack, .. } | RuntimeError::IndexOutOfBounds { call_stack, .. } @@ -111,12 +140,6 @@ impl From for FileDiagnostic { impl RuntimeError { fn into_diagnostic(self) -> Diagnostic { match self { - RuntimeError::InternalError(InternalError::ReturnConstant { ref call_stack }) => { - let message = self.to_string(); - let location = - call_stack.back().expect("Expected RuntimeError to have a location"); - Diagnostic::simple_error(message, "constant value".to_string(), location.span) - } RuntimeError::InternalError(cause) => { Diagnostic::simple_error( "Internal Consistency Evaluators Errors: \n diff --git a/compiler/noirc_evaluator/src/ssa.rs b/compiler/noirc_evaluator/src/ssa.rs index 7cf51a4f0b3..ff13878e129 100644 --- a/compiler/noirc_evaluator/src/ssa.rs +++ b/compiler/noirc_evaluator/src/ssa.rs @@ -9,7 +9,7 @@ use std::collections::BTreeSet; -use crate::errors::RuntimeError; +use crate::errors::{RuntimeError, SsaReport}; use acvm::acir::{ circuit::{Circuit, PublicInputs}, native_types::Witness, @@ -72,7 +72,7 @@ pub fn create_circuit( program: Program, enable_ssa_logging: bool, enable_brillig_logging: bool, -) -> Result<(Circuit, DebugInfo, Abi), RuntimeError> { +) -> Result<(Circuit, DebugInfo, Abi, Vec), RuntimeError> { let func_sig = program.main_function_signature.clone(); let mut generated_acir = optimize_into_acir(program, enable_ssa_logging, enable_brillig_logging)?; @@ -83,6 +83,7 @@ pub fn create_circuit( locations, input_witnesses, assert_messages, + warnings, .. } = generated_acir; @@ -119,7 +120,7 @@ pub fn create_circuit( let (optimized_circuit, transformation_map) = acvm::compiler::optimize(circuit); debug_info.update_acir(transformation_map); - Ok((optimized_circuit, debug_info, abi)) + Ok((optimized_circuit, debug_info, abi, warnings)) } // This is just a convenience object to bundle the ssa with `print_ssa_passes` for debug printing. diff --git a/compiler/noirc_evaluator/src/ssa/acir_gen/acir_ir/acir_variable.rs b/compiler/noirc_evaluator/src/ssa/acir_gen/acir_ir/acir_variable.rs index f54ddd9f4d4..908189ad785 100644 --- a/compiler/noirc_evaluator/src/ssa/acir_gen/acir_ir/acir_variable.rs +++ b/compiler/noirc_evaluator/src/ssa/acir_gen/acir_ir/acir_variable.rs @@ -1,7 +1,7 @@ use super::generated_acir::GeneratedAcir; use crate::brillig::brillig_gen::brillig_directive; use crate::brillig::brillig_ir::artifact::GeneratedBrillig; -use crate::errors::{InternalError, RuntimeError}; +use crate::errors::{InternalError, RuntimeError, SsaReport}; use crate::ssa::acir_gen::{AcirDynamicArray, AcirValue}; use crate::ssa::ir::dfg::CallStack; use crate::ssa::ir::types::Type as SsaType; @@ -656,7 +656,11 @@ impl AcirContext { let remainder_var = r_value.into_var()?; // Constrain `q < 2^{max_q_bits}`. - self.range_constrain_var(quotient_var, &NumericType::Unsigned { bit_size: max_q_bits })?; + self.range_constrain_var( + quotient_var, + &NumericType::Unsigned { bit_size: max_q_bits }, + None, + )?; // Constrain `r < 2^{max_rhs_bits}`. // @@ -664,7 +668,11 @@ impl AcirContext { // In the case where `rhs` isn't a power of 2 then this range constraint is required // as the bound constraint creates a new witness. // This opcode will be optimized out if it is redundant so we always add it for safety. - self.range_constrain_var(remainder_var, &NumericType::Unsigned { bit_size: max_rhs_bits })?; + self.range_constrain_var( + remainder_var, + &NumericType::Unsigned { bit_size: max_rhs_bits }, + None, + )?; // Constrain `r < rhs`. self.bound_constraint_with_offset(remainder_var, rhs, predicate, max_rhs_bits)?; @@ -768,12 +776,12 @@ impl AcirContext { let r_var = self.add_constant(r.into()); let aor = self.add_var(lhs_offset, r_var)?; // lhs_offset<=rhs_offset <=> lhs_offset + r < rhs_offset + r = 2^bit_size <=> witness < 2^bit_size - self.range_constrain_var(aor, &NumericType::Unsigned { bit_size })?; + self.range_constrain_var(aor, &NumericType::Unsigned { bit_size }, None)?; return Ok(()); } // General case: lhs_offset<=rhs <=> rhs-lhs_offset>=0 <=> rhs-lhs_offset is a 'bits' bit integer let sub_expression = self.sub_var(rhs, lhs_offset)?; //rhs-lhs_offset - self.range_constrain_var(sub_expression, &NumericType::Unsigned { bit_size: bits })?; + self.range_constrain_var(sub_expression, &NumericType::Unsigned { bit_size: bits }, None)?; Ok(()) } @@ -874,6 +882,7 @@ impl AcirContext { &mut self, variable: AcirVar, numeric_type: &NumericType, + message: Option, ) -> Result { match numeric_type { NumericType::Signed { bit_size } | NumericType::Unsigned { bit_size } => { @@ -886,6 +895,11 @@ impl AcirContext { } let witness = self.var_to_witness(variable)?; self.acir_ir.range_constraint(witness, *bit_size)?; + if let Some(message) = message { + self.acir_ir + .assert_messages + .insert(self.acir_ir.last_acir_opcode_location(), message); + } } NumericType::NativeField => { // Range constraining a Field is a no-op @@ -1162,8 +1176,9 @@ impl AcirContext { } /// Terminates the context and takes the resulting `GeneratedAcir` - pub(crate) fn finish(mut self, inputs: Vec) -> GeneratedAcir { + pub(crate) fn finish(mut self, inputs: Vec, warnings: Vec) -> GeneratedAcir { self.acir_ir.input_witnesses = vecmap(inputs, Witness); + self.acir_ir.warnings = warnings; self.acir_ir } diff --git a/compiler/noirc_evaluator/src/ssa/acir_gen/acir_ir/generated_acir.rs b/compiler/noirc_evaluator/src/ssa/acir_gen/acir_ir/generated_acir.rs index 221137b9dab..f29d3c9ec05 100644 --- a/compiler/noirc_evaluator/src/ssa/acir_gen/acir_ir/generated_acir.rs +++ b/compiler/noirc_evaluator/src/ssa/acir_gen/acir_ir/generated_acir.rs @@ -4,7 +4,7 @@ use std::collections::BTreeMap; use crate::{ brillig::{brillig_gen::brillig_directive, brillig_ir::artifact::GeneratedBrillig}, - errors::{InternalError, RuntimeError}, + errors::{InternalError, RuntimeError, SsaReport}, ssa::ir::dfg::CallStack, }; @@ -53,6 +53,8 @@ pub(crate) struct GeneratedAcir { /// Correspondence between an opcode index and the error message associated with it. pub(crate) assert_messages: BTreeMap, + + pub(crate) warnings: Vec, } impl GeneratedAcir { diff --git a/compiler/noirc_evaluator/src/ssa/acir_gen/mod.rs b/compiler/noirc_evaluator/src/ssa/acir_gen/mod.rs index bbd53a5a204..35b970f1e06 100644 --- a/compiler/noirc_evaluator/src/ssa/acir_gen/mod.rs +++ b/compiler/noirc_evaluator/src/ssa/acir_gen/mod.rs @@ -23,7 +23,7 @@ use super::{ use crate::brillig::brillig_ir::artifact::GeneratedBrillig; use crate::brillig::brillig_ir::BrilligContext; use crate::brillig::{brillig_gen::brillig_fn::FunctionContext as BrilligFunctionContext, Brillig}; -use crate::errors::{InternalError, RuntimeError}; +use crate::errors::{InternalError, InternalWarning, RuntimeError, SsaReport}; pub(crate) use acir_ir::generated_acir::GeneratedAcir; use acvm::{ acir::{circuit::opcodes::BlockId, native_types::Expression}, @@ -201,9 +201,9 @@ impl Context { self.convert_ssa_instruction(*instruction_id, dfg, ssa, &brillig, last_array_uses)?; } - self.convert_ssa_return(entry_block.unwrap_terminator(), dfg)?; + let warnings = self.convert_ssa_return(entry_block.unwrap_terminator(), dfg)?; - Ok(self.acir_context.finish(input_witness.collect())) + Ok(self.acir_context.finish(input_witness.collect(), warnings)) } fn convert_brillig_main( @@ -240,7 +240,7 @@ impl Context { self.acir_context.return_var(acir_var)?; } - Ok(self.acir_context.finish(witness_inputs)) + Ok(self.acir_context.finish(witness_inputs, Vec::new())) } /// Adds and binds `AcirVar`s for each numeric block parameter or block parameter array element. @@ -347,7 +347,7 @@ impl Context { ) -> Result { let acir_var = self.acir_context.add_variable(); if matches!(numeric_type, NumericType::Signed { .. } | NumericType::Unsigned { .. }) { - self.acir_context.range_constrain_var(acir_var, numeric_type)?; + self.acir_context.range_constrain_var(acir_var, numeric_type, None)?; } Ok(acir_var) } @@ -529,6 +529,14 @@ impl Context { Instruction::Load { .. } => { unreachable!("Expected all load instructions to be removed before acir_gen") } + Instruction::RangeCheck { value, max_bit_size, assert_message } => { + let acir_var = self.convert_numeric_value(*value, dfg)?; + self.acir_context.range_constrain_var( + acir_var, + &NumericType::Unsigned { bit_size: *max_bit_size }, + assert_message.clone(), + )?; + } } self.acir_context.set_call_stack(CallStack::new()); Ok(()) @@ -1247,8 +1255,8 @@ impl Context { &mut self, terminator: &TerminatorInstruction, dfg: &DataFlowGraph, - ) -> Result<(), InternalError> { - let (return_values, _call_stack) = match terminator { + ) -> Result, InternalError> { + let (return_values, call_stack) = match terminator { TerminatorInstruction::Return { return_values, call_stack } => { (return_values, call_stack) } @@ -1258,16 +1266,16 @@ impl Context { // The return value may or may not be an array reference. Calling `flatten_value_list` // will expand the array if there is one. let return_acir_vars = self.flatten_value_list(return_values, dfg); + let mut warnings = Vec::new(); for acir_var in return_acir_vars { - // TODO(Guillaume) -- disabled as it has shown to break - // TODO with important programs. We will add it back once - // TODO we change it to a warning. - // if self.acir_context.is_constant(&acir_var) { - // return Err(InternalError::ReturnConstant { call_stack: call_stack.clone() }); - // } + if self.acir_context.is_constant(&acir_var) { + warnings.push(SsaReport::Warning(InternalWarning::ReturnConstant { + call_stack: call_stack.clone(), + })); + } self.acir_context.return_var(acir_var)?; } - Ok(()) + Ok(warnings) } /// Gets the cached `AcirVar` that was converted from the corresponding `ValueId`. If it does diff --git a/compiler/noirc_evaluator/src/ssa/function_builder/mod.rs b/compiler/noirc_evaluator/src/ssa/function_builder/mod.rs index 155e5a7baba..058f91adacb 100644 --- a/compiler/noirc_evaluator/src/ssa/function_builder/mod.rs +++ b/compiler/noirc_evaluator/src/ssa/function_builder/mod.rs @@ -1,4 +1,4 @@ -use std::borrow::Cow; +use std::{borrow::Cow, rc::Rc}; use acvm::FieldElement; use noirc_errors::Location; @@ -16,7 +16,8 @@ use super::{ basic_block::BasicBlock, dfg::{CallStack, InsertInstructionResult}, function::RuntimeType, - instruction::{InstructionId, Intrinsic}, + instruction::{Endian, InstructionId, Intrinsic}, + types::NumericType, }, ssa_gen::Ssa, }; @@ -259,9 +260,126 @@ impl FunctionBuilder { arguments: Vec, result_types: Vec, ) -> Cow<[ValueId]> { + if let Value::Intrinsic(intrinsic) = &self.current_function.dfg[func] { + if intrinsic == &Intrinsic::WrappingShiftLeft { + let result_type = self.current_function.dfg.type_of_value(arguments[0]); + let bit_size = match result_type { + Type::Numeric(NumericType::Signed { bit_size }) + | Type::Numeric(NumericType::Unsigned { bit_size }) => bit_size, + _ => { + unreachable!("ICE: Truncation attempted on non-integer"); + } + }; + return self + .insert_wrapping_shift_left(arguments[0], arguments[1], bit_size) + .results(); + } + } + self.insert_instruction(Instruction::Call { func, arguments }, Some(result_types)).results() } + /// Insert ssa instructions which computes lhs << rhs by doing lhs*2^rhs + pub(crate) fn insert_shift_left(&mut self, lhs: ValueId, rhs: ValueId) -> ValueId { + let base = self.field_constant(FieldElement::from(2_u128)); + let pow = self.pow(base, rhs); + let typ = self.current_function.dfg.type_of_value(lhs); + let pow = self.insert_cast(pow, typ); + self.insert_binary(lhs, BinaryOp::Mul, pow) + } + + /// Insert ssa instructions which computes lhs << rhs by doing lhs*2^rhs + /// and truncate the result to bit_size + fn insert_wrapping_shift_left( + &mut self, + lhs: ValueId, + rhs: ValueId, + bit_size: u32, + ) -> InsertInstructionResult { + let base = self.field_constant(FieldElement::from(2_u128)); + let typ = self.current_function.dfg.type_of_value(lhs); + let (max_bit, pow) = if let Some(rhs_constant) = + self.current_function.dfg.get_numeric_constant(rhs) + { + // Happy case is that we know precisely by how many bits the the integer will + // increase: lhs_bit_size + rhs + let (rhs_bit_size_pow_2, overflows) = + 2_u32.overflowing_pow(rhs_constant.to_u128() as u32); + if overflows { + let zero = self.numeric_constant(FieldElement::zero(), typ); + return InsertInstructionResult::SimplifiedTo(zero); + } + let pow = self.numeric_constant(FieldElement::from(rhs_bit_size_pow_2 as u128), typ); + (bit_size + (rhs_constant.to_u128() as u32), pow) + } else { + // we use a predicate to nullify the result in case of overflow + let bit_size_var = + self.numeric_constant(FieldElement::from(bit_size as u128), typ.clone()); + let overflow = self.insert_binary(rhs, BinaryOp::Lt, bit_size_var); + let one = self.numeric_constant(FieldElement::one(), Type::unsigned(1)); + let predicate = self.insert_binary(overflow, BinaryOp::Eq, one); + let predicate = self.insert_cast(predicate, typ.clone()); + + let pow = self.pow(base, rhs); + let pow = self.insert_cast(pow, typ); + (FieldElement::max_num_bits(), self.insert_binary(predicate, BinaryOp::Mul, pow)) + }; + + let instruction = Instruction::Binary(Binary { lhs, rhs: pow, operator: BinaryOp::Mul }); + if max_bit <= bit_size { + self.insert_instruction(instruction, None) + } else { + let result = self.insert_instruction(instruction, None).first(); + self.insert_instruction( + Instruction::Truncate { value: result, bit_size, max_bit_size: max_bit }, + None, + ) + } + } + + /// Insert ssa instructions which computes lhs >> rhs by doing lhs/2^rhs + pub(crate) fn insert_shift_right(&mut self, lhs: ValueId, rhs: ValueId) -> ValueId { + let base = self.field_constant(FieldElement::from(2_u128)); + let pow = self.pow(base, rhs); + self.insert_binary(lhs, BinaryOp::Div, pow) + } + + /// Computes lhs^rhs via square&multiply, using the bits decomposition of rhs + /// Pseudo-code of the computation: + /// let mut r = 1; + /// let rhs_bits = to_bits(rhs); + /// for i in 1 .. bit_size + 1 { + /// let r_squared = r * r; + /// let b = rhs_bits[bit_size - i]; + /// r = (r_squared * lhs * b) + (1 - b) * r_squared; + /// } + pub(crate) fn pow(&mut self, lhs: ValueId, rhs: ValueId) -> ValueId { + let typ = self.current_function.dfg.type_of_value(rhs); + if let Type::Numeric(NumericType::Unsigned { bit_size }) = typ { + let to_bits = self.import_intrinsic_id(Intrinsic::ToBits(Endian::Little)); + let length = self.field_constant(FieldElement::from(bit_size as i128)); + let result_types = + vec![Type::field(), Type::Array(Rc::new(vec![Type::bool()]), bit_size as usize)]; + let rhs_bits = self.insert_call(to_bits, vec![rhs, length], result_types); + let rhs_bits = rhs_bits[1]; + let one = self.field_constant(FieldElement::one()); + let mut r = one; + for i in 1..bit_size + 1 { + let r_squared = self.insert_binary(r, BinaryOp::Mul, r); + let a = self.insert_binary(r_squared, BinaryOp::Mul, lhs); + let idx = self.field_constant(FieldElement::from((bit_size - i) as i128)); + let b = self.insert_array_get(rhs_bits, idx, Type::field()); + let r1 = self.insert_binary(a, BinaryOp::Mul, b); + let c = self.insert_binary(one, BinaryOp::Sub, b); + let r2 = self.insert_binary(c, BinaryOp::Mul, r_squared); + r = self.insert_binary(r1, BinaryOp::Add, r2); + } + r + } else { + unreachable!("Value must be unsigned in power operation"); + } + } + /// Insert an instruction to extract an element from an array pub(crate) fn insert_array_get( &mut self, diff --git a/compiler/noirc_evaluator/src/ssa/ir/instruction.rs b/compiler/noirc_evaluator/src/ssa/ir/instruction.rs index badc1e82d50..7eaf557c175 100644 --- a/compiler/noirc_evaluator/src/ssa/ir/instruction.rs +++ b/compiler/noirc_evaluator/src/ssa/ir/instruction.rs @@ -46,6 +46,7 @@ pub(crate) enum Intrinsic { BlackBox(BlackBoxFunc), FromField, AsField, + WrappingShiftLeft, } impl std::fmt::Display for Intrinsic { @@ -68,6 +69,7 @@ impl std::fmt::Display for Intrinsic { Intrinsic::BlackBox(function) => write!(f, "{function}"), Intrinsic::FromField => write!(f, "from_field"), Intrinsic::AsField => write!(f, "as_field"), + Intrinsic::WrappingShiftLeft => write!(f, "wrapping_shift_left"), } } } @@ -92,7 +94,8 @@ impl Intrinsic { | Intrinsic::ToBits(_) | Intrinsic::ToRadix(_) | Intrinsic::FromField - | Intrinsic::AsField => false, + | Intrinsic::AsField + | Intrinsic::WrappingShiftLeft => false, // Some black box functions have side-effects Intrinsic::BlackBox(func) => matches!(func, BlackBoxFunc::RecursiveAggregation), @@ -119,6 +122,7 @@ impl Intrinsic { "to_be_bits" => Some(Intrinsic::ToBits(Endian::Big)), "from_field" => Some(Intrinsic::FromField), "as_field" => Some(Intrinsic::AsField), + "wrapping_shift_left" => Some(Intrinsic::WrappingShiftLeft), other => BlackBoxFunc::lookup(other).map(Intrinsic::BlackBox), } } @@ -150,6 +154,9 @@ pub(crate) enum Instruction { /// Constrains two values to be equal to one another. Constrain(ValueId, ValueId, Option), + /// Range constrain `value` to `max_bit_size` + RangeCheck { value: ValueId, max_bit_size: u32, assert_message: Option }, + /// Performs a function call with a list of its arguments. Call { func: ValueId, arguments: Vec }, @@ -199,7 +206,8 @@ impl Instruction { Instruction::ArraySet { array, .. } => InstructionResultType::Operand(*array), Instruction::Constrain(..) | Instruction::Store { .. } - | Instruction::EnableSideEffects { .. } => InstructionResultType::None, + | Instruction::EnableSideEffects { .. } + | Instruction::RangeCheck { .. } => InstructionResultType::None, Instruction::Load { .. } | Instruction::ArrayGet { .. } | Instruction::Call { .. } => { InstructionResultType::Unknown } @@ -226,9 +234,12 @@ impl Instruction { Truncate { .. } => false, // These either have side-effects or interact with memory - Constrain(..) | EnableSideEffects { .. } | Allocate | Load { .. } | Store { .. } => { - false - } + Constrain(..) + | EnableSideEffects { .. } + | Allocate + | Load { .. } + | Store { .. } + | RangeCheck { .. } => false, Call { func, .. } => match dfg[*func] { Value::Intrinsic(intrinsic) => !intrinsic.has_side_effects(), @@ -259,7 +270,7 @@ impl Instruction { | ArrayGet { .. } | ArraySet { .. } => false, - Constrain(..) | Store { .. } | EnableSideEffects { .. } => true, + Constrain(..) | Store { .. } | EnableSideEffects { .. } | RangeCheck { .. } => true, // Some `Intrinsic`s have side effects so we must check what kind of `Call` this is. Call { func, .. } => match dfg[*func] { @@ -316,6 +327,13 @@ impl Instruction { Instruction::ArraySet { array, index, value } => { Instruction::ArraySet { array: f(*array), index: f(*index), value: f(*value) } } + Instruction::RangeCheck { value, max_bit_size, assert_message } => { + Instruction::RangeCheck { + value: f(*value), + max_bit_size: *max_bit_size, + assert_message: assert_message.clone(), + } + } } } @@ -360,6 +378,9 @@ impl Instruction { Instruction::EnableSideEffects { condition } => { f(*condition); } + Instruction::RangeCheck { value, .. } => { + f(*value); + } } } @@ -457,6 +478,14 @@ impl Instruction { Instruction::Allocate { .. } => None, Instruction::Load { .. } => None, Instruction::Store { .. } => None, + Instruction::RangeCheck { value, max_bit_size, .. } => { + if let Some(numeric_constant) = dfg.get_numeric_constant(*value) { + if numeric_constant.num_bits() < *max_bit_size { + return Remove; + } + } + None + } } } } @@ -480,7 +509,11 @@ fn simplify_cast(value: ValueId, dst_typ: &Type, dfg: &mut DataFlowGraph) -> Sim SimplifiedTo(dfg.make_constant(constant, dst_typ.clone())) } ( - Type::Numeric(NumericType::NativeField | NumericType::Unsigned { .. }), + Type::Numeric( + NumericType::NativeField + | NumericType::Unsigned { .. } + | NumericType::Signed { .. }, + ), Type::Numeric(NumericType::Unsigned { bit_size }), ) => { // Field/Unsigned -> unsigned: truncate @@ -818,6 +851,29 @@ fn eval_constant_binary_op( let result = function(lhs, rhs); truncate(result, *bit_size).into() } + Type::Numeric(NumericType::Signed { bit_size }) => { + let function = operator.get_i128_function(); + + let lhs = truncate(lhs.try_into_u128()?, *bit_size); + let rhs = truncate(rhs.try_into_u128()?, *bit_size); + let l_pos = lhs < 2u128.pow(bit_size - 1); + let r_pos = rhs < 2u128.pow(bit_size - 1); + let lhs = if l_pos { lhs as i128 } else { -((2u128.pow(*bit_size) - lhs) as i128) }; + let rhs = if r_pos { rhs as i128 } else { -((2u128.pow(*bit_size) - rhs) as i128) }; + // The divisor is being truncated into the type of the operand, which can potentially + // lead to the rhs being zero. + // If the rhs of a division is zero, attempting to evaluate the division will cause a compiler panic. + // Thus, we do not evaluate the division in this method, as we want to avoid triggering a panic, + // and the operation should be handled by ACIR generation. + if matches!(operator, BinaryOp::Div | BinaryOp::Mod) && rhs == 0 { + return None; + } + + let result = function(lhs, rhs); + let result = + if result >= 0 { result as u128 } else { (2i128.pow(*bit_size) + result) as u128 }; + truncate(result, *bit_size).into() + } _ => return None, }; @@ -864,6 +920,21 @@ impl BinaryOp { BinaryOp::Lt => |x, y| (x < y) as u128, } } + + fn get_i128_function(self) -> fn(i128, i128) -> i128 { + match self { + BinaryOp::Add => i128::wrapping_add, + BinaryOp::Sub => i128::wrapping_sub, + BinaryOp::Mul => i128::wrapping_mul, + BinaryOp::Div => i128::wrapping_div, + BinaryOp::Mod => i128::wrapping_rem, + BinaryOp::And => |x, y| x & y, + BinaryOp::Or => |x, y| x | y, + BinaryOp::Xor => |x, y| x ^ y, + BinaryOp::Eq => |x, y| (x == y) as i128, + BinaryOp::Lt => |x, y| (x < y) as i128, + } + } } /// Binary Operations allowed in the IR. diff --git a/compiler/noirc_evaluator/src/ssa/ir/instruction/call.rs b/compiler/noirc_evaluator/src/ssa/ir/instruction/call.rs index b07e2df7bd3..da5544d7dc6 100644 --- a/compiler/noirc_evaluator/src/ssa/ir/instruction/call.rs +++ b/compiler/noirc_evaluator/src/ssa/ir/instruction/call.rs @@ -245,6 +245,9 @@ pub(super) fn simplify_call( let instruction = Instruction::Cast(arguments[0], ctrl_typevars.unwrap().remove(0)); SimplifyResult::SimplifiedToInstruction(instruction) } + Intrinsic::WrappingShiftLeft => { + unreachable!("ICE - wrapping shift left should have been proccessed before") + } } } diff --git a/compiler/noirc_evaluator/src/ssa/ir/printer.rs b/compiler/noirc_evaluator/src/ssa/ir/printer.rs index aee8e456b13..51e436643ab 100644 --- a/compiler/noirc_evaluator/src/ssa/ir/printer.rs +++ b/compiler/noirc_evaluator/src/ssa/ir/printer.rs @@ -172,5 +172,8 @@ pub(crate) fn display_instruction( show(*value) ) } + Instruction::RangeCheck { value, max_bit_size, .. } => { + write!(f, "range_check {} to {} bits", show(*value), *max_bit_size,) + } } } diff --git a/compiler/noirc_evaluator/src/ssa/ssa_gen/context.rs b/compiler/noirc_evaluator/src/ssa/ssa_gen/context.rs index 26c818250dc..4cf97acef9a 100644 --- a/compiler/noirc_evaluator/src/ssa/ssa_gen/context.rs +++ b/compiler/noirc_evaluator/src/ssa/ssa_gen/context.rs @@ -13,7 +13,8 @@ use crate::ssa::function_builder::FunctionBuilder; use crate::ssa::ir::dfg::DataFlowGraph; use crate::ssa::ir::function::FunctionId as IrFunctionId; use crate::ssa::ir::function::{Function, RuntimeType}; -use crate::ssa::ir::instruction::{BinaryOp, Endian, Intrinsic}; +use crate::ssa::ir::instruction::BinaryOp; +use crate::ssa::ir::instruction::Instruction; use crate::ssa::ir::map::AtomicCounter; use crate::ssa::ir::types::{NumericType, Type}; use crate::ssa::ir::value::ValueId; @@ -265,50 +266,190 @@ impl<'a> FunctionContext<'a> { Ok(self.builder.numeric_constant(value, typ)) } - /// Insert ssa instructions which computes lhs << rhs by doing lhs*2^rhs - fn insert_shift_left(&mut self, lhs: ValueId, rhs: ValueId) -> ValueId { - let base = self.builder.field_constant(FieldElement::from(2_u128)); - let pow = self.pow(base, rhs); - let typ = self.builder.current_function.dfg.type_of_value(lhs); - let pow = self.builder.insert_cast(pow, typ); - self.builder.insert_binary(lhs, BinaryOp::Mul, pow) - } - - /// Insert ssa instructions which computes lhs >> rhs by doing lhs/2^rhs - fn insert_shift_right(&mut self, lhs: ValueId, rhs: ValueId) -> ValueId { - let base = self.builder.field_constant(FieldElement::from(2_u128)); - let pow = self.pow(base, rhs); - self.builder.insert_binary(lhs, BinaryOp::Div, pow) - } - - /// Computes lhs^rhs via square&multiply, using the bits decomposition of rhs - fn pow(&mut self, lhs: ValueId, rhs: ValueId) -> ValueId { - let typ = self.builder.current_function.dfg.type_of_value(rhs); - if let Type::Numeric(NumericType::Unsigned { bit_size }) = typ { - let to_bits = self.builder.import_intrinsic_id(Intrinsic::ToBits(Endian::Little)); - let length = self.builder.field_constant(FieldElement::from(bit_size as i128)); - let result_types = - vec![Type::field(), Type::Array(Rc::new(vec![Type::bool()]), bit_size as usize)]; - let rhs_bits = self.builder.insert_call(to_bits, vec![rhs, length], result_types); - let rhs_bits = rhs_bits[1]; - let one = self.builder.field_constant(FieldElement::one()); - let mut r = one; - for i in 1..bit_size + 1 { - let r1 = self.builder.insert_binary(r, BinaryOp::Mul, r); - let a = self.builder.insert_binary(r1, BinaryOp::Mul, lhs); - let idx = self.builder.field_constant(FieldElement::from((bit_size - i) as i128)); - let b = self.builder.insert_array_get(rhs_bits, idx, Type::field()); - let r2 = self.builder.insert_binary(a, BinaryOp::Mul, b); - let c = self.builder.insert_binary(one, BinaryOp::Sub, b); - let r3 = self.builder.insert_binary(c, BinaryOp::Mul, r1); - r = self.builder.insert_binary(r2, BinaryOp::Add, r3); - } - r - } else { - unreachable!("Value must be unsigned in power operation"); + /// helper function which add instructions to the block computing the absolute value of the + /// given signed integer input. When the input is negative, we return its two complement, and itself when it is positive. + fn absolute_value_helper(&mut self, input: ValueId, sign: ValueId, bit_size: u32) -> ValueId { + // We compute the absolute value of lhs + let one = self.builder.numeric_constant(FieldElement::one(), Type::bool()); + let bit_width = + self.builder.numeric_constant(FieldElement::from(2_i128.pow(bit_size)), Type::field()); + let sign_not = self.builder.insert_binary(one, BinaryOp::Sub, sign); + let as_field = + self.builder.insert_instruction(Instruction::Cast(input, Type::field()), None).first(); + let sign_field = + self.builder.insert_instruction(Instruction::Cast(sign, Type::field()), None).first(); + let positive_predicate = self.builder.insert_binary(sign_field, BinaryOp::Mul, as_field); + let two_complement = self.builder.insert_binary(bit_width, BinaryOp::Sub, as_field); + let sign_not_field = self + .builder + .insert_instruction(Instruction::Cast(sign_not, Type::field()), None) + .first(); + let negative_predicate = + self.builder.insert_binary(sign_not_field, BinaryOp::Mul, two_complement); + self.builder.insert_binary(positive_predicate, BinaryOp::Add, negative_predicate) + } + + fn check_overflow( + &mut self, + result: ValueId, + lhs: ValueId, + rhs: ValueId, + operator: BinaryOpKind, + location: Location, + ) -> ValueId { + let result_type = self.builder.current_function.dfg.type_of_value(result); + match result_type { + Type::Numeric(NumericType::Signed { bit_size }) => { + match operator { + BinaryOpKind::Add | BinaryOpKind::Subtract => { + // Result is computed modulo the bit size + let mut result = self + .builder + .insert_instruction( + Instruction::Truncate { + value: result, + bit_size, + max_bit_size: bit_size + 1, + }, + None, + ) + .first(); + result = self.builder.insert_cast(result, Type::unsigned(bit_size)); + + self.check_signed_overflow(result, lhs, rhs, operator, bit_size, location); + self.builder.insert_cast(result, result_type) + } + BinaryOpKind::Multiply => { + // Result is computed modulo the bit size + let mut result = + self.builder.insert_cast(result, Type::unsigned(2 * bit_size)); + result = self + .builder + .insert_instruction( + Instruction::Truncate { + value: result, + bit_size, + max_bit_size: 2 * bit_size, + }, + None, + ) + .first(); + + self.check_signed_overflow(result, lhs, rhs, operator, bit_size, location); + self.builder.insert_cast(result, result_type) + } + BinaryOpKind::ShiftLeft => { + unreachable!("shift is not supported for signed integer") + } + _ => unreachable!("operator {} should not overflow", operator), + } + } + Type::Numeric(NumericType::Unsigned { bit_size }) => { + let op_name = match operator { + BinaryOpKind::Add => "add", + BinaryOpKind::Subtract => "subtract", + BinaryOpKind::Multiply => "multiply", + BinaryOpKind::ShiftLeft => "left shift", + _ => unreachable!("operator {} should not overflow", operator), + }; + let message = format!("attempt to {} with overflow", op_name); + let range_constraint = Instruction::RangeCheck { + value: result, + max_bit_size: bit_size, + assert_message: Some(message), + }; + self.builder.set_location(location).insert_instruction(range_constraint, None); + if operator == BinaryOpKind::ShiftLeft { + match result_type { + Type::Numeric(NumericType::Signed { bit_size }) + | Type::Numeric(NumericType::Unsigned { bit_size }) => { + self.builder.insert_truncate(result, bit_size, bit_size + 1) + } + _ => result, + } + } else { + result + } + } + _ => result, } } + fn check_signed_overflow( + &mut self, + result: ValueId, + lhs: ValueId, + rhs: ValueId, + operator: BinaryOpKind, + bit_size: u32, + location: Location, + ) { + let is_sub = operator == BinaryOpKind::Subtract; + let one = self.builder.numeric_constant(FieldElement::one(), Type::bool()); + let half_width = self.builder.numeric_constant( + FieldElement::from(2_i128.pow(bit_size - 1)), + Type::unsigned(bit_size), + ); + // We compute the sign of the operands. The overflow checks for signed integers depends on these signs + let lhs_as_unsigned = self.builder.insert_cast(lhs, Type::unsigned(bit_size)); + let rhs_as_unsigned = self.builder.insert_cast(rhs, Type::unsigned(bit_size)); + let lhs_sign = self.builder.insert_binary(lhs_as_unsigned, BinaryOp::Lt, half_width); + let mut rhs_sign = self.builder.insert_binary(rhs_as_unsigned, BinaryOp::Lt, half_width); + let message = if is_sub { + // lhs - rhs = lhs + (-rhs) + rhs_sign = self.builder.insert_binary(one, BinaryOp::Sub, rhs_sign); + "attempt to subtract with overflow".to_string() + } else { + "attempt to add with overflow".to_string() + }; + // same_sign is true if both operands have the same sign + let same_sign = self.builder.insert_binary(lhs_sign, BinaryOp::Eq, rhs_sign); + match operator { + BinaryOpKind::Add | BinaryOpKind::Subtract => { + //Check the result has the same sign as its inputs + let result_sign = self.builder.insert_binary(result, BinaryOp::Lt, half_width); + let sign_diff = self.builder.insert_binary(result_sign, BinaryOp::Eq, lhs_sign); + let sign_diff_with_predicate = + self.builder.insert_binary(sign_diff, BinaryOp::Mul, same_sign); + let overflow_check = + Instruction::Constrain(sign_diff_with_predicate, same_sign, Some(message)); + self.builder.set_location(location).insert_instruction(overflow_check, None); + } + BinaryOpKind::Multiply => { + // Overflow check for the multiplication: + // First we compute the absolute value of operands, and their product + let lhs_abs = self.absolute_value_helper(lhs, lhs_sign, bit_size); + let rhs_abs = self.absolute_value_helper(rhs, rhs_sign, bit_size); + let product_field = self.builder.insert_binary(lhs_abs, BinaryOp::Mul, rhs_abs); + // It must not already overflow the bit_size + let message = "attempt to multiply with overflow".to_string(); + let size_overflow = Instruction::RangeCheck { + value: product_field, + max_bit_size: bit_size, + assert_message: Some(message.clone()), + }; + self.builder.set_location(location).insert_instruction(size_overflow, None); + let product = self.builder.insert_cast(product_field, Type::unsigned(bit_size)); + + // Then we check the signed product fits in a signed integer of bit_size-bits + let not_same = self.builder.insert_binary(one, BinaryOp::Sub, same_sign); + let not_same_sign_field = self + .builder + .insert_instruction(Instruction::Cast(not_same, Type::unsigned(bit_size)), None) + .first(); + let positive_maximum_with_offset = + self.builder.insert_binary(half_width, BinaryOp::Add, not_same_sign_field); + let product_overflow_check = + self.builder.insert_binary(product, BinaryOp::Lt, positive_maximum_with_offset); + self.builder.set_location(location).insert_instruction( + Instruction::Constrain(product_overflow_check, one, Some(message)), + None, + ); + } + BinaryOpKind::ShiftLeft => unreachable!("shift is not supported for signed integer"), + _ => unreachable!("operator {} should not overflow", operator), + } + } /// Insert a binary instruction at the end of the current block. /// Converts the form of the binary instruction as necessary /// (e.g. swapping arguments, inserting a not) to represent it in the IR. @@ -321,8 +462,8 @@ impl<'a> FunctionContext<'a> { location: Location, ) -> Values { let mut result = match operator { - BinaryOpKind::ShiftLeft => self.insert_shift_left(lhs, rhs), - BinaryOpKind::ShiftRight => self.insert_shift_right(lhs, rhs), + BinaryOpKind::ShiftLeft => self.builder.insert_shift_left(lhs, rhs), + BinaryOpKind::ShiftRight => self.builder.insert_shift_right(lhs, rhs), BinaryOpKind::Equal | BinaryOpKind::NotEqual if matches!(self.builder.type_of_value(lhs), Type::Array(..)) => { @@ -338,21 +479,15 @@ impl<'a> FunctionContext<'a> { } }; - if let Some(max_bit_size) = operator_result_max_bit_size_to_truncate( + // Check for integer overflow + if matches!( operator, - lhs, - rhs, - &self.builder.current_function.dfg, + BinaryOpKind::Add + | BinaryOpKind::Subtract + | BinaryOpKind::Multiply + | BinaryOpKind::ShiftLeft ) { - let result_type = self.builder.current_function.dfg.type_of_value(result); - let bit_size = match result_type { - Type::Numeric(NumericType::Signed { bit_size }) - | Type::Numeric(NumericType::Unsigned { bit_size }) => bit_size, - _ => { - unreachable!("ICE: Truncation attempted on non-integer"); - } - }; - result = self.builder.insert_truncate(result, bit_size, max_bit_size); + result = self.check_overflow(result, lhs, rhs, operator, location); } if operator_requires_not(operator) { diff --git a/compiler/noirc_frontend/Cargo.toml b/compiler/noirc_frontend/Cargo.toml index 6cc7b07126c..246d6617c94 100644 --- a/compiler/noirc_frontend/Cargo.toml +++ b/compiler/noirc_frontend/Cargo.toml @@ -28,5 +28,4 @@ strum = "0.24" strum_macros = "0.24" [features] -default = [] aztec = [] diff --git a/compiler/noirc_frontend/src/ast/statement.rs b/compiler/noirc_frontend/src/ast/statement.rs index 9fe78f40c59..7d19a079203 100644 --- a/compiler/noirc_frontend/src/ast/statement.rs +++ b/compiler/noirc_frontend/src/ast/statement.rs @@ -1,9 +1,14 @@ use std::fmt::Display; +use std::sync::atomic::{AtomicU32, Ordering}; use crate::lexer::token::SpannedToken; use crate::parser::{ParserError, ParserErrorReason}; use crate::token::Token; -use crate::{Expression, ExpressionKind, IndexExpression, MemberAccessExpression, UnresolvedType}; +use crate::{ + BlockExpression, Expression, ExpressionKind, IndexExpression, MemberAccessExpression, + MethodCallExpression, UnresolvedType, +}; +use acvm::FieldElement; use iter_extended::vecmap; use noirc_errors::{Span, Spanned}; @@ -478,12 +483,123 @@ impl LValue { } } +#[derive(Debug, PartialEq, Eq, Clone)] +pub enum ForRange { + Range(/*start:*/ Expression, /*end:*/ Expression), + Array(Expression), +} + +impl ForRange { + /// Create a 'for' expression taking care of desugaring a 'for e in array' loop + /// into the following if needed: + /// + /// { + /// let fresh1 = array; + /// for fresh2 in 0 .. std::array::len(fresh1) { + /// let elem = fresh1[fresh2]; + /// ... + /// } + /// } + pub(crate) fn into_for( + self, + identifier: Ident, + block: Expression, + for_loop_span: Span, + ) -> StatementKind { + /// Counter used to generate unique names when desugaring + /// code in the parser requires the creation of fresh variables. + /// The parser is stateless so this is a static global instead. + static UNIQUE_NAME_COUNTER: AtomicU32 = AtomicU32::new(0); + + match self { + ForRange::Range(..) => { + unreachable!() + } + ForRange::Array(array) => { + let array_span = array.span; + let start_range = ExpressionKind::integer(FieldElement::zero()); + let start_range = Expression::new(start_range, array_span); + + let next_unique_id = UNIQUE_NAME_COUNTER.fetch_add(1, Ordering::Relaxed); + let array_name = format!("$i{next_unique_id}"); + let array_span = array.span; + let array_ident = Ident::new(array_name, array_span); + + // let fresh1 = array; + let let_array = Statement { + kind: StatementKind::Let(LetStatement { + pattern: Pattern::Identifier(array_ident.clone()), + r#type: UnresolvedType::unspecified(), + expression: array, + }), + span: array_span, + }; + + // array.len() + let segments = vec![array_ident]; + let array_ident = + ExpressionKind::Variable(Path { segments, kind: PathKind::Plain }); + + let end_range = ExpressionKind::MethodCall(Box::new(MethodCallExpression { + object: Expression::new(array_ident.clone(), array_span), + method_name: Ident::new("len".to_string(), array_span), + arguments: vec![], + })); + let end_range = Expression::new(end_range, array_span); + + let next_unique_id = UNIQUE_NAME_COUNTER.fetch_add(1, Ordering::Relaxed); + let index_name = format!("$i{next_unique_id}"); + let fresh_identifier = Ident::new(index_name.clone(), array_span); + + // array[i] + let segments = vec![Ident::new(index_name, array_span)]; + let index_ident = + ExpressionKind::Variable(Path { segments, kind: PathKind::Plain }); + + let loop_element = ExpressionKind::Index(Box::new(IndexExpression { + collection: Expression::new(array_ident, array_span), + index: Expression::new(index_ident, array_span), + })); + + // let elem = array[i]; + let let_elem = Statement { + kind: StatementKind::Let(LetStatement { + pattern: Pattern::Identifier(identifier), + r#type: UnresolvedType::unspecified(), + expression: Expression::new(loop_element, array_span), + }), + span: array_span, + }; + + let block_span = block.span; + let new_block = BlockExpression(vec![ + let_elem, + Statement { kind: StatementKind::Expression(block), span: block_span }, + ]); + let new_block = Expression::new(ExpressionKind::Block(new_block), block_span); + let for_loop = Statement { + kind: StatementKind::For(ForLoopStatement { + identifier: fresh_identifier, + range: ForRange::Range(start_range, end_range), + block: new_block, + span: for_loop_span, + }), + span: for_loop_span, + }; + + let block = ExpressionKind::Block(BlockExpression(vec![let_array, for_loop])); + StatementKind::Expression(Expression::new(block, for_loop_span)) + } + } + } +} + #[derive(Debug, PartialEq, Eq, Clone)] pub struct ForLoopStatement { pub identifier: Ident, - pub start_range: Expression, - pub end_range: Expression, + pub range: ForRange, pub block: Expression, + pub span: Span, } impl Display for StatementKind { @@ -575,10 +691,11 @@ impl Display for Pattern { impl Display for ForLoopStatement { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - write!( - f, - "for {} in {} .. {} {}", - self.identifier, self.start_range, self.end_range, self.block - ) + let range = match &self.range { + ForRange::Range(start, end) => format!("{start}..{end}"), + ForRange::Array(expr) => expr.to_string(), + }; + + write!(f, "for {} in {range} {}", self.identifier, self.block) } } diff --git a/compiler/noirc_frontend/src/hir/aztec_library.rs b/compiler/noirc_frontend/src/hir/aztec_library.rs index 24dd79efc6c..0eb550dd59a 100644 --- a/compiler/noirc_frontend/src/hir/aztec_library.rs +++ b/compiler/noirc_frontend/src/hir/aztec_library.rs @@ -16,8 +16,8 @@ use crate::{ UnresolvedType, UnresolvedTypeData, Visibility, }; use crate::{ - ForLoopStatement, FunctionDefinition, FunctionVisibility, ImportStatement, NoirStruct, - PrefixExpression, Signedness, StatementKind, StructType, Type, TypeImpl, UnaryOp, + ForLoopStatement, ForRange, FunctionDefinition, FunctionVisibility, ImportStatement, + NoirStruct, PrefixExpression, Signedness, StatementKind, StructType, Type, TypeImpl, UnaryOp, }; use fm::FileId; @@ -170,15 +170,9 @@ pub(crate) fn transform( // Covers all functions in the ast for submodule in ast.submodules.iter_mut().filter(|submodule| submodule.is_contract) { - let storage_defined = check_for_storage_definition(&submodule.contents); - - if transform_module(&mut submodule.contents, storage_defined) { - match check_for_aztec_dependency(crate_id, context) { - Ok(()) => include_relevant_imports(&mut submodule.contents), - Err(file_id) => { - return Err((DefCollectorErrorKind::AztecNotFound {}, file_id)); - } - } + if transform_module(&mut submodule.contents, crate_id, context)? { + check_for_aztec_dependency(crate_id, context)?; + include_relevant_imports(&mut submodule.contents); } } Ok(ast) @@ -209,19 +203,59 @@ fn include_relevant_imports(ast: &mut SortedModule) { } /// Creates an error alerting the user that they have not downloaded the Aztec-noir library -fn check_for_aztec_dependency(crate_id: &CrateId, context: &Context) -> Result<(), FileId> { +fn check_for_aztec_dependency( + crate_id: &CrateId, + context: &Context, +) -> Result<(), (DefCollectorErrorKind, FileId)> { let crate_graph = &context.crate_graph[crate_id]; let has_aztec_dependency = crate_graph.dependencies.iter().any(|dep| dep.as_name() == "aztec"); if has_aztec_dependency { Ok(()) } else { - Err(crate_graph.root_file_id) + Err((DefCollectorErrorKind::AztecNotFound {}, crate_graph.root_file_id)) } } // Check to see if the user has defined a storage struct fn check_for_storage_definition(module: &SortedModule) -> bool { - module.types.iter().any(|function| function.name.0.contents == "Storage") + module.types.iter().any(|r#struct| r#struct.name.0.contents == "Storage") +} + +// Check if "compute_note_hash_and_nullifier(Field,Field,Field,[Field; N]) -> [Field; 4]" is defined +fn check_for_compute_note_hash_and_nullifier_definition(module: &SortedModule) -> bool { + module.functions.iter().any(|func| { + func.def.name.0.contents == "compute_note_hash_and_nullifier" + && func.def.parameters.len() == 4 + && func.def.parameters[0].1.typ == UnresolvedTypeData::FieldElement + && func.def.parameters[1].1.typ == UnresolvedTypeData::FieldElement + && func.def.parameters[2].1.typ == UnresolvedTypeData::FieldElement + // checks if the 4th parameter is an array and the Box in + // Array(Option, Box) contains only fields + && match &func.def.parameters[3].1.typ { + UnresolvedTypeData::Array(_, inner_type) => { + match inner_type.typ { + UnresolvedTypeData::FieldElement => true, + _ => false, + } + }, + _ => false, + } + // We check the return type the same way as we did the 4th parameter + && match &func.def.return_type { + FunctionReturnType::Default(_) => false, + FunctionReturnType::Ty(unresolved_type) => { + match &unresolved_type.typ { + UnresolvedTypeData::Array(_, inner_type) => { + match inner_type.typ { + UnresolvedTypeData::FieldElement => true, + _ => false, + } + }, + _ => false, + } + } + } + }) } /// Checks if an attribute is a custom attribute with a specific name @@ -236,9 +270,26 @@ fn is_custom_attribute(attr: &SecondaryAttribute, attribute_name: &str) -> bool /// Determines if ast nodes are annotated with aztec attributes. /// For annotated functions it calls the `transform` function which will perform the required transformations. /// Returns true if an annotated node is found, false otherwise -fn transform_module(module: &mut SortedModule, storage_defined: bool) -> bool { +fn transform_module( + module: &mut SortedModule, + crate_id: &CrateId, + context: &Context, +) -> Result { let mut has_transformed_module = false; + // Check for a user defined storage struct + let storage_defined = check_for_storage_definition(&module); + + if storage_defined && !check_for_compute_note_hash_and_nullifier_definition(&module) { + let crate_graph = &context.crate_graph[crate_id]; + return Err(( + DefCollectorErrorKind::AztecComputeNoteHashAndNullifierNotFound { + span: Span::default(), // Add a default span so we know which contract file the error originates from + }, + crate_graph.root_file_id, + )); + } + for structure in module.types.iter() { if structure.attributes.iter().any(|attr| matches!(attr, SecondaryAttribute::Event)) { module.impls.push(generate_selector_impl(structure)); @@ -262,7 +313,7 @@ fn transform_module(module: &mut SortedModule, storage_defined: bool) -> bool { has_transformed_module = true; } } - has_transformed_module + Ok(has_transformed_module) } /// If it does, it will insert the following things: @@ -822,6 +873,7 @@ fn add_struct_to_hasher(identifier: &Ident) -> Statement { fn create_loop_over(var: Expression, loop_body: Vec) -> Statement { // If this is an array of primitive types (integers / fields) we can add them each to the hasher // casted to a field + let span = var.span.clone(); // `array.len()` let end_range_expression = method_call( @@ -836,12 +888,15 @@ fn create_loop_over(var: Expression, loop_body: Vec) -> Statement { // `for i in 0..{ident}.len()` make_statement(StatementKind::For(ForLoopStatement { + range: ForRange::Range( + expression(ExpressionKind::Literal(Literal::Integer(FieldElement::from(i128::from( + 0, + ))))), + end_range_expression, + ), identifier: ident("i"), - start_range: expression(ExpressionKind::Literal(Literal::Integer(FieldElement::from( - i128::from(0), - )))), - end_range: end_range_expression, block: for_loop_block, + span, })) } diff --git a/compiler/noirc_frontend/src/hir/def_collector/dc_crate.rs b/compiler/noirc_frontend/src/hir/def_collector/dc_crate.rs index aa2bedb37b7..460abde8e74 100644 --- a/compiler/noirc_frontend/src/hir/def_collector/dc_crate.rs +++ b/compiler/noirc_frontend/src/hir/def_collector/dc_crate.rs @@ -1,7 +1,7 @@ use super::dc_mod::collect_defs; use super::errors::{DefCollectorErrorKind, DuplicateType}; use crate::graph::CrateId; -use crate::hir::def_map::{CrateDefMap, LocalModuleId, ModuleDefId, ModuleId}; +use crate::hir::def_map::{CrateDefMap, LocalModuleId, ModuleData, ModuleDefId, ModuleId}; use crate::hir::resolution::errors::ResolverError; use crate::hir::resolution::import::PathResolutionError; use crate::hir::resolution::path_resolver::PathResolver; @@ -13,9 +13,7 @@ use crate::hir::resolution::{ use crate::hir::type_check::{type_check_func, TypeCheckError, TypeChecker}; use crate::hir::Context; use crate::hir_def::traits::{Trait, TraitConstant, TraitFunction, TraitImpl, TraitType}; -use crate::node_interner::{ - FuncId, NodeInterner, StmtId, StructId, TraitId, TraitImplKey, TypeAliasId, -}; +use crate::node_interner::{FuncId, NodeInterner, StmtId, StructId, TraitId, TypeAliasId}; use crate::parser::{ParserError, SortedModule}; use crate::{ @@ -92,6 +90,7 @@ pub struct UnresolvedTraitImpl { pub trait_path: Path, pub object_type: UnresolvedType, pub methods: UnresolvedFunctions, + pub generics: UnresolvedGenerics, } #[derive(Clone)] @@ -126,7 +125,7 @@ pub struct DefCollector { pub enum CompilationError { ParseError(ParserError), DefinitionError(DefCollectorErrorKind), - ResolveError(ResolverError), + ResolverError(ResolverError), TypeError(TypeCheckError), } @@ -135,7 +134,7 @@ impl From for CustomDiagnostic { match value { CompilationError::ParseError(error) => error.into(), CompilationError::DefinitionError(error) => error.into(), - CompilationError::ResolveError(error) => error.into(), + CompilationError::ResolverError(error) => error.into(), CompilationError::TypeError(error) => error.into(), } } @@ -155,7 +154,7 @@ impl From for CompilationError { impl From for CompilationError { fn from(value: ResolverError) -> Self { - CompilationError::ResolveError(value) + CompilationError::ResolverError(value) } } impl From for CompilationError { @@ -296,12 +295,6 @@ impl DefCollector { // globals will need to reference the struct type they're initialized to to ensure they are valid. resolved_globals.extend(resolve_globals(context, other_globals, crate_id)); - // Before we resolve any function symbols we must go through our impls and - // re-collect the methods within into their proper module. This cannot be - // done before resolution since we need to be able to resolve the type of the - // impl since that determines the module we should collect into. - errors.extend(collect_impls(context, crate_id, &def_collector.collected_impls)); - // Bind trait impls to their trait. Collect trait functions, that have a // default implementation, which hasn't been overridden. errors.extend(collect_trait_impls( @@ -310,6 +303,15 @@ impl DefCollector { &mut def_collector.collected_traits_impls, )); + // Before we resolve any function symbols we must go through our impls and + // re-collect the methods within into their proper module. This cannot be + // done before resolution since we need to be able to resolve the type of the + // impl since that determines the module we should collect into. + // + // These are resolved after trait impls so that struct methods are chosen + // over trait methods if there are name conflicts. + errors.extend(collect_impls(context, crate_id, &def_collector.collected_impls)); + // Lower each function in the crate. This is now possible since imports have been resolved let file_func_ids = resolve_free_functions( &mut context.def_interner, @@ -327,7 +329,6 @@ impl DefCollector { def_collector.collected_impls, &mut errors, ); - // resolve_trait_impls can fill different type of errors, therefore we pass errors by mut ref let file_trait_impls_ids = resolve_trait_impls( context, def_collector.collected_traits_impls, @@ -377,7 +378,6 @@ fn collect_impls( if let Some(struct_type) = get_struct_type(&typ) { let struct_type = struct_type.borrow(); - let type_module = struct_type.id.local_module_id(); // `impl`s are only allowed on types defined within the current crate if struct_type.id.krate() != crate_id { @@ -391,7 +391,7 @@ fn collect_impls( // Grab the module defined by the struct type. Note that impls are a case // where the module the methods are added to is not the same as the module // they are resolved in. - let module = &mut def_maps.get_mut(&crate_id).unwrap().modules[type_module.0]; + let module = get_module_mut(def_maps, struct_type.id.module_id()); for (_, method_id, method) in &unresolved.functions { // If this method was already declared, remove it from the module so it cannot @@ -413,6 +413,13 @@ fn collect_impls( errors } +fn get_module_mut( + def_maps: &mut BTreeMap, + module: ModuleId, +) -> &mut ModuleData { + &mut def_maps.get_mut(&module.krate).unwrap().modules[module.local_id.0] +} + fn collect_trait_impl_methods( interner: &mut NodeInterner, def_maps: &BTreeMap, @@ -494,25 +501,6 @@ fn collect_trait_impl_methods( errors } -fn add_method_to_struct_namespace( - current_def_map: &mut CrateDefMap, - struct_type: &Shared, - func_id: FuncId, - name_ident: &Ident, - trait_id: TraitId, -) -> Result<(), DefCollectorErrorKind> { - let struct_type = struct_type.borrow(); - let type_module = struct_type.id.local_module_id(); - let module = &mut current_def_map.modules[type_module.0]; - module.declare_trait_function(name_ident.clone(), func_id, trait_id).map_err( - |(first_def, second_def)| DefCollectorErrorKind::Duplicate { - typ: DuplicateType::TraitImplementation, - first_def, - second_def, - }, - ) -} - fn collect_trait_impl( context: &mut Context, crate_id: CrateId, @@ -535,28 +523,25 @@ fn collect_trait_impl( if let Some(trait_id) = trait_impl.trait_id { errors .extend(collect_trait_impl_methods(interner, def_maps, crate_id, trait_id, trait_impl)); - for (_, func_id, ast) in &trait_impl.methods.functions { - let file = def_maps[&crate_id].file_id(trait_impl.module_id); - let path_resolver = StandardPathResolver::new(module); - let mut resolver = Resolver::new(interner, &path_resolver, def_maps, file); - resolver.add_generics(&ast.def.generics); - let typ = resolver.resolve_type(unresolved_type.clone()); - - if let Some(struct_type) = get_struct_type(&typ) { - errors.extend(take_errors(trait_impl.file_id, resolver)); - let current_def_map = def_maps.get_mut(&struct_type.borrow().id.krate()).unwrap(); - match add_method_to_struct_namespace( - current_def_map, - struct_type, - *func_id, - ast.name_ident(), - trait_id, - ) { - Ok(()) => {} - Err(err) => { - errors.push((err.into(), trait_impl.file_id)); - } + let path_resolver = StandardPathResolver::new(module); + let file = def_maps[&crate_id].file_id(trait_impl.module_id); + let mut resolver = Resolver::new(interner, &path_resolver, def_maps, file); + resolver.add_generics(&trait_impl.generics); + let typ = resolver.resolve_type(unresolved_type); + errors.extend(take_errors(trait_impl.file_id, resolver)); + + if let Some(struct_type) = get_struct_type(&typ) { + let struct_type = struct_type.borrow(); + let module = get_module_mut(def_maps, struct_type.id.module_id()); + + for (_, method_id, method) in &trait_impl.methods.functions { + // If this method was already declared, remove it from the module so it cannot + // be accessed with the `TypeName::method` syntax. We'll check later whether the + // object types in each method overlap or not. If they do, we issue an error. + // If not, that is specialization which is allowed. + if module.declare_function(method.name_ident().clone(), *method_id).is_err() { + module.remove_function(method.name_ident()); } } } @@ -772,7 +757,7 @@ fn resolve_trait_methods( for item in &unresolved_trait.trait_def.items { if let TraitItem::Function { name, - generics: _, + generics, parameters, return_type, where_clause: _, @@ -784,14 +769,14 @@ fn resolve_trait_methods( Type::TypeVariable(the_trait.self_type_typevar.clone(), TypeVariableKind::Normal); let mut resolver = Resolver::new(interner, &path_resolver, def_maps, file); + resolver.add_generics(generics); resolver.set_self_type(Some(self_type)); let arguments = vecmap(parameters, |param| resolver.resolve_type(param.1.clone())); let resolved_return_type = resolver.resolve_type(return_type.get_type().into_owned()); + let generics = resolver.get_generics().to_vec(); let name = name.clone(); - // TODO - let generics: Generics = vec![]; let span: Span = name.span(); let default_impl_list: Vec<_> = unresolved_trait .fns_with_default_impl @@ -841,7 +826,7 @@ fn take_errors_filter_self_not_resolved( } fn take_errors(file_id: FileId, resolver: Resolver<'_>) -> Vec<(CompilationError, FileId)> { - resolver.take_errors().iter().cloned().map(|e| (e.into(), file_id)).collect() + vecmap(resolver.take_errors(), |e| (e.into(), file_id)) } /// Create the mappings from TypeId -> TraitType @@ -942,7 +927,7 @@ fn resolve_impls( let method_name = interner.function_name(method_id).to_owned(); if let Some(first_fn) = - interner.add_method(&self_type, method_name.clone(), *method_id) + interner.add_method(&self_type, method_name.clone(), *method_id, false) { let error = ResolverError::DuplicateDefinition { name: method_name, @@ -974,17 +959,14 @@ fn resolve_trait_impls( let local_mod_id = trait_impl.module_id; let module_id = ModuleId { krate: crate_id, local_id: local_mod_id }; let path_resolver = StandardPathResolver::new(module_id); - let trait_definition_ident = trait_impl.trait_path.last_segment(); let self_type_span = unresolved_type.span; - let self_type = { - let mut resolver = - Resolver::new(interner, &path_resolver, &context.def_maps, trait_impl.file_id); - resolver.resolve_type(unresolved_type.clone()) - }; - - let maybe_trait_id = trait_impl.trait_id; + let mut resolver = + Resolver::new(interner, &path_resolver, &context.def_maps, trait_impl.file_id); + resolver.add_generics(&trait_impl.generics); + let self_type = resolver.resolve_type(unresolved_type.clone()); + let generics = resolver.get_generics().to_vec(); let mut impl_methods = resolve_function_set( interner, @@ -992,45 +974,57 @@ fn resolve_trait_impls( &context.def_maps, trait_impl.methods.clone(), Some(self_type.clone()), - vec![], // TODO + generics, errors, ); + let maybe_trait_id = trait_impl.trait_id; if let Some(trait_id) = maybe_trait_id { for (_, func) in &impl_methods { interner.set_function_trait(*func, self_type.clone(), trait_id); } } + if matches!(self_type, Type::MutableReference(_)) { + let span = self_type_span.unwrap_or_else(|| trait_impl.trait_path.span()); + let error = DefCollectorErrorKind::MutableReferenceInTraitImpl { span }; + errors.push((error.into(), trait_impl.file_id)); + } + let mut new_resolver = Resolver::new(interner, &path_resolver, &context.def_maps, trait_impl.file_id); new_resolver.set_self_type(Some(self_type.clone())); if let Some(trait_id) = maybe_trait_id { - check_methods_signatures(&mut new_resolver, &impl_methods, trait_id, errors); - - let key = TraitImplKey { typ: self_type.clone(), trait_id }; - if let Some(prev_trait_impl_ident) = interner.get_trait_implementation(&key) { - let err = DefCollectorErrorKind::Duplicate { - typ: DuplicateType::TraitImplementation, - first_def: prev_trait_impl_ident.borrow().ident.clone(), - second_def: trait_definition_ident.clone(), - }; - errors.push((err.into(), trait_impl.methods.file_id)); - } else { - let resolved_trait_impl = Shared::new(TraitImpl { - ident: trait_impl.trait_path.last_segment().clone(), + check_methods_signatures( + &mut new_resolver, + &impl_methods, + trait_id, + trait_impl.generics.len(), + errors, + ); + + let resolved_trait_impl = Shared::new(TraitImpl { + ident: trait_impl.trait_path.last_segment().clone(), + typ: self_type.clone(), + trait_id, + file: trait_impl.file_id, + methods: vecmap(&impl_methods, |(_, func_id)| *func_id), + }); + + if let Some((prev_span, prev_file)) = + interner.add_trait_implementation(self_type.clone(), trait_id, resolved_trait_impl) + { + let error = DefCollectorErrorKind::OverlappingImpl { typ: self_type.clone(), - trait_id, - methods: vecmap(&impl_methods, |(_, func_id)| *func_id), - }); - if !interner.add_trait_implementation(&key, resolved_trait_impl.clone()) { - let error = DefCollectorErrorKind::TraitImplNotAllowedFor { - trait_path: trait_impl.trait_path.clone(), - span: self_type_span.unwrap_or_else(|| trait_impl.trait_path.span()), - }; - errors.push((error.into(), trait_impl.file_id)); - } + span: self_type_span.unwrap_or_else(|| trait_impl.trait_path.span()), + }; + errors.push((error.into(), trait_impl.file_id)); + + // The 'previous impl defined here' note must be a separate error currently + // since it may be in a different file and all errors have the same file id. + let error = DefCollectorErrorKind::OverlappingImplNote { span: prev_span }; + errors.push((error.into(), prev_file)); } methods.append(&mut impl_methods); @@ -1045,6 +1039,7 @@ fn check_methods_signatures( resolver: &mut Resolver, impl_methods: &Vec<(FileId, FuncId)>, trait_id: TraitId, + trait_impl_generic_count: usize, errors: &mut Vec<(CompilationError, FileId)>, ) { let the_trait = resolver.interner.get_trait(trait_id); @@ -1055,24 +1050,42 @@ fn check_methods_signatures( let _ = the_trait.self_type_typevar.borrow_mut().bind_to(self_type.clone(), the_trait.span); for (file_id, func_id) in impl_methods { - let meta = resolver.interner.function_meta(func_id); + let impl_method = resolver.interner.function_meta(func_id); let func_name = resolver.interner.function_name(func_id).to_owned(); let mut typecheck_errors = Vec::new(); - // `method` is None in the case where the impl block has a method that's not part of the trait. + // This is None in the case where the impl block has a method that's not part of the trait. // If that's the case, a `MethodNotInTrait` error has already been thrown, and we can ignore // the impl method, since there's nothing in the trait to match its signature against. - if let Some(method) = + if let Some(trait_method) = the_trait.methods.iter().find(|method| method.name.0.contents == func_name) { - let function_typ = meta.typ.instantiate(resolver.interner); + let impl_function_type = impl_method.typ.instantiate(resolver.interner); + + let impl_method_generic_count = + impl_method.typ.generic_count() - trait_impl_generic_count; + let trait_method_generic_count = trait_method.generics.len(); + + if impl_method_generic_count != trait_method_generic_count { + let error = DefCollectorErrorKind::MismatchTraitImplementationNumGenerics { + impl_method_generic_count, + trait_method_generic_count, + trait_name: the_trait.name.to_string(), + method_name: func_name.to_string(), + span: impl_method.location.span, + }; + errors.push((error.into(), *file_id)); + } - if let Type::Function(params, _, _) = function_typ.0 { - if method.arguments.len() == params.len() { + if let Type::Function(impl_params, _, _) = impl_function_type.0 { + if trait_method.arguments.len() == impl_params.len() { // Check the parameters of the impl method against the parameters of the trait method + let args = trait_method.arguments.iter(); + let args_and_params = args.zip(&impl_params).zip(&impl_method.parameters.0); + for (parameter_index, ((expected, actual), (hir_pattern, _, _))) in - method.arguments.iter().zip(¶ms).zip(&meta.parameters.0).enumerate() + args_and_params.enumerate() { expected.unify(actual, &mut typecheck_errors, || { TypeCheckError::TraitMethodParameterTypeMismatch { @@ -1085,33 +1098,28 @@ fn check_methods_signatures( }); } } else { - errors.push(( - DefCollectorErrorKind::MismatchTraitImplementationNumParameters { - actual_num_parameters: meta.parameters.0.len(), - expected_num_parameters: method.arguments.len(), - trait_name: the_trait.name.to_string(), - method_name: func_name.to_string(), - span: meta.location.span, - } - .into(), - *file_id, - )); + let error = DefCollectorErrorKind::MismatchTraitImplementationNumParameters { + actual_num_parameters: impl_method.parameters.0.len(), + expected_num_parameters: trait_method.arguments.len(), + trait_name: the_trait.name.to_string(), + method_name: func_name.to_string(), + span: impl_method.location.span, + }; + errors.push((error.into(), *file_id)); } } // Check that impl method return type matches trait return type: let resolved_return_type = - resolver.resolve_type(meta.return_type.get_type().into_owned()); + resolver.resolve_type(impl_method.return_type.get_type().into_owned()); - method.return_type.unify(&resolved_return_type, &mut typecheck_errors, || { - let ret_type_span = - meta.return_type.get_type().span.expect("return type must always have a span"); + trait_method.return_type.unify(&resolved_return_type, &mut typecheck_errors, || { + let ret_type_span = impl_method.return_type.get_type().span; + let expr_span = ret_type_span.expect("return type must always have a span"); - TypeCheckError::TypeMismatch { - expected_typ: method.return_type.to_string(), - expr_typ: meta.return_type().to_string(), - expr_span: ret_type_span, - } + let expected_typ = trait_method.return_type.to_string(); + let expr_typ = impl_method.return_type().to_string(); + TypeCheckError::TypeMismatch { expr_typ, expected_typ, expr_span } }); errors.extend(typecheck_errors.iter().cloned().map(|e| (e.into(), *file_id))); diff --git a/compiler/noirc_frontend/src/hir/def_collector/dc_mod.rs b/compiler/noirc_frontend/src/hir/def_collector/dc_mod.rs index ed48d7fbb51..32f39ce4952 100644 --- a/compiler/noirc_frontend/src/hir/def_collector/dc_mod.rs +++ b/compiler/noirc_frontend/src/hir/def_collector/dc_mod.rs @@ -7,7 +7,7 @@ use noirc_errors::Location; use crate::{ graph::CrateId, hir::def_collector::dc_crate::{UnresolvedStruct, UnresolvedTrait}, - node_interner::{TraitId, TypeAliasId}, + node_interner::{FunctionModifiers, TraitId, TypeAliasId}, parser::{SortedModule, SortedSubModule}, FunctionDefinition, Ident, LetStatement, NoirFunction, NoirStruct, NoirTrait, NoirTraitImpl, NoirTypeAlias, TraitImplItem, TraitItem, TypeImpl, @@ -145,12 +145,13 @@ impl<'a> ModCollector<'a> { for trait_impl in impls { let trait_name = trait_impl.trait_name.clone(); - let unresolved_functions = + let mut unresolved_functions = self.collect_trait_impl_function_overrides(context, &trait_impl, krate); let module = ModuleId { krate, local_id: self.module_id }; - for (_, func_id, noir_function) in &unresolved_functions.functions { + for (_, func_id, noir_function) in &mut unresolved_functions.functions { + noir_function.def.where_clause.append(&mut trait_impl.where_clause.clone()); context.def_interner.push_function(*func_id, &noir_function.def, module); } @@ -160,6 +161,7 @@ impl<'a> ModCollector<'a> { trait_path: trait_name, methods: unresolved_functions, object_type: trait_impl.object_type, + generics: trait_impl.impl_generics, trait_id: None, // will be filled later }; @@ -378,11 +380,22 @@ impl<'a> ModCollector<'a> { body, } => { let func_id = context.def_interner.push_empty_fn(); + let modifiers = FunctionModifiers { + name: name.to_string(), + visibility: crate::FunctionVisibility::Public, + // TODO(Maddiaa): Investigate trait implementations with attributes see: https://github.com/noir-lang/noir/issues/2629 + attributes: crate::token::Attributes::empty(), + is_unconstrained: false, + contract_function_type: None, + is_internal: None, + }; + + context.def_interner.push_function_definition(func_id, modifiers, id.0); + match self.def_collector.def_map.modules[id.0.local_id.0] .declare_function(name.clone(), func_id) { Ok(()) => { - // TODO(Maddiaa): Investigate trait implementations with attributes see: https://github.com/noir-lang/noir/issues/2629 if let Some(body) = body { let impl_method = NoirFunction::normal(FunctionDefinition::normal( diff --git a/compiler/noirc_frontend/src/hir/def_collector/errors.rs b/compiler/noirc_frontend/src/hir/def_collector/errors.rs index 4e7f8ad286b..edb39fe68d7 100644 --- a/compiler/noirc_frontend/src/hir/def_collector/errors.rs +++ b/compiler/noirc_frontend/src/hir/def_collector/errors.rs @@ -33,11 +33,15 @@ pub enum DefCollectorErrorKind { PathResolutionError(PathResolutionError), #[error("Non-struct type used in impl")] NonStructTypeInImpl { span: Span }, - #[error("Trait implementation is not allowed for this")] - TraitImplNotAllowedFor { trait_path: Path, span: Span }, + #[error("Cannot implement trait on a mutable reference type")] + MutableReferenceInTraitImpl { span: Span }, + #[error("Impl for type `{typ}` overlaps with existing impl")] + OverlappingImpl { span: Span, typ: crate::Type }, + #[error("Previous impl defined here")] + OverlappingImplNote { span: Span }, #[error("Cannot `impl` a type defined outside the current crate")] ForeignImpl { span: Span, type_name: String }, - #[error("Mismatch number of parameters in of trait implementation")] + #[error("Mismatched number of parameters in trait implementation")] MismatchTraitImplementationNumParameters { actual_num_parameters: usize, expected_num_parameters: usize, @@ -45,6 +49,14 @@ pub enum DefCollectorErrorKind { method_name: String, span: Span, }, + #[error("Mismatched number of generics in impl method")] + MismatchTraitImplementationNumGenerics { + impl_method_generic_count: usize, + trait_method_generic_count: usize, + trait_name: String, + method_name: String, + span: Span, + }, #[error("Method is not defined in trait")] MethodNotInTrait { trait_name: Ident, impl_method: Ident }, #[error("Only traits can be implemented")] @@ -57,13 +69,19 @@ pub enum DefCollectorErrorKind { ModuleAlreadyPartOfCrate { mod_name: Ident, span: Span }, #[error("Module was originally declared here")] ModuleOriginallyDefined { mod_name: Ident, span: Span }, - #[cfg(feature = "aztec")] - #[error("Aztec dependency not found. Please add aztec as a dependency in your Cargo.toml")] - AztecNotFound {}, #[error( "Either the type or the trait must be from the same crate as the trait implementation" )] TraitImplOrphaned { span: Span }, + + // Aztec feature flag errors + // TODO(benesjan): https://github.com/AztecProtocol/aztec-packages/issues/2905 + #[cfg(feature = "aztec")] + #[error("Aztec dependency not found. Please add aztec as a dependency in your Cargo.toml")] + AztecNotFound {}, + #[cfg(feature = "aztec")] + #[error("compute_note_hash_and_nullifier function not found. Define it in your contract.")] + AztecComputeNoteHashAndNullifierNotFound { span: Span }, } impl DefCollectorErrorKind { @@ -125,10 +143,25 @@ impl From for Diagnostic { "Only struct types may have implementation methods".into(), span, ), - DefCollectorErrorKind::TraitImplNotAllowedFor { trait_path, span } => { + DefCollectorErrorKind::MutableReferenceInTraitImpl { span } => Diagnostic::simple_error( + "Trait impls are not allowed on mutable reference types".into(), + "Try using a struct type here instead".into(), + span, + ), + DefCollectorErrorKind::OverlappingImpl { span, typ } => { + Diagnostic::simple_error( + format!("Impl for type `{typ}` overlaps with existing impl"), + "Overlapping impl".into(), + span, + ) + } + DefCollectorErrorKind::OverlappingImplNote { span } => { + // This should be a note or part of the previous error eventually. + // This must be an error to appear next to the previous OverlappingImpl + // error since we sort warnings first. Diagnostic::simple_error( - format!("Only limited types may implement trait `{trait_path}`"), - "Only limited types may implement traits".into(), + "Previous impl defined here".into(), + "Previous impl defined here".into(), span, ) } @@ -149,8 +182,21 @@ impl From for Diagnostic { method_name, span, } => { + let plural = if expected_num_parameters == 1 { "" } else { "s" }; let primary_message = format!( - "Method `{method_name}` of trait `{trait_name}` needs {expected_num_parameters} parameters, but has {actual_num_parameters}"); + "`{trait_name}::{method_name}` expects {expected_num_parameters} parameter{plural}, but this method has {actual_num_parameters}"); + Diagnostic::simple_error(primary_message, "".to_string(), span) + } + DefCollectorErrorKind::MismatchTraitImplementationNumGenerics { + impl_method_generic_count, + trait_method_generic_count, + trait_name, + method_name, + span, + } => { + let plural = if trait_method_generic_count == 1 { "" } else { "s" }; + let primary_message = format!( + "`{trait_name}::{method_name}` expects {trait_method_generic_count} generic{plural}, but this method has {impl_method_generic_count}"); Diagnostic::simple_error(primary_message, "".to_string(), span) } DefCollectorErrorKind::MethodNotInTrait { trait_name, impl_method } => { @@ -194,15 +240,21 @@ impl From for Diagnostic { let secondary = String::new(); Diagnostic::simple_error(message, secondary, span) } - #[cfg(feature = "aztec")] - DefCollectorErrorKind::AztecNotFound {} => Diagnostic::from_message( - "Aztec dependency not found. Please add aztec as a dependency in your Cargo.toml", - ), DefCollectorErrorKind::TraitImplOrphaned { span } => Diagnostic::simple_error( "Orphaned trait implementation".into(), "Either the type or the trait must be from the same crate as the trait implementation".into(), span, ), + #[cfg(feature = "aztec")] + DefCollectorErrorKind::AztecNotFound {} => Diagnostic::from_message( + "Aztec dependency not found. Please add aztec as a dependency in your Cargo.toml", + ), + #[cfg(feature = "aztec")] + DefCollectorErrorKind::AztecComputeNoteHashAndNullifierNotFound {span} => Diagnostic::simple_error( + "compute_note_hash_and_nullifier function not found. Define it in your contract.".into(), + "".into(), + span + ), } } } diff --git a/compiler/noirc_frontend/src/hir/resolution/resolver.rs b/compiler/noirc_frontend/src/hir/resolution/resolver.rs index b3796418ab3..72597ae97ba 100644 --- a/compiler/noirc_frontend/src/hir/resolution/resolver.rs +++ b/compiler/noirc_frontend/src/hir/resolution/resolver.rs @@ -36,10 +36,11 @@ use crate::{ StatementKind, }; use crate::{ - ArrayLiteral, ContractFunctionType, Distinctness, FunctionVisibility, Generics, LValue, - NoirStruct, NoirTypeAlias, Path, PathKind, Pattern, Shared, StructType, Type, TypeAliasType, - TypeBinding, TypeVariable, UnaryOp, UnresolvedGenerics, UnresolvedTraitConstraint, - UnresolvedType, UnresolvedTypeData, UnresolvedTypeExpression, Visibility, ERROR_IDENT, + ArrayLiteral, ContractFunctionType, Distinctness, ForRange, FunctionVisibility, Generics, + LValue, NoirStruct, NoirTypeAlias, Path, PathKind, Pattern, Shared, StructType, Type, + TypeAliasType, TypeBinding, TypeVariable, UnaryOp, UnresolvedGenerics, + UnresolvedTraitConstraint, UnresolvedType, UnresolvedTypeData, UnresolvedTypeExpression, + Visibility, ERROR_IDENT, }; use fm::FileId; use iter_extended::vecmap; @@ -1007,23 +1008,37 @@ impl<'a> Resolver<'a> { HirStatement::Assign(stmt) } StatementKind::For(for_loop) => { - let start_range = self.resolve_expression(for_loop.start_range); - let end_range = self.resolve_expression(for_loop.end_range); - let (identifier, block) = (for_loop.identifier, for_loop.block); - - // TODO: For loop variables are currently mutable by default since we haven't - // yet implemented syntax for them to be optionally mutable. - let (identifier, block) = self.in_new_scope(|this| { - let decl = this.add_variable_decl( - identifier, - false, - true, - DefinitionKind::Local(None), - ); - (decl, this.resolve_expression(block)) - }); + match for_loop.range { + ForRange::Range(start_range, end_range) => { + let start_range = self.resolve_expression(start_range); + let end_range = self.resolve_expression(end_range); + let (identifier, block) = (for_loop.identifier, for_loop.block); + + // TODO: For loop variables are currently mutable by default since we haven't + // yet implemented syntax for them to be optionally mutable. + let (identifier, block) = self.in_new_scope(|this| { + let decl = this.add_variable_decl( + identifier, + false, + true, + DefinitionKind::Local(None), + ); + (decl, this.resolve_expression(block)) + }); - HirStatement::For(HirForStatement { start_range, end_range, block, identifier }) + HirStatement::For(HirForStatement { + start_range, + end_range, + block, + identifier, + }) + } + range @ ForRange::Array(_) => { + let for_stmt = + range.into_for(for_loop.identifier, for_loop.block, for_loop.span); + self.resolve_stmt(for_stmt) + } + } } StatementKind::Error => HirStatement::Error, } diff --git a/compiler/noirc_frontend/src/hir/type_check/expr.rs b/compiler/noirc_frontend/src/hir/type_check/expr.rs index 7f21bdbebda..645082c3713 100644 --- a/compiler/noirc_frontend/src/hir/type_check/expr.rs +++ b/compiler/noirc_frontend/src/hir/type_check/expr.rs @@ -266,6 +266,7 @@ impl<'interner> TypeChecker<'interner> { Box::new(method.return_type.clone()), Box::new(Type::Unit), ); + let (typ, bindings) = typ.instantiate(self.interner); self.interner.store_instantiation_bindings(*expr_id, bindings); typ @@ -293,9 +294,9 @@ impl<'interner> TypeChecker<'interner> { argument_types: &mut [(Type, ExprId, noirc_errors::Span)], ) { let expected_object_type = match function_type { - Type::Function(args, _, _) => args.get(0), + Type::Function(args, _, _) => args.first(), Type::Forall(_, typ) => match typ.as_ref() { - Type::Function(args, _, _) => args.get(0), + Type::Function(args, _, _) => args.first(), typ => unreachable!("Unexpected type for function: {typ}"), }, typ => unreachable!("Unexpected type for function: {typ}"), @@ -880,20 +881,14 @@ impl<'interner> TypeChecker<'interner> { // This may be a struct or a primitive type. Type::MutableReference(element) => self .interner - .lookup_mut_primitive_trait_method(element.as_ref(), method_name) + .lookup_primitive_trait_method_mut(element.as_ref(), method_name) .map(HirMethodReference::FuncId) .or_else(|| self.lookup_method(element, method_name, expr_id)), // If we fail to resolve the object to a struct type, we have no way of type // checking its arguments as we can't even resolve the name of the function Type::Error => None, - // In the future we could support methods for non-struct types if we have a context - // (in the interner?) essentially resembling HashMap - other => match self - .interner - .lookup_primitive_method(other, method_name) - .or_else(|| self.interner.lookup_primitive_trait_method(other, method_name)) - { + other => match self.interner.lookup_primitive_method(other, method_name) { Some(method_id) => Some(HirMethodReference::FuncId(method_id)), None => { self.errors.push(TypeCheckError::UnresolvedMethodCall { diff --git a/compiler/noirc_frontend/src/hir/type_check/mod.rs b/compiler/noirc_frontend/src/hir/type_check/mod.rs index 035dbbc3518..2a12d68406d 100644 --- a/compiler/noirc_frontend/src/hir/type_check/mod.rs +++ b/compiler/noirc_frontend/src/hir/type_check/mod.rs @@ -15,7 +15,7 @@ pub use errors::TypeCheckError; use crate::{ hir_def::{expr::HirExpression, stmt::HirStatement}, - node_interner::{ExprId, FuncId, NodeInterner, StmtId, TraitImplKey}, + node_interner::{ExprId, FuncId, NodeInterner, StmtId}, Type, }; @@ -65,8 +65,10 @@ pub fn type_check_func(interner: &mut NodeInterner, func_id: FuncId) -> Vec, TypeVariable, Span)>, pub arguments: Vec, pub return_type: Type, pub span: Span, @@ -62,6 +65,7 @@ pub struct TraitImpl { pub ident: Ident, pub typ: Type, pub trait_id: TraitId, + pub file: FileId, pub methods: Vec, // methods[i] is the implementation of trait.methods[i] for Type typ } diff --git a/compiler/noirc_frontend/src/hir_def/types.rs b/compiler/noirc_frontend/src/hir_def/types.rs index 110334f331e..15eb47e9f1b 100644 --- a/compiler/noirc_frontend/src/hir_def/types.rs +++ b/compiler/noirc_frontend/src/hir_def/types.rs @@ -560,6 +560,21 @@ impl Type { .all(|(_, field)| field.is_valid_for_program_input()), } } + + /// Returns the number of `Forall`-quantified type variables on this type. + /// Returns 0 if this is not a Type::Forall + pub fn generic_count(&self) -> usize { + match self { + Type::Forall(generics, _) => generics.len(), + Type::TypeVariable(type_variable, _) | Type::NamedGeneric(type_variable, _) => { + match &*type_variable.borrow() { + TypeBinding::Bound(binding) => binding.generic_count(), + TypeBinding::Unbound(_) => 0, + } + } + _ => 0, + } + } } impl std::fmt::Display for Type { @@ -1069,6 +1084,75 @@ impl Type { } } + /// Replace each NamedGeneric (and TypeVariable) in this type with a fresh type variable + pub(crate) fn instantiate_named_generics(&self, interner: &NodeInterner) -> Type { + let mut substitutions = HashMap::new(); + self.find_all_unbound_type_variables(interner, &mut substitutions); + self.substitute(&substitutions) + } + + /// For each unbound type variable in the current type, add a type binding to the given list + /// to bind the unbound type variable to a fresh type variable. + fn find_all_unbound_type_variables( + &self, + interner: &NodeInterner, + bindings: &mut TypeBindings, + ) { + match self { + Type::FieldElement + | Type::Integer(_, _) + | Type::Bool + | Type::Unit + | Type::TraitAsType(_) + | Type::Constant(_) + | Type::NotConstant + | Type::Error => (), + Type::Array(length, elem) => { + length.find_all_unbound_type_variables(interner, bindings); + elem.find_all_unbound_type_variables(interner, bindings); + } + Type::String(length) => length.find_all_unbound_type_variables(interner, bindings), + Type::FmtString(length, env) => { + length.find_all_unbound_type_variables(interner, bindings); + env.find_all_unbound_type_variables(interner, bindings); + } + Type::Struct(_, generics) => { + for generic in generics { + generic.find_all_unbound_type_variables(interner, bindings); + } + } + Type::Tuple(fields) => { + for field in fields { + field.find_all_unbound_type_variables(interner, bindings); + } + } + Type::Function(args, ret, env) => { + for arg in args { + arg.find_all_unbound_type_variables(interner, bindings); + } + ret.find_all_unbound_type_variables(interner, bindings); + env.find_all_unbound_type_variables(interner, bindings); + } + Type::MutableReference(elem) => { + elem.find_all_unbound_type_variables(interner, bindings); + } + Type::Forall(_, typ) => typ.find_all_unbound_type_variables(interner, bindings), + Type::TypeVariable(type_variable, _) | Type::NamedGeneric(type_variable, _) => { + match &*type_variable.borrow() { + TypeBinding::Bound(binding) => { + binding.find_all_unbound_type_variables(interner, bindings); + } + TypeBinding::Unbound(id) => { + if !bindings.contains_key(id) { + let fresh_type_variable = interner.next_type_variable(); + bindings.insert(*id, (type_variable.clone(), fresh_type_variable)); + } + } + } + } + } + } + /// Substitute any type variables found within this type with the /// given bindings if found. If a type variable is not found within /// the given TypeBindings, it is unchanged. diff --git a/compiler/noirc_frontend/src/lexer/lexer.rs b/compiler/noirc_frontend/src/lexer/lexer.rs index 2576b7a08ab..4a5ea56d8bc 100644 --- a/compiler/noirc_frontend/src/lexer/lexer.rs +++ b/compiler/noirc_frontend/src/lexer/lexer.rs @@ -6,17 +6,13 @@ use super::{ }; use acvm::FieldElement; use noirc_errors::{Position, Span}; -use std::str::Chars; -use std::{ - iter::{Peekable, Zip}, - ops::RangeFrom, -}; +use std::str::CharIndices; /// The job of the lexer is to transform an iterator of characters (`char_iter`) /// into an iterator of `SpannedToken`. Each `Token` corresponds roughly to 1 word or operator. /// Tokens are tagged with their location in the source file (a `Span`) for use in error reporting. pub struct Lexer<'a> { - char_iter: Peekable, RangeFrom>>, + chars: CharIndices<'a>, position: Position, done: bool, skip_comments: bool, @@ -41,13 +37,7 @@ impl<'a> Lexer<'a> { } pub fn new(source: &'a str) -> Self { - Lexer { - // We zip with the character index here to ensure the first char has index 0 - char_iter: source.chars().zip(0..).peekable(), - position: 0, - done: false, - skip_comments: true, - } + Lexer { chars: source.char_indices(), position: 0, done: false, skip_comments: true } } pub fn skip_comments(mut self, flag: bool) -> Self { @@ -57,21 +47,21 @@ impl<'a> Lexer<'a> { /// Iterates the cursor and returns the char at the new cursor position fn next_char(&mut self) -> Option { - let (c, index) = self.char_iter.next()?; - self.position = index; - Some(c) + let (position, ch) = self.chars.next()?; + self.position = position as u32; + Some(ch) } /// Peeks at the next char. Does not iterate the cursor fn peek_char(&mut self) -> Option { - self.char_iter.peek().map(|(c, _)| *c) + self.chars.clone().next().map(|(_, ch)| ch) } /// Peeks at the character two positions ahead. Does not iterate the cursor fn peek2_char(&mut self) -> Option { - let mut chars = self.char_iter.clone(); + let mut chars = self.chars.clone(); chars.next(); - chars.next().map(|(c, _)| c) + chars.next().map(|(_, ch)| ch) } /// Peeks at the next char and returns true if it is equal to the char argument diff --git a/compiler/noirc_frontend/src/monomorphization/mod.rs b/compiler/noirc_frontend/src/monomorphization/mod.rs index 6891bcf2872..0785f150a1e 100644 --- a/compiler/noirc_frontend/src/monomorphization/mod.rs +++ b/compiler/noirc_frontend/src/monomorphization/mod.rs @@ -24,7 +24,7 @@ use crate::{ stmt::{HirAssignStatement, HirLValue, HirLetStatement, HirPattern, HirStatement}, types, }, - node_interner::{self, DefinitionKind, NodeInterner, StmtId, TraitImplKey, TraitMethodId}, + node_interner::{self, DefinitionKind, NodeInterner, StmtId, TraitMethodId}, token::FunctionAttribute, ContractFunctionType, FunctionKind, Type, TypeBinding, TypeBindings, TypeVariableKind, Visibility, @@ -820,10 +820,7 @@ impl<'interner> Monomorphizer<'interner> { let trait_impl = self .interner - .get_trait_implementation(&TraitImplKey { - typ: self_type.follow_bindings(), - trait_id: method.trait_id, - }) + .lookup_trait_implementation(self_type.follow_bindings(), method.trait_id) .expect("ICE: missing trait impl - should be caught during type checking"); let hir_func_id = trait_impl.borrow().methods[method.method_index]; diff --git a/compiler/noirc_frontend/src/node_interner.rs b/compiler/noirc_frontend/src/node_interner.rs index 514a65d37a2..c527951ea0a 100644 --- a/compiler/noirc_frontend/src/node_interner.rs +++ b/compiler/noirc_frontend/src/node_interner.rs @@ -25,13 +25,6 @@ use crate::{ TypeBinding, TypeBindings, TypeVariable, TypeVariableId, TypeVariableKind, }; -#[derive(Eq, PartialEq, Hash, Clone)] -pub struct TraitImplKey { - pub typ: Type, - pub trait_id: TraitId, - // pub generics: Generics - TODO -} - type StructAttributes = Vec; /// The node interner is the central storage location of all nodes in Noir's Hir (the @@ -92,7 +85,19 @@ pub struct NodeInterner { // Trait implementation map // For each type that implements a given Trait ( corresponding TraitId), there should be an entry here // The purpose for this hashmap is to detect duplication of trait implementations ( if any ) - trait_implementations: HashMap>, + // + // Indexed by TraitImplIds + trait_implementations: Vec>, + + /// Trait implementations on each type. This is expected to always have the same length as + /// `self.trait_implementations`. + /// + /// For lack of a better name, this maps a trait id and type combination + /// to a corresponding impl if one is available for the type. Due to generics, + /// we cannot map from Type directly to impl, we need to iterate a Vec of all impls + /// of that trait to see if any type may match. This can be further optimized later + /// by splitting it up by type. + trait_implementation_map: HashMap>, /// Map from ExprId (referring to a Function/Method call) to its corresponding TypeBindings, /// filled out during type checking from instantiated variables. Used during monomorphization @@ -113,16 +118,27 @@ pub struct NodeInterner { /// may have both `impl Struct { fn foo(){} }` and `impl Struct { fn foo(){} }`. /// If this happens, the returned Vec will have 2 entries and we'll need to further /// disambiguate them by checking the type of each function. - struct_methods: HashMap<(StructId, String), Vec>, + struct_methods: HashMap<(StructId, String), Methods>, /// Methods on primitive types defined in the stdlib. - primitive_methods: HashMap<(TypeMethodKey, String), FuncId>, + primitive_methods: HashMap<(TypeMethodKey, String), Methods>, // For trait implementation functions, this is their self type and trait they belong to func_id_to_trait: HashMap, +} - /// Trait implementations on primitive types - primitive_trait_impls: HashMap<(Type, String), FuncId>, +/// Represents the methods on a given type that each share the same name. +/// +/// Methods are split into inherent methods and trait methods. If there is +/// ever a name that is defined on both a type directly, and defined indirectly +/// via a trait impl, the direct (inherent) name will always take precedence. +/// +/// Additionally, types can define specialized impls with methods of the same name +/// as long as these specialized impls do not overlap. E.g. `impl Struct` and `impl Struct` +#[derive(Default)] +pub struct Methods { + direct: Vec, + trait_impl_methods: Vec, } /// All the information from a function that is filled out during definition collection rather than @@ -257,6 +273,9 @@ impl TraitId { } } +#[derive(Debug, Eq, PartialEq, Hash, Clone, Copy)] +pub struct TraitImplId(usize); + #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct TraitMethodId { pub trait_id: TraitId, @@ -380,14 +399,14 @@ impl Default for NodeInterner { struct_attributes: HashMap::new(), type_aliases: Vec::new(), traits: HashMap::new(), - trait_implementations: HashMap::new(), + trait_implementations: Vec::new(), + trait_implementation_map: HashMap::new(), instantiation_bindings: HashMap::new(), field_indices: HashMap::new(), next_type_variable_id: std::cell::Cell::new(0), globals: HashMap::new(), struct_methods: HashMap::new(), primitive_methods: HashMap::new(), - primitive_trait_impls: HashMap::new(), }; // An empty block expression is used often, we add this into the `node` on startup @@ -618,9 +637,10 @@ impl NodeInterner { #[cfg(test)] pub fn push_test_function_definition(&mut self, name: String) -> FuncId { let id = self.push_fn(HirFunction::empty()); - let modifiers = FunctionModifiers::new(); + let mut modifiers = FunctionModifiers::new(); + modifiers.name = name; let module = ModuleId::dummy_id(); - self.push_function_definition(name, id, modifiers, module); + self.push_function_definition(id, modifiers, module); id } @@ -631,7 +651,6 @@ impl NodeInterner { module: ModuleId, ) -> DefinitionId { use ContractFunctionType::*; - let name = function.name.0.contents.clone(); // We're filling in contract_function_type and is_internal now, but these will be verified // later during name resolution. @@ -643,16 +662,16 @@ impl NodeInterner { contract_function_type: Some(if function.is_open { Open } else { Secret }), is_internal: Some(function.is_internal), }; - self.push_function_definition(name, id, modifiers, module) + self.push_function_definition(id, modifiers, module) } pub fn push_function_definition( &mut self, - name: String, func: FuncId, modifiers: FunctionModifiers, module: ModuleId, ) -> DefinitionId { + let name = modifiers.name.clone(); self.function_modifiers.insert(func, modifiers); self.function_modules.insert(func, module); self.push_definition(name, false, DefinitionKind::Function(func)) @@ -891,6 +910,7 @@ impl NodeInterner { self_type: &Type, method_name: String, method_id: FuncId, + is_trait_method: bool, ) -> Option { match self_type { Type::Struct(struct_type, _generics) => { @@ -901,68 +921,82 @@ impl NodeInterner { } let key = (id, method_name); - self.struct_methods.entry(key).or_default().push(method_id); + self.struct_methods.entry(key).or_default().add_method(method_id, is_trait_method); None } Type::Error => None, + Type::MutableReference(element) => { + self.add_method(element, method_name, method_id, is_trait_method) + } other => { let key = get_type_method_key(self_type).unwrap_or_else(|| { unreachable!("Cannot add a method to the unsupported type '{}'", other) }); - self.primitive_methods.insert((key, method_name), method_id) + self.primitive_methods + .entry((key, method_name)) + .or_default() + .add_method(method_id, is_trait_method); + None } } } - pub fn get_trait_implementation(&self, key: &TraitImplKey) -> Option> { - self.trait_implementations.get(key).cloned() + pub fn get_trait_implementation(&self, id: TraitImplId) -> Shared { + self.trait_implementations[id.0].clone() + } + + pub fn lookup_trait_implementation( + &self, + object_type: Type, + trait_id: TraitId, + ) -> Option> { + let impls = self.trait_implementation_map.get(&trait_id)?; + for (existing_object_type, impl_id) in impls { + let object_type = object_type.instantiate_named_generics(self); + let existing_object_type = existing_object_type.instantiate_named_generics(self); + + if object_type.try_unify(&existing_object_type).is_ok() { + return Some(self.get_trait_implementation(*impl_id)); + } + } + None } pub fn add_trait_implementation( &mut self, - key: &TraitImplKey, + object_type: Type, + trait_id: TraitId, trait_impl: Shared, - ) -> bool { - self.trait_implementations.insert(key.clone(), trait_impl.clone()); - match &key.typ { - Type::Struct(..) => { - for func_id in &trait_impl.borrow().methods { - let method_name = self.function_name(func_id).to_owned(); - self.add_method(&key.typ, method_name, *func_id); - } - true - } - Type::FieldElement - | Type::Unit - | Type::Array(..) - | Type::Integer(..) - | Type::Bool - | Type::Tuple(..) - | Type::String(..) - | Type::FmtString(..) - | Type::Function(..) - | Type::MutableReference(..) => { - for func_id in &trait_impl.borrow().methods { - let method_name = self.function_name(func_id).to_owned(); - let key = (key.typ.clone(), method_name); - self.primitive_trait_impls.insert(key, *func_id); + ) -> Option<(Span, FileId)> { + let id = TraitImplId(self.trait_implementations.len()); + + self.trait_implementations.push(trait_impl.clone()); + + if let Some(entries) = self.trait_implementation_map.get(&trait_id) { + // Check that this new impl does not overlap with any existing impls first + for (existing_object_type, existing_impl_id) in entries { + // Instantiate named generics so that S overlaps with S + let object_type = object_type.instantiate_named_generics(self); + let existing_object_type = existing_object_type.instantiate_named_generics(self); + + if object_type.try_unify(&existing_object_type).is_ok() { + // Overlapping impl + let existing_impl = &self.trait_implementations[existing_impl_id.0]; + let existing_impl = existing_impl.borrow(); + return Some((existing_impl.ident.span(), existing_impl.file)); } - true } - // We should allow implementing traits NamedGenerics will also eventually be possible once we support generics - // impl Foo for T - // but it's fine not to include these until we do. - Type::NamedGeneric(..) => false, - // prohibited are internal types (like NotConstant, TypeVariable, Forall, and Error) that - // aren't possible for users to write anyway - Type::TypeVariable(..) - | Type::Forall(..) - | Type::NotConstant - | Type::Constant(..) - | Type::TraitAsType(..) - | Type::Error => false, } + + for method in &trait_impl.borrow().methods { + let method_name = self.function_name(method).to_owned(); + self.add_method(&object_type, method_name, *method, true); + } + + let entries = self.trait_implementation_map.entry(trait_id).or_default(); + entries.push((object_type, id)); + None } /// Search by name for a method on the given struct. @@ -981,25 +1015,94 @@ impl NodeInterner { typ: &Type, id: StructId, method_name: &str, - check_type: bool, + force_type_check: bool, ) -> Option { let methods = self.struct_methods.get(&(id, method_name.to_owned()))?; // If there is only one method, just return it immediately. // It will still be typechecked later. - if !check_type && methods.len() == 1 { - return Some(methods[0]); + if !force_type_check { + if let Some(method) = methods.get_unambiguous() { + return Some(method); + } + } + + self.find_matching_method(typ, methods, method_name) + } + + /// Select the 1 matching method with an object type matching `typ` + fn find_matching_method( + &self, + typ: &Type, + methods: &Methods, + method_name: &str, + ) -> Option { + if let Some(method) = methods.find_matching_method(typ, self) { + Some(method) + } else { + // Failed to find a match for the type in question, switch to looking at impls + // for all types `T`, e.g. `impl Foo for T` + let key = &(TypeMethodKey::Generic, method_name.to_owned()); + let global_methods = self.primitive_methods.get(key)?; + global_methods.find_matching_method(typ, self) } + } + + /// Looks up a given method name on the given primitive type. + pub fn lookup_primitive_method(&self, typ: &Type, method_name: &str) -> Option { + let key = get_type_method_key(typ)?; + let methods = self.primitive_methods.get(&(key, method_name.to_owned()))?; + self.find_matching_method(typ, methods, method_name) + } + pub fn lookup_primitive_trait_method_mut( + &self, + typ: &Type, + method_name: &str, + ) -> Option { + let typ = Type::MutableReference(Box::new(typ.clone())); + self.lookup_primitive_method(&typ, method_name) + } +} + +impl Methods { + /// Get a single, unambiguous reference to a name if one exists. + /// If not, there may be multiple methods of the same name for a given + /// type or there may be no methods at all. + fn get_unambiguous(&self) -> Option { + if self.direct.len() == 1 { + Some(self.direct[0]) + } else if self.direct.is_empty() && self.trait_impl_methods.len() == 1 { + Some(self.trait_impl_methods[0]) + } else { + None + } + } + + fn add_method(&mut self, method: FuncId, is_trait_method: bool) { + if is_trait_method { + self.trait_impl_methods.push(method); + } else { + self.direct.push(method); + } + } + + /// Iterate through each method, starting with the direct methods + fn iter(&self) -> impl Iterator + '_ { + self.direct.iter().copied().chain(self.trait_impl_methods.iter().copied()) + } + + /// Select the 1 matching method with an object type matching `typ` + fn find_matching_method(&self, typ: &Type, interner: &NodeInterner) -> Option { // When adding methods we always check they do not overlap, so there should be // at most 1 matching method in this list. - for method in methods { - match self.function_meta(method).typ.instantiate(self).0 { + for method in self.iter() { + match interner.function_meta(&method).typ.instantiate(interner).0 { Type::Function(args, _, _) => { if let Some(object) = args.get(0) { // TODO #3089: This is dangerous! try_unify may commit type bindings even on failure if object.try_unify(typ).is_ok() { - return Some(*method); + return Some(method); } } } @@ -1007,29 +1110,8 @@ impl NodeInterner { other => unreachable!("Expected function type, found {other}"), } } - None } - - /// Looks up a given method name on the given primitive type. - pub fn lookup_primitive_method(&self, typ: &Type, method_name: &str) -> Option { - get_type_method_key(typ) - .and_then(|key| self.primitive_methods.get(&(key, method_name.to_owned())).copied()) - } - - pub fn lookup_primitive_trait_method(&self, typ: &Type, method_name: &str) -> Option { - self.primitive_trait_impls.get(&(typ.clone(), method_name.to_string())).copied() - } - - pub fn lookup_mut_primitive_trait_method( - &self, - typ: &Type, - method_name: &str, - ) -> Option { - self.primitive_trait_impls - .get(&(Type::MutableReference(Box::new(typ.clone())), method_name.to_string())) - .copied() - } } /// These are the primitive type variants that we support adding methods to @@ -1041,9 +1123,11 @@ enum TypeMethodKey { Array, Bool, String, + FmtString, Unit, Tuple, Function, + Generic, } fn get_type_method_key(typ: &Type) -> Option { @@ -1056,20 +1140,20 @@ fn get_type_method_key(typ: &Type) -> Option { Type::TypeVariable(_, TypeVariableKind::IntegerOrField) => Some(FieldOrInt), Type::Bool => Some(Bool), Type::String(_) => Some(String), + Type::FmtString(_, _) => Some(FmtString), Type::Unit => Some(Unit), Type::Tuple(_) => Some(Tuple), Type::Function(_, _, _) => Some(Function), + Type::NamedGeneric(_, _) => Some(Generic), Type::MutableReference(element) => get_type_method_key(element), // We do not support adding methods to these types Type::TypeVariable(_, _) - | Type::NamedGeneric(_, _) | Type::Forall(_, _) | Type::Constant(_) | Type::Error | Type::NotConstant | Type::Struct(_, _) - | Type::TraitAsType(_) - | Type::FmtString(_, _) => None, + | Type::TraitAsType(_) => None, } } diff --git a/compiler/noirc_frontend/src/parser/mod.rs b/compiler/noirc_frontend/src/parser/mod.rs index 4b76e2020b5..a6c631895cd 100644 --- a/compiler/noirc_frontend/src/parser/mod.rs +++ b/compiler/noirc_frontend/src/parser/mod.rs @@ -11,17 +11,13 @@ mod labels; #[allow(clippy::module_inception)] mod parser; -use std::sync::atomic::{AtomicU32, Ordering}; - use crate::token::{Keyword, Token}; use crate::{ast::ImportStatement, Expression, NoirStruct}; use crate::{ - BlockExpression, ExpressionKind, ForLoopStatement, Ident, IndexExpression, LetStatement, - MethodCallExpression, NoirFunction, NoirTrait, NoirTraitImpl, NoirTypeAlias, Path, PathKind, - Pattern, Recoverable, Statement, StatementKind, TypeImpl, UnresolvedType, UseTree, + Ident, LetStatement, NoirFunction, NoirTrait, NoirTraitImpl, NoirTypeAlias, Recoverable, + StatementKind, TypeImpl, UseTree, }; -use acvm::FieldElement; use chumsky::prelude::*; use chumsky::primitive::Container; pub use errors::ParserError; @@ -29,11 +25,6 @@ pub use errors::ParserErrorReason; use noirc_errors::Span; pub use parser::parse_program; -/// Counter used to generate unique names when desugaring -/// code in the parser requires the creation of fresh variables. -/// The parser is stateless so this is a static global instead. -static UNIQUE_NAME_COUNTER: AtomicU32 = AtomicU32::new(0); - #[derive(Debug, Clone)] pub(crate) enum TopLevelStatement { Function(NoirFunction), @@ -478,106 +469,6 @@ impl Precedence { } } -enum ForRange { - Range(/*start:*/ Expression, /*end:*/ Expression), - Array(Expression), -} - -impl ForRange { - /// Create a 'for' expression taking care of desugaring a 'for e in array' loop - /// into the following if needed: - /// - /// { - /// let fresh1 = array; - /// for fresh2 in 0 .. std::array::len(fresh1) { - /// let elem = fresh1[fresh2]; - /// ... - /// } - /// } - fn into_for(self, identifier: Ident, block: Expression, for_loop_span: Span) -> StatementKind { - match self { - ForRange::Range(start_range, end_range) => { - StatementKind::For(ForLoopStatement { identifier, start_range, end_range, block }) - } - ForRange::Array(array) => { - let array_span = array.span; - let start_range = ExpressionKind::integer(FieldElement::zero()); - let start_range = Expression::new(start_range, array_span); - - let next_unique_id = UNIQUE_NAME_COUNTER.fetch_add(1, Ordering::Relaxed); - let array_name = format!("$i{next_unique_id}"); - let array_span = array.span; - let array_ident = Ident::new(array_name, array_span); - - // let fresh1 = array; - let let_array = Statement { - kind: StatementKind::Let(LetStatement { - pattern: Pattern::Identifier(array_ident.clone()), - r#type: UnresolvedType::unspecified(), - expression: array, - }), - span: array_span, - }; - - // array.len() - let segments = vec![array_ident]; - let array_ident = - ExpressionKind::Variable(Path { segments, kind: PathKind::Plain }); - - let end_range = ExpressionKind::MethodCall(Box::new(MethodCallExpression { - object: Expression::new(array_ident.clone(), array_span), - method_name: Ident::new("len".to_string(), array_span), - arguments: vec![], - })); - let end_range = Expression::new(end_range, array_span); - - let next_unique_id = UNIQUE_NAME_COUNTER.fetch_add(1, Ordering::Relaxed); - let index_name = format!("$i{next_unique_id}"); - let fresh_identifier = Ident::new(index_name.clone(), array_span); - - // array[i] - let segments = vec![Ident::new(index_name, array_span)]; - let index_ident = - ExpressionKind::Variable(Path { segments, kind: PathKind::Plain }); - - let loop_element = ExpressionKind::Index(Box::new(IndexExpression { - collection: Expression::new(array_ident, array_span), - index: Expression::new(index_ident, array_span), - })); - - // let elem = array[i]; - let let_elem = Statement { - kind: StatementKind::Let(LetStatement { - pattern: Pattern::Identifier(identifier), - r#type: UnresolvedType::unspecified(), - expression: Expression::new(loop_element, array_span), - }), - span: array_span, - }; - - let block_span = block.span; - let new_block = BlockExpression(vec![ - let_elem, - Statement { kind: StatementKind::Expression(block), span: block_span }, - ]); - let new_block = Expression::new(ExpressionKind::Block(new_block), block_span); - let for_loop = Statement { - kind: StatementKind::For(ForLoopStatement { - identifier: fresh_identifier, - start_range, - end_range, - block: new_block, - }), - span: for_loop_span, - }; - - let block = ExpressionKind::Block(BlockExpression(vec![let_array, for_loop])); - StatementKind::Expression(Expression::new(block, for_loop_span)) - } - } - } -} - impl std::fmt::Display for TopLevelStatement { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { diff --git a/compiler/noirc_frontend/src/parser/parser.rs b/compiler/noirc_frontend/src/parser/parser.rs index cee824a51c9..6d934421783 100644 --- a/compiler/noirc_frontend/src/parser/parser.rs +++ b/compiler/noirc_frontend/src/parser/parser.rs @@ -26,8 +26,8 @@ use super::{ foldl_with_span, labels::ParsingRuleLabel, parameter_name_recovery, parameter_recovery, parenthesized, then_commit, then_commit_ignore, top_level_statement_recovery, ExprParser, - ForRange, NoirParser, ParsedModule, ParsedSubModule, ParserError, ParserErrorReason, - Precedence, TopLevelStatement, + NoirParser, ParsedModule, ParsedSubModule, ParserError, ParserErrorReason, Precedence, + TopLevelStatement, }; use super::{spanned, Item, ItemKind}; use crate::ast::{ @@ -38,11 +38,11 @@ use crate::parser::{force, ignore_then_commit, statement_recovery}; use crate::token::{Attribute, Attributes, Keyword, SecondaryAttribute, Token, TokenKind}; use crate::{ BinaryOp, BinaryOpKind, BlockExpression, ConstrainKind, ConstrainStatement, Distinctness, - FunctionDefinition, FunctionReturnType, FunctionVisibility, Ident, IfExpression, - InfixExpression, LValue, Lambda, Literal, NoirFunction, NoirStruct, NoirTrait, NoirTraitImpl, - NoirTypeAlias, Path, PathKind, Pattern, Recoverable, Statement, TraitBound, TraitImplItem, - TraitItem, TypeImpl, UnaryOp, UnresolvedTraitConstraint, UnresolvedTypeExpression, UseTree, - UseTreeKind, Visibility, + ForLoopStatement, ForRange, FunctionDefinition, FunctionReturnType, FunctionVisibility, Ident, + IfExpression, InfixExpression, LValue, Lambda, Literal, NoirFunction, NoirStruct, NoirTrait, + NoirTraitImpl, NoirTypeAlias, Path, PathKind, Pattern, Recoverable, Statement, TraitBound, + TraitImplItem, TraitItem, TypeImpl, UnaryOp, UnresolvedTraitConstraint, + UnresolvedTypeExpression, UseTree, UseTreeKind, Visibility, }; use chumsky::prelude::*; @@ -1482,7 +1482,9 @@ where .then_ignore(keyword(Keyword::In)) .then(for_range(expr_no_constructors)) .then(block_expr(statement)) - .map_with_span(|((identifier, range), block), span| range.into_for(identifier, block, span)) + .map_with_span(|((identifier, range), block), span| { + StatementKind::For(ForLoopStatement { identifier, range, block, span }) + }) } /// The 'range' of a for loop. Either an actual range `start .. end` or an array expression. diff --git a/compiler/noirc_frontend/src/tests.rs b/compiler/noirc_frontend/src/tests.rs index 91fce8d8862..6a1cf80accd 100644 --- a/compiler/noirc_frontend/src/tests.rs +++ b/compiler/noirc_frontend/src/tests.rs @@ -461,7 +461,7 @@ mod test { for (err, _file_id) in errors { match &err { - CompilationError::ResolveError(ResolverError::PathResolutionError( + CompilationError::ResolverError(ResolverError::PathResolutionError( PathResolutionError::Unresolved(ident), )) => { assert_eq!(ident, "NotAType"); @@ -533,18 +533,18 @@ mod test { } } - fn main() { - } + fn main() {} "; let errors = get_program_errors(src); assert!(!has_parser_error(&errors)); assert!(errors.len() == 1, "Expected 1 error, got: {:?}", errors); for (err, _file_id) in errors { match &err { - CompilationError::DefinitionError( - DefCollectorErrorKind::TraitImplNotAllowedFor { trait_path, span: _ }, - ) => { - assert_eq!(trait_path.as_string(), "Default"); + CompilationError::ResolverError(ResolverError::Expected { + expected, got, .. + }) => { + assert_eq!(expected, "type"); + assert_eq!(got, "function"); } _ => { panic!("No other errors are expected! Found = {:?}", err); @@ -658,18 +658,15 @@ mod test { "; let errors = get_program_errors(src); assert!(!has_parser_error(&errors)); - assert!(errors.len() == 1, "Expected 1 error, got: {:?}", errors); + assert!(errors.len() == 2, "Expected 2 errors, got: {:?}", errors); for (err, _file_id) in errors { match &err { - CompilationError::DefinitionError(DefCollectorErrorKind::Duplicate { - typ, - first_def, - second_def, - }) => { - assert_eq!(typ, &DuplicateType::TraitImplementation); - assert_eq!(first_def, "Default"); - assert_eq!(second_def, "Default"); - } + CompilationError::DefinitionError(DefCollectorErrorKind::OverlappingImpl { + .. + }) => (), + CompilationError::DefinitionError(DefCollectorErrorKind::OverlappingImplNote { + .. + }) => (), _ => { panic!("No other errors are expected! Found = {:?}", err); } @@ -699,18 +696,15 @@ mod test { "; let errors = get_program_errors(src); assert!(!has_parser_error(&errors)); - assert!(errors.len() == 1, "Expected 1 error, got: {:?}", errors); + assert!(errors.len() == 2, "Expected 2 errors, got: {:?}", errors); for (err, _file_id) in errors { match &err { - CompilationError::DefinitionError(DefCollectorErrorKind::Duplicate { - typ, - first_def, - second_def, - }) => { - assert_eq!(typ, &DuplicateType::TraitImplementation); - assert_eq!(first_def, "Default"); - assert_eq!(second_def, "Default"); - } + CompilationError::DefinitionError(DefCollectorErrorKind::OverlappingImpl { + .. + }) => (), + CompilationError::DefinitionError(DefCollectorErrorKind::OverlappingImplNote { + .. + }) => (), _ => { panic!("No other errors are expected! Found = {:?}", err); } @@ -810,7 +804,7 @@ mod test { assert!(errors.len() == 1, "Expected 1 error, got: {:?}", errors); // It should be regarding the unused variable match &errors[0].0 { - CompilationError::ResolveError(ResolverError::UnusedVariable { ident }) => { + CompilationError::ResolverError(ResolverError::UnusedVariable { ident }) => { assert_eq!(&ident.0.contents, "y"); } _ => unreachable!("we should only have an unused var error"), @@ -829,7 +823,7 @@ mod test { assert!(errors.len() == 1, "Expected 1 error, got: {:?}", errors); // It should be regarding the unresolved var `z` (Maybe change to undeclared and special case) match &errors[0].0 { - CompilationError::ResolveError(ResolverError::VariableNotDeclared { + CompilationError::ResolverError(ResolverError::VariableNotDeclared { name, span: _, }) => assert_eq!(name, "z"), @@ -848,7 +842,7 @@ mod test { assert!(errors.len() == 1, "Expected 1 error, got: {:?}", errors); for (compilation_error, _file_id) in errors { match compilation_error { - CompilationError::ResolveError(err) => { + CompilationError::ResolverError(err) => { match err { ResolverError::PathResolutionError(PathResolutionError::Unresolved( name, @@ -892,7 +886,7 @@ mod test { // `foo::bar` does not exist for (compilation_error, _file_id) in errors { match compilation_error { - CompilationError::ResolveError(err) => { + CompilationError::ResolverError(err) => { match err { ResolverError::UnusedVariable { ident } => { assert_eq!(&ident.0.contents, "z"); @@ -1069,12 +1063,13 @@ mod test { for (err, _file_id) in errors { match &err { - CompilationError::ResolveError(ResolverError::VariableNotDeclared { - name, .. + CompilationError::ResolverError(ResolverError::VariableNotDeclared { + name, + .. }) => { assert_eq!(name, "i"); } - CompilationError::ResolveError(ResolverError::NumericConstantInFormatString { + CompilationError::ResolverError(ResolverError::NumericConstantInFormatString { name, .. }) => { diff --git a/compiler/wasm/Cargo.toml b/compiler/wasm/Cargo.toml index b527e2de203..9ece26c6df4 100644 --- a/compiler/wasm/Cargo.toml +++ b/compiler/wasm/Cargo.toml @@ -22,16 +22,15 @@ wasm-bindgen.workspace = true serde.workspace = true js-sys.workspace = true cfg-if.workspace = true - -console_error_panic_hook = "0.1.7" -gloo-utils = { version = "0.1", features = ["serde"] } +console_error_panic_hook.workspace = true +gloo-utils.workspace = true log = "0.4.17" wasm-logger = "0.2.0" # This is an unused dependency, we are adding it # so that we can enable the js feature in getrandom. -getrandom = { version = "*", features = ["js"] } +getrandom = { workspace = true, features = ["js"] } [build-dependencies] -build-data = "0.1.3" +build-data.workspace = true diff --git a/compiler/wasm/fixtures/deps/lib-a/Nargo.toml b/compiler/wasm/fixtures/deps/lib-a/Nargo.toml index 3a02ccc1086..fa40b736619 100644 --- a/compiler/wasm/fixtures/deps/lib-a/Nargo.toml +++ b/compiler/wasm/fixtures/deps/lib-a/Nargo.toml @@ -2,7 +2,6 @@ name="lib_a" type="lib" authors = [""] -compiler_version = "0.1" [dependencies] lib_b = { path = "../lib-b" } diff --git a/compiler/wasm/fixtures/deps/lib-b/Nargo.toml b/compiler/wasm/fixtures/deps/lib-b/Nargo.toml index 99db61e4bfa..904b6e14b90 100644 --- a/compiler/wasm/fixtures/deps/lib-b/Nargo.toml +++ b/compiler/wasm/fixtures/deps/lib-b/Nargo.toml @@ -2,6 +2,5 @@ name="lib_b" type="lib" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/compiler/wasm/fixtures/deps/noir-script/Nargo.toml b/compiler/wasm/fixtures/deps/noir-script/Nargo.toml index 0df22c2be7e..7c8182a02ae 100644 --- a/compiler/wasm/fixtures/deps/noir-script/Nargo.toml +++ b/compiler/wasm/fixtures/deps/noir-script/Nargo.toml @@ -2,7 +2,6 @@ name="noir_wasm_testing" type="bin" authors = [""] -compiler_version = "0.1" [dependencies] lib_a = { path="../lib-a" } diff --git a/compiler/wasm/fixtures/simple/noir-script/Nargo.toml b/compiler/wasm/fixtures/simple/noir-script/Nargo.toml index a8d4eb100f2..75499a08245 100644 --- a/compiler/wasm/fixtures/simple/noir-script/Nargo.toml +++ b/compiler/wasm/fixtures/simple/noir-script/Nargo.toml @@ -2,6 +2,5 @@ name="noir_wasm_testing" type="bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/compiler/wasm/fixtures/simple/noir-script/src/main.nr b/compiler/wasm/fixtures/simple/noir-script/src/main.nr index 36fcc1916f5..b1889529f86 100644 --- a/compiler/wasm/fixtures/simple/noir-script/src/main.nr +++ b/compiler/wasm/fixtures/simple/noir-script/src/main.nr @@ -1,3 +1,3 @@ fn main(x : u64, y : pub u64) { - assert(x < y); + assert(x < y); } diff --git a/compiler/wasm/src/circuit.rs b/compiler/wasm/src/circuit.rs index 97f9ef9cf18..fdd9a7d9a20 100644 --- a/compiler/wasm/src/circuit.rs +++ b/compiler/wasm/src/circuit.rs @@ -6,7 +6,7 @@ use wasm_bindgen::prelude::*; #[wasm_bindgen] pub fn acir_read_bytes(bytes: Vec) -> JsValue { console_error_panic_hook::set_once(); - let circuit = Circuit::read(&*bytes).unwrap(); + let circuit = Circuit::deserialize_circuit(&bytes).unwrap(); ::from_serde(&circuit).unwrap() } @@ -14,7 +14,5 @@ pub fn acir_read_bytes(bytes: Vec) -> JsValue { pub fn acir_write_bytes(acir: JsValue) -> Vec { console_error_panic_hook::set_once(); let circuit: Circuit = JsValueSerdeExt::into_serde(&acir).unwrap(); - let mut bytes = Vec::new(); - circuit.write(&mut bytes).unwrap(); - bytes + Circuit::serialize_circuit(&circuit) } diff --git a/compiler/wasm/src/compile.rs b/compiler/wasm/src/compile.rs index ac6219ee625..e7fd3dd5212 100644 --- a/compiler/wasm/src/compile.rs +++ b/compiler/wasm/src/compile.rs @@ -1,8 +1,9 @@ use fm::FileManager; use gloo_utils::format::JsValueSerdeExt; -use js_sys::Object; +use js_sys::{JsString, Object}; use nargo::artifacts::{ contract::{PreprocessedContract, PreprocessedContractFunction}, + debug::DebugArtifact, program::PreprocessedProgram, }; use noirc_driver::{ @@ -27,6 +28,38 @@ export type DependencyGraph = { root_dependencies: readonly string[]; library_dependencies: Readonly>; } + +export type CompiledContract = { + noir_version: string; + name: string; + backend: string; + functions: Array; + events: Array; +}; + +export type CompiledProgram = { + noir_version: string; + backend: string; + abi: any; + bytecode: string; +} + +export type DebugArtifact = { + debug_symbols: Array; + file_map: Record; + warnings: Array; +}; + +export type CompileResult = ( + | { + contract: CompiledContract; + debug: DebugArtifact; + } + | { + program: CompiledProgram; + debug: DebugArtifact; + } +); "#; #[wasm_bindgen] @@ -34,6 +67,57 @@ extern "C" { #[wasm_bindgen(extends = Object, js_name = "DependencyGraph", typescript_type = "DependencyGraph")] #[derive(Clone, Debug, PartialEq, Eq)] pub type JsDependencyGraph; + + #[wasm_bindgen(extends = Object, js_name = "CompileResult", typescript_type = "CompileResult")] + #[derive(Clone, Debug, PartialEq, Eq)] + pub type JsCompileResult; + + #[wasm_bindgen(constructor, js_class = "Object")] + fn constructor() -> JsCompileResult; +} + +impl JsCompileResult { + const CONTRACT_PROP: &'static str = "contract"; + const PROGRAM_PROP: &'static str = "program"; + const DEBUG_PROP: &'static str = "debug"; + + pub fn new(resp: CompileResult) -> JsCompileResult { + let obj = JsCompileResult::constructor(); + match resp { + CompileResult::Contract { contract, debug } => { + js_sys::Reflect::set( + &obj, + &JsString::from(JsCompileResult::CONTRACT_PROP), + &::from_serde(&contract).unwrap(), + ) + .unwrap(); + + js_sys::Reflect::set( + &obj, + &JsString::from(JsCompileResult::DEBUG_PROP), + &::from_serde(&debug).unwrap(), + ) + .unwrap(); + } + CompileResult::Program { program, debug } => { + js_sys::Reflect::set( + &obj, + &JsString::from(JsCompileResult::PROGRAM_PROP), + &::from_serde(&program).unwrap(), + ) + .unwrap(); + + js_sys::Reflect::set( + &obj, + &JsString::from(JsCompileResult::DEBUG_PROP), + &::from_serde(&debug).unwrap(), + ) + .unwrap(); + } + }; + + obj + } } #[derive(Deserialize)] @@ -42,12 +126,17 @@ struct DependencyGraph { library_dependencies: HashMap>, } +pub enum CompileResult { + Contract { contract: PreprocessedContract, debug: DebugArtifact }, + Program { program: PreprocessedProgram, debug: DebugArtifact }, +} + #[wasm_bindgen] pub fn compile( entry_point: String, contracts: Option, dependency_graph: Option, -) -> Result { +) -> Result { console_error_panic_hook::set_once(); let dependency_graph: DependencyGraph = if let Some(dependency_graph) = dependency_graph { @@ -89,9 +178,8 @@ pub fn compile( nargo::ops::optimize_contract(compiled_contract, np_language, &is_opcode_supported) .expect("Contract optimization failed"); - let preprocessed_contract = preprocess_contract(optimized_contract); - - Ok(::from_serde(&preprocessed_contract).unwrap()) + let compile_output = preprocess_contract(optimized_contract); + Ok(JsCompileResult::new(compile_output)) } else { let compiled_program = compile_main(&mut context, crate_id, &compile_options, None, true) .map_err(|errs| { @@ -107,9 +195,8 @@ pub fn compile( nargo::ops::optimize_program(compiled_program, np_language, &is_opcode_supported) .expect("Program optimization failed"); - let preprocessed_program = preprocess_program(optimized_program); - - Ok(::from_serde(&preprocessed_program).unwrap()) + let compile_output = preprocess_program(optimized_program); + Ok(JsCompileResult::new(compile_output)) } } @@ -145,17 +232,30 @@ fn add_noir_lib(context: &mut Context, library_name: &CrateName) -> CrateId { prepare_dependency(context, &path_to_lib) } -fn preprocess_program(program: CompiledProgram) -> PreprocessedProgram { - PreprocessedProgram { +fn preprocess_program(program: CompiledProgram) -> CompileResult { + let debug_artifact = DebugArtifact { + debug_symbols: vec![program.debug], + file_map: program.file_map, + warnings: program.warnings, + }; + + let preprocessed_program = PreprocessedProgram { hash: program.hash, backend: String::from(BACKEND_IDENTIFIER), abi: program.abi, noir_version: NOIR_ARTIFACT_VERSION_STRING.to_string(), bytecode: program.circuit, - } + }; + + CompileResult::Program { program: preprocessed_program, debug: debug_artifact } } -fn preprocess_contract(contract: CompiledContract) -> PreprocessedContract { +fn preprocess_contract(contract: CompiledContract) -> CompileResult { + let debug_artifact = DebugArtifact { + debug_symbols: contract.functions.iter().map(|function| function.debug.clone()).collect(), + file_map: contract.file_map, + warnings: contract.warnings, + }; let preprocessed_functions = contract .functions .into_iter() @@ -168,13 +268,15 @@ fn preprocess_contract(contract: CompiledContract) -> PreprocessedContract { }) .collect(); - PreprocessedContract { + let preprocessed_contract = PreprocessedContract { noir_version: String::from(NOIR_ARTIFACT_VERSION_STRING), name: contract.name, backend: String::from(BACKEND_IDENTIFIER), functions: preprocessed_functions, events: contract.events, - } + }; + + CompileResult::Contract { contract: preprocessed_contract, debug: debug_artifact } } cfg_if::cfg_if! { diff --git a/compiler/wasm/test/browser/index.test.ts b/compiler/wasm/test/browser/index.test.ts index cad2ada0c61..8a3f82ffff9 100644 --- a/compiler/wasm/test/browser/index.test.ts +++ b/compiler/wasm/test/browser/index.test.ts @@ -47,10 +47,14 @@ describe('noir wasm', () => { const wasmCircuit = await compile('/main.nr'); const cliCircuit = await getPrecompiledSource(simpleScriptExpectedArtifact); + if (!('program' in wasmCircuit)) { + throw Error('Expected program to be present'); + } + // We don't expect the hashes to match due to how `noir_wasm` handles dependencies - expect(wasmCircuit.bytecode).to.eq(cliCircuit.bytecode); - expect(wasmCircuit.abi).to.deep.eq(cliCircuit.abi); - expect(wasmCircuit.backend).to.eq(cliCircuit.backend); + expect(wasmCircuit.program.bytecode).to.eq(cliCircuit.bytecode); + expect(wasmCircuit.program.abi).to.deep.eq(cliCircuit.abi); + expect(wasmCircuit.program.backend).to.eq(cliCircuit.backend); }).timeout(20e3); // 20 seconds }); @@ -87,12 +91,16 @@ describe('noir wasm', () => { }, }); + if (!('program' in wasmCircuit)) { + throw Error('Expected program to be present'); + } + const cliCircuit = await getPrecompiledSource(depsScriptExpectedArtifact); // We don't expect the hashes to match due to how `noir_wasm` handles dependencies - expect(wasmCircuit.bytecode).to.eq(cliCircuit.bytecode); - expect(wasmCircuit.abi).to.deep.eq(cliCircuit.abi); - expect(wasmCircuit.backend).to.eq(cliCircuit.backend); + expect(wasmCircuit.program.bytecode).to.eq(cliCircuit.bytecode); + expect(wasmCircuit.program.abi).to.deep.eq(cliCircuit.abi); + expect(wasmCircuit.program.backend).to.eq(cliCircuit.backend); }).timeout(20e3); // 20 seconds }); }); diff --git a/compiler/wasm/test/node/index.test.ts b/compiler/wasm/test/node/index.test.ts index 2b430abdca4..c0d5f88e407 100644 --- a/compiler/wasm/test/node/index.test.ts +++ b/compiler/wasm/test/node/index.test.ts @@ -24,10 +24,14 @@ describe('noir wasm compilation', () => { const wasmCircuit = await compile(join(__dirname, simpleScriptSourcePath)); const cliCircuit = await getPrecompiledSource(simpleScriptExpectedArtifact); + if (!('program' in wasmCircuit)) { + throw Error('Expected program to be present'); + } + // We don't expect the hashes to match due to how `noir_wasm` handles dependencies - expect(wasmCircuit.bytecode).to.eq(cliCircuit.bytecode); - expect(wasmCircuit.abi).to.deep.eq(cliCircuit.abi); - expect(wasmCircuit.backend).to.eq(cliCircuit.backend); + expect(wasmCircuit.program.bytecode).to.eq(cliCircuit.bytecode); + expect(wasmCircuit.program.abi).to.deep.eq(cliCircuit.abi); + expect(wasmCircuit.program.backend).to.eq(cliCircuit.backend); }).timeout(10e3); }); @@ -61,10 +65,14 @@ describe('noir wasm compilation', () => { const cliCircuit = await getPrecompiledSource(depsScriptExpectedArtifact); + if (!('program' in wasmCircuit)) { + throw Error('Expected program to be present'); + } + // We don't expect the hashes to match due to how `noir_wasm` handles dependencies - expect(wasmCircuit.bytecode).to.eq(cliCircuit.bytecode); - expect(wasmCircuit.abi).to.deep.eq(cliCircuit.abi); - expect(wasmCircuit.backend).to.eq(cliCircuit.backend); + expect(wasmCircuit.program.bytecode).to.eq(cliCircuit.bytecode); + expect(wasmCircuit.program.abi).to.deep.eq(cliCircuit.abi); + expect(wasmCircuit.program.backend).to.eq(cliCircuit.backend); }).timeout(10e3); }); }); diff --git a/cspell.json b/cspell.json index 4df858ffcfa..90d3963566d 100644 --- a/cspell.json +++ b/cspell.json @@ -15,6 +15,7 @@ "bitand", "blackbox", "brillig", + "cachix", "callsite", "callsites", "canonicalize", @@ -23,6 +24,7 @@ "clippy", "codegen", "codegens", + "codespan", "coeff", "combinators", "comptime", @@ -95,6 +97,7 @@ "sdiv", "secp256k1", "secp256r1", + "serde", "signedness", "smol", "splitn", diff --git a/docs/.gitignore b/docs/.gitignore index 96ecf9cbc03..c034d49ebde 100644 --- a/docs/.gitignore +++ b/docs/.gitignore @@ -20,4 +20,4 @@ npm-debug.log* yarn-debug.log* yarn-error.log* -package-lock.json +package-lock.json \ No newline at end of file diff --git a/docs/docs/examples/merkle-proof.mdx b/docs/docs/examples/merkle-proof.mdx index 6430780817c..832fb4bb55e 100644 --- a/docs/docs/examples/merkle-proof.mdx +++ b/docs/docs/examples/merkle-proof.mdx @@ -23,7 +23,7 @@ fn main(message : [Field; 62], index : Field, hashpath : [Field; 40], root : Fie The message is hashed using `hash_to_field`. The specific hash function that is being used is chosen by the backend. The only requirement is that this hash function can heuristically be used as a -random oracle. If only collision resistance is needed, then one can call `std::hash::pedersen` +random oracle. If only collision resistance is needed, then one can call `std::hash::pedersen_hash` instead. ```rust diff --git a/docs/docs/getting_started/00_nargo_installation.md b/docs/docs/getting_started/00_nargo_installation.md index 26a665a0d51..725c5f4d373 100644 --- a/docs/docs/getting_started/00_nargo_installation.md +++ b/docs/docs/getting_started/00_nargo_installation.md @@ -23,8 +23,8 @@ There are four approaches for installing Nargo: - [Option 1: Noirup](#option-1-noirup) - [Option 2: Binaries](#option-2-binaries) -- [Option 3: Install via Nix](#option-3-install-via-nix) -- [Option 4: Compile from Source](#option-4-compile-from-source) +- [Option 3: Compile from Source](#option-3-compile-from-source) +- [Option 4: WSL for Windows](#option-4-wsl-for-windows) Optionally you can also install [Noir VS Code extension] for syntax highlighting. @@ -98,21 +98,6 @@ echo '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.zshrc && \ source ~/.zshrc ``` -##### Windows (PowerShell) - -Open PowerShell as Administrator and run: - -```powershell -mkdir -f -p "$env:USERPROFILE\.nargo\bin\"; ` -Invoke-RestMethod -Method Get -Uri https://github.com/noir-lang/noir/releases/download/v0.4.1/nargo-x86_64-pc-windows-msvc.zip -Outfile "$env:USERPROFILE\.nargo\bin\nargo-x86_64-pc-windows-msvc.zip"; ` -Expand-Archive -Path "$env:USERPROFILE\.nargo\bin\nargo-x86_64-pc-windows-msvc.zip" -DestinationPath "$env:USERPROFILE\.nargo\bin\"; ` -$Reg = "Registry::HKLM\System\CurrentControlSet\Control\Session Manager\Environment"; ` -$OldPath = (Get-ItemProperty -Path "$Reg" -Name PATH).Path; ` -$NewPath = $OldPath + ’;’ + "$env:USERPROFILE\.nargo\bin\"; ` -Set-ItemProperty -Path "$Reg" -Name PATH –Value "$NewPath"; ` -$env:Path = [System.Environment]::GetEnvironmentVariable("Path","Machine") + ";" + [System.Environment]::GetEnvironmentVariable("Path","User") -``` - ##### Linux (Bash) ```bash @@ -220,7 +205,7 @@ code . #### Building and testing Assuming you are using `direnv` to populate your environment, building and testing the project can be done -with the typical `cargo build`, `cargo test`, and `cargo clippy` commands. You'll notice that the `cargo` version matches the version we specify in `flake.nix`, which is 1.66.0 at the time of this writing. +with the typical `cargo build`, `cargo test`, and `cargo clippy` commands. You'll notice that the `cargo` version matches the version we specify in `rust-toolchain.toml`, which is 1.71.1 at the time of this writing. If you want to build the entire project in an isolated sandbox, you can use Nix commands: @@ -233,6 +218,14 @@ If you have hesitations with using direnv, you can launch a subshell with `nix d Advanced: If you aren't using direnv nor launching your editor within the subshell, you can try to install Barretenberg and other global dependencies the package needs. This is an advanced workflow and likely won't receive support! +### Option 4: WSL (for Windows) + +The default backend for Noir (Barretenberg) doesn't provide Windows binaries at this time. For that reason, Noir cannot be installed nativerly. However, it is available by using Windows Subsystem for Linux (WSL). + +Step 1: Follow the instructions [here](https://learn.microsoft.com/en-us/windows/wsl/install) to install and run WSL. + +step 2: Follow the [Noirup instructions](#option-1-noirup). + ## Uninstalling Nargo ### Noirup diff --git a/docs/docs/getting_started/02_breakdown.md b/docs/docs/getting_started/02_breakdown.md index bc0e742fb4e..9a17f5d6360 100644 --- a/docs/docs/getting_started/02_breakdown.md +++ b/docs/docs/getting_started/02_breakdown.md @@ -66,7 +66,7 @@ The package section requires a number of fields including: - `name` (**required**) - the name of the package - `type` (**required**) - can be "bin", "lib", or "contract" to specify whether its a binary, library or Aztec contract - `authors` (optional) - authors of the project -- `compiler_version` (optional) - specifies the version of the compiler to use. This is not currently enforced by the compiler, but will be in future versions. +- `compiler_version` - specifies the version of the compiler to use. This is enforced by the compiler and follow's [Rust's versioning](https://doc.rust-lang.org/cargo/reference/manifest.html#the-version-field), so a `compiler_version = 0.18.0` will enforce Nargo version 0.18.0, `compiler_version = ^0.18.0` will enforce anything above 0.18.0 but below 0.19.0, etc. For more information, see how [Rust handles these operators](https://docs.rs/semver/latest/semver/enum.Op.html) - `description` (optional) - `entry` (optional) - a relative filepath to use as the entry point into your package (overrides the default of `src/lib.nr` or `src/main.nr`) - `backend` (optional) diff --git a/docs/docs/index.md b/docs/docs/index.md index 9ebe1d54944..75e1abf2932 100644 --- a/docs/docs/index.md +++ b/docs/docs/index.md @@ -79,7 +79,8 @@ ACIR Supported OPCODES: - Blake2s - Schnorr signature verification - MerkleMembership -- Pedersen +- Pedersen Commitment +- Pedersen Hash - HashToField ## Libraries diff --git a/docs/docs/language_concepts/data_types/01_integers.md b/docs/docs/language_concepts/data_types/01_integers.md index d9c5e20e795..3a115f2fc23 100644 --- a/docs/docs/language_concepts/data_types/01_integers.md +++ b/docs/docs/language_concepts/data_types/01_integers.md @@ -15,9 +15,16 @@ keywords: An integer type is a range constrained field type. The Noir frontend currently supports unsigned, arbitrary-sized integer types. +> **Note:** When an integer is defined in Noir without a specific type, it will default to `Field`. The one exception is for loop indices which default to `u64` since comparisons on `Field`s are not possible. + An integer type is specified first with the letter `u`, indicating its unsigned nature, followed by its length in bits (e.g. `32`). For example, a `u32` variable can store a value in the range of -$\\([0,2^{32}-1]\\)$: +$\\([0,2^{32}-1]\\)$. + +> **Note:** The default proving backend supports both even (e.g. `u16`, `u48`) and odd (e.g. `u5`, `u3`) +> sized integer types. + +Taking a look of how the type is used: ```rust fn main(x : Field, y : u32) { @@ -28,6 +35,3 @@ fn main(x : Field, y : u32) { `x`, `y` and `z` are all private values in this example. However, `x` is a field while `y` and `z` are unsigned 32-bit integers. If `y` or `z` exceeds the range $\\([0,2^{32}-1]\\)$, proofs created will be rejected by the verifier. - -> **Note:** The default backend supports both even (e.g. `u16`, `u48`) and odd (e.g. `u5`, `u3`) -> sized integer types. diff --git a/docs/docs/language_concepts/data_types/05_slices.mdx b/docs/docs/language_concepts/data_types/05_slices.mdx index 7fd07225a4e..1be0ec4a137 100644 --- a/docs/docs/language_concepts/data_types/05_slices.mdx +++ b/docs/docs/language_concepts/data_types/05_slices.mdx @@ -4,7 +4,7 @@ description: Explore the Slice data type in Noir. Understand its methods, see re keywords: [noir, slice type, methods, examples, subarrays] --- -import Experimental from '../../../src/components/Notes/_experimental.mdx'; +import Experimental from '@site/src/components/Notes/_experimental.mdx'; @@ -21,7 +21,7 @@ fn main() -> pub Field { } ``` -View the corresponding test file [here]([test-file]. +View the corresponding test file [here][test-file]. [test-file]: https://github.com/noir-lang/noir/blob/f387ec1475129732f72ba294877efdf6857135ac/crates/nargo_cli/tests/test_data_ssa_refactor/slices/src/main.nr diff --git a/docs/docs/language_concepts/data_types/06_vectors.mdx b/docs/docs/language_concepts/data_types/06_vectors.mdx index 4d3406f20c0..4617e90d038 100644 --- a/docs/docs/language_concepts/data_types/06_vectors.mdx +++ b/docs/docs/language_concepts/data_types/06_vectors.mdx @@ -4,7 +4,7 @@ description: Delve into the Vector data type in Noir. Learn about its methods, p keywords: [noir, vector type, methods, examples, dynamic arrays] --- -import Experimental from '../../../src/components/Notes/_experimental.mdx'; +import Experimental from '@site/src/components/Notes/_experimental.mdx'; diff --git a/docs/docs/migration_notes.md b/docs/docs/migration_notes.md index 48a8abcf22e..e87eb1feaba 100644 --- a/docs/docs/migration_notes.md +++ b/docs/docs/migration_notes.md @@ -6,6 +6,14 @@ keywords: [Noir, notes, migration, updating, upgrading] Noir is in full-speed development. Things break fast, wild, and often. This page attempts to leave some notes on errors you might encounter when upgrading and how to resolve them until proper patches are built. +## ≥0.19 + +### Enforcing `compiler_version` + +From this version on, the compiler will check for the `compiler_version` field in `Nargo.toml`, and will error if it doesn't match the current Nargo version in use. + +To update, please make sure this field in `Nargo.toml` matches the output of `nargo --version`. + ## ≥0.14 The index of the [for loops](./language_concepts/02_control_flow.md#loops) is now of type `u64` instead of `Field`. An example refactor would be: diff --git a/docs/docs/nargo/04_language_server.md b/docs/docs/nargo/04_language_server.md index 144cd249c4b..48c01465f6e 100644 --- a/docs/docs/nargo/04_language_server.md +++ b/docs/docs/nargo/04_language_server.md @@ -27,12 +27,12 @@ Currently, Noir provides a Language Client for Visual Studio Code via the [vscod When your language server is running correctly and the VSCode plugin is installed, you should see handy codelens buttons for compilation, measuring circuit size, execution, and tests: -![Compile and Execute](./../../static/img/codelens_compile_execute.png) -![Run test](../../static/img/codelens_run_test.png) +![Compile and Execute](@site/static/img/codelens_compile_execute.png) +![Run test](@site/static/img/codelens_run_test.png) You should also see your tests in the `testing` panel: -![Testing panel](./../../static/img/codelens_testing_panel.png) +![Testing panel](@site/static/img/codelens_testing_panel.png) ### Configuration diff --git a/docs/docs/noir_js/getting_started/01_tiny_noir_app.md b/docs/docs/noir_js/getting_started/01_tiny_noir_app.md index 1b0c8bfc353..c51ed61de52 100644 --- a/docs/docs/noir_js/getting_started/01_tiny_noir_app.md +++ b/docs/docs/noir_js/getting_started/01_tiny_noir_app.md @@ -6,6 +6,8 @@ keywords: [how to, guide, javascript, typescript, noir, barretenberg, zero-knowl NoirJS works both on the browser and on the server, and works for both ESM and CJS module systems. In this page, we will learn how can we write a simple test and a simple web app to verify the standard Noir example. +You can find the complete app code for this guide [here](https://github.com/noir-lang/tiny-noirjs-app). + ## Before we start :::note @@ -45,7 +47,7 @@ Go back to the previous folder and start a new project by running run `npm init` We'll need two `npm` packages. These packages will provide us the methods we need to run and verify proofs: ```bash -npm i @noir-lang/backend_barretenberg@^0.17.0 @noir-lang/noir_js@^0.17.0 +npm i @noir-lang/backend_barretenberg@^0.17.0 @noir-lang/noir_js@^0.17.0 ``` To serve our page, we can use a build tool such as `vite`. Because we're gonna use some `wasm` files, we need to install a plugin as well. Run: @@ -235,7 +237,7 @@ You're probably eager to see stuff happening, so go and run your app now! From your terminal, run `npm start` (or `yarn start`). If it doesn't open a browser for you, just visit `localhost:5173`. On a modern laptop, proof will generate in less than 100ms, and you'll see this: -![Getting Started 0](./../../../static/img/noir_getting_started_1.png) +![Getting Started 0](@site/static/img/noir_getting_started_1.png) If you're human, you shouldn't be able to understand anything on the "proof" box. That's OK. We like you, human. @@ -249,6 +251,8 @@ if (verification) display('logs', 'Verifying proof... ✅'); By saving, your app will refresh and here's our complete Tiny Noir App! +You can find the complete app code for this guide [here](https://github.com/noir-lang/tiny-noirjs-app). + ## Further Reading You can see how noirjs is used in a full stack Next.js hardhat application in the [noir-starter repo here](https://github.com/noir-lang/noir-starter/tree/main/next-hardhat). The example shows how to calculate a proof in the browser and verify it with a deployed Solidity verifier contract from noirjs. diff --git a/docs/docs/noir_js/reference/01_noirjs.md b/docs/docs/noir_js/reference/01_noirjs.md index d9e5a0c6115..0d6d5abbbff 100644 --- a/docs/docs/noir_js/reference/01_noirjs.md +++ b/docs/docs/noir_js/reference/01_noirjs.md @@ -58,10 +58,12 @@ await noirInstance.init(); This async method allows to execute a circuit to get its witness and return value. [`generateFinalProof`](#generatefinalproof) calls it for you, but you can call it directly (i.e. to feed directly to a backend, or to get the return value). +You can optionally provide a foreignCallHandler, to handle functions that should run outside of the prover (e.g. `std::println`) + ### Syntax ```js -async execute(inputs) +async execute(inputs, foreignCallHandler) ``` ### Parameters @@ -69,6 +71,7 @@ async execute(inputs) | Parameter | Type | Description | | --------- | ------ | ------------------------------------------------ | | `inputs` | Object | An object containing the inputs to your circuit. | +| `foreignCallHandler` (optional) | Function | A function handling the foreign call from your circuit | ### Returns @@ -81,6 +84,7 @@ async execute(inputs) ```js const { witness, returnValue } = await noir.execute(inputs) +const { witness, returnValue } = await noir.execute(inputs, (name, args) => console.log(`Received foreign call ${name} with arguments ${args}`)) ``` ## `generateFinalProof` diff --git a/docs/docs/standard_library/black_box_fns.md b/docs/docs/standard_library/black_box_fns.md index c758846b688..1dfabfe8f22 100644 --- a/docs/docs/standard_library/black_box_fns.md +++ b/docs/docs/standard_library/black_box_fns.md @@ -29,7 +29,8 @@ Here is a list of the current black box functions that are supported by UltraPlo - [SHA256](./cryptographic_primitives/hashes#sha256) - [Schnorr signature verification](./cryptographic_primitives/schnorr) - [Blake2s](./cryptographic_primitives/hashes#blake2s) -- [Pedersen](./cryptographic_primitives/hashes#pedersen) +- [Pedersen Hash](./cryptographic_primitives/hashes#pedersen_hash) +- [Pedersen Commitment](./cryptographic_primitives/hashes#pedersen_commitment) - [HashToField128Security](./cryptographic_primitives/hashes#hash_to_field) - [ECDSA signature verification](./cryptographic_primitives/ecdsa_sig_verification) - [Fixed base scalar multiplication](./cryptographic_primitives/scalar) diff --git a/docs/docs/standard_library/cryptographic_primitives/00_hashes.mdx b/docs/docs/standard_library/cryptographic_primitives/00_hashes.mdx index bb2621b6499..76745196681 100644 --- a/docs/docs/standard_library/cryptographic_primitives/00_hashes.mdx +++ b/docs/docs/standard_library/cryptographic_primitives/00_hashes.mdx @@ -7,7 +7,7 @@ keywords: [cryptographic primitives, Noir project, sha256, blake2s, pedersen, mimc_bn254, mimc, hash] --- -import BlackBoxInfo from '../../../src/components/Notes/_blackbox.mdx'; +import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; ## sha256 @@ -47,12 +47,12 @@ fn main() { -## pedersen +## pedersen_hash Given an array of Fields, returns the Pedersen hash. ```rust -fn pedersen(_input : [Field]) -> [Field; 2] +fn pedersen_hash(_input : [Field]) -> Field ``` example: @@ -60,7 +60,28 @@ example: ```rust fn main() { let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::pedersen(x); + let hash = std::hash::pedersen_hash(x); +} +``` + + + + + +## pedersen_commitment + +Given an array of Fields, returns the Pedersen commitment. + +```rust +fn pedersen_commitment(_input : [Field]) -> [Field; 2] +``` + +example: + +```rust +fn main() { + let x = [163, 117, 178, 149]; // some random bytes + let commitment = std::hash::pedersen_commitment(x); } ``` @@ -130,7 +151,7 @@ example: fn main() { let x = [163, 117, 178, 149]; // some random bytes - let hash = std::hash::mimc_bn254(x); + let hash = std::hash::mimc::mimc_bn254(x); } ``` diff --git a/docs/docs/standard_library/cryptographic_primitives/01_scalar.mdx b/docs/docs/standard_library/cryptographic_primitives/01_scalar.mdx index 0d7990859b5..c7eed820a80 100644 --- a/docs/docs/standard_library/cryptographic_primitives/01_scalar.mdx +++ b/docs/docs/standard_library/cryptographic_primitives/01_scalar.mdx @@ -4,7 +4,7 @@ description: See how you can perform scalar multiplications over a fixed base in keywords: [cryptographic primitives, Noir project, scalar multiplication] --- -import BlackBoxInfo from '../../../src/components/Notes/_blackbox.mdx'; +import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; ## scalar_mul::fixed_base_embedded_curve diff --git a/docs/docs/standard_library/cryptographic_primitives/02_schnorr.mdx b/docs/docs/standard_library/cryptographic_primitives/02_schnorr.mdx index 73737eb54bb..c184ce28120 100644 --- a/docs/docs/standard_library/cryptographic_primitives/02_schnorr.mdx +++ b/docs/docs/standard_library/cryptographic_primitives/02_schnorr.mdx @@ -4,7 +4,7 @@ description: Learn how you can verify Schnorr signatures using Noir keywords: [cryptographic primitives, Noir project, schnorr, signatures] --- -import BlackBoxInfo from '../../../src/components/Notes/_blackbox.mdx'; +import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; ## schnorr::verify_signature diff --git a/docs/docs/standard_library/cryptographic_primitives/03_ecdsa_sig_verification.mdx b/docs/docs/standard_library/cryptographic_primitives/03_ecdsa_sig_verification.mdx index 25185b062f7..72bce984821 100644 --- a/docs/docs/standard_library/cryptographic_primitives/03_ecdsa_sig_verification.mdx +++ b/docs/docs/standard_library/cryptographic_primitives/03_ecdsa_sig_verification.mdx @@ -4,7 +4,7 @@ description: Learn about the cryptographic primitives regarding ECDSA over the s keywords: [cryptographic primitives, Noir project, ecdsa, secp256k1, secp256r1, signatures] --- -import BlackBoxInfo from '../../../src/components/Notes/_blackbox.mdx'; +import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; Noir supports ECDSA signatures verification over the secp256k1 and secp256r1 curves. diff --git a/docs/docs/standard_library/cryptographic_primitives/05_eddsa.mdx b/docs/docs/standard_library/cryptographic_primitives/05_eddsa.mdx index 39dfb604669..9a5beb55ee9 100644 --- a/docs/docs/standard_library/cryptographic_primitives/05_eddsa.mdx +++ b/docs/docs/standard_library/cryptographic_primitives/05_eddsa.mdx @@ -4,7 +4,7 @@ description: Learn about the cryptographic primitives regarding EdDSA keywords: [cryptographic primitives, Noir project, eddsa, signatures] --- -import BlackBoxInfo from '../../../src/components/Notes/_blackbox.mdx'; +import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; ## eddsa::eddsa_poseidon_verify diff --git a/docs/docs/standard_library/merkle_trees.md b/docs/docs/standard_library/merkle_trees.md index 9761105f4f2..dc383a1426b 100644 --- a/docs/docs/standard_library/merkle_trees.md +++ b/docs/docs/standard_library/merkle_trees.md @@ -17,7 +17,7 @@ keywords: ## compute_merkle_root -Returns the root of the tree from the provided leaf and its hash path, using a [Pedersen hash](cryptographic_primitives/00_hashes.mdx#pedersen). +Returns the root of the tree from the provided leaf and its hash path, using a [Pedersen hash](cryptographic_primitives/00_hashes.mdx#pedersen_hash). ```rust fn compute_merkle_root(leaf : Field, index : Field, hash_path: [Field]) -> Field diff --git a/docs/docusaurus.config.js b/docs/docusaurus.config.js index ff07b5697ce..5128a99b000 100644 --- a/docs/docusaurus.config.js +++ b/docs/docusaurus.config.js @@ -45,9 +45,6 @@ const config = { label: 'dev', path: 'dev', }, - '0.7.1': { - label: '0.7.1 / 0.8.0', - }, }, editUrl: ({ versionDocsDirPath, docPath }) => `https://github.com/noir-lang/noir/edit/master/docs/${versionDocsDirPath}/${docPath}`, @@ -62,7 +59,7 @@ const config = { themeConfig: /** @type {import('@docusaurus/preset-classic').ThemeConfig} */ - ({ + { // Replace with your project's social card navbar: { logo: { @@ -87,8 +84,7 @@ const config = { metadata: [ { name: 'Noir', - content: - 'noir, programming, language, documentation, zk, zero-knowledge, l2, crypto, layer2, ethereum', + content: 'noir, programming, language, documentation, zk, zero-knowledge, l2, crypto, layer2, ethereum', }, ], footer: { @@ -149,7 +145,7 @@ const config = { indexName: 'noir-lang', }, - }), + }, }; module.exports = config; diff --git a/docs/package.json b/docs/package.json index edf4bba0686..3d71493c0ff 100644 --- a/docs/package.json +++ b/docs/package.json @@ -4,7 +4,8 @@ "private": true, "scripts": { "start": "docusaurus start", - "build": "docusaurus build" + "build": "docusaurus build", + "setStable": "node ./scripts/setStable.js" }, "dependencies": { "@docusaurus/core": "^2.4.0", diff --git a/docs/scripts/setStable.js b/docs/scripts/setStable.js new file mode 100644 index 00000000000..d0954cd6708 --- /dev/null +++ b/docs/scripts/setStable.js @@ -0,0 +1,41 @@ +/* eslint-disable */ +const fs = require('fs'); +const path = require('path'); +const axios = require('axios'); +const { release } = require('os'); + +const IGNORE_VERSIONS = ['0.16.0']; +const NUMBER_OF_VERSIONS_TO_SHOW = 2; + +async function main() { + const versionsFile = path.join(__dirname, '../versions.json'); + + const axiosOpts = { + params: { per_page: 100 }, + }; + + console.log(process.env.GITHUB_TOKEN); + // cool if you have a GITHUB_TOKEN because of rate limiting + // but fine if you don't + if (process.env.GITHUB_TOKEN) axiosOpts.headers = { Authorization: `token ${process.env.GITHUB_TOKEN}` }; + + const { data } = await axios.get('https://api.github.com/repos/noir-lang/noir/releases', axiosOpts); + + const all = data.map((release) => release.tag_name); + console.log('All versions: ', all); + const aztecs = data.filter((release) => release.tag_name.includes('aztec')).map((release) => release.tag_name); + console.log('Removing aztecs: ', aztecs); + const prereleases = data.filter((release) => !release.prerelease).map((release) => release.tag_name); + console.log('Removing prereleases: ', prereleases); + + const stables = data + .filter((release) => !release.prerelease && !release.tag_name.includes('aztec')) + .filter((release) => !IGNORE_VERSIONS.includes(release.tag_name.replace('v', ''))) + .map((release) => release.tag_name.replace('v', '')) + .slice(0, NUMBER_OF_VERSIONS_TO_SHOW); + + console.log('Stables: ', stables); + fs.writeFileSync(versionsFile, JSON.stringify(stables, null, 2)); +} + +main(); diff --git a/docs/versioned_docs/version-0.10.5/getting_started/03_language_server.md b/docs/versioned_docs/version-0.10.5/getting_started/03_language_server.md index f2de55cfb7c..49bd1d24675 100644 --- a/docs/versioned_docs/version-0.10.5/getting_started/03_language_server.md +++ b/docs/versioned_docs/version-0.10.5/getting_started/03_language_server.md @@ -25,8 +25,8 @@ Currently, Noir provides a Language Client for Visual Studio Code via the [vscod When you language server is running correctly and the VSCode plugin is installed, you should see handy codelens buttons for compilation, execution, and tests: -![Compile and Execute](./../../../static/img/codelens_compile_execute.png) -![Run test](../../../static/img/codelens_run_test.png) +![Compile and Execute](@site/static/img/codelens_compile_execute.png) +![Run test](@site/static/img/codelens_run_test.png) ### Configuration diff --git a/docs/versioned_docs/version-0.17.0/examples/merkle-proof.mdx b/docs/versioned_docs/version-0.17.0/examples/merkle-proof.mdx new file mode 100644 index 00000000000..6430780817c --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/examples/merkle-proof.mdx @@ -0,0 +1,48 @@ +--- +title: Merkle Proof Membership +description: + Learn how to use merkle membership proof in Noir to prove that a given leaf is a member of a + merkle tree with a specified root, at a given index. +keywords: + [merkle proof, merkle membership proof, Noir, rust, hash function, Pedersen, sha256, merkle tree] +--- + +Let's walk through an example of a merkle membership proof in Noir that proves that a given leaf is +in a merkle tree. + +```rust +use dep::std; + +fn main(message : [Field; 62], index : Field, hashpath : [Field; 40], root : Field) { + let leaf = std::hash::hash_to_field(message); + let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); + assert(merkle_root == root); +} + +``` + +The message is hashed using `hash_to_field`. The specific hash function that is being used is chosen +by the backend. The only requirement is that this hash function can heuristically be used as a +random oracle. If only collision resistance is needed, then one can call `std::hash::pedersen` +instead. + +```rust +let leaf = std::hash::hash_to_field(message); +``` + +The leaf is then passed to a compute_merkle_root function with the root, index and hashpath. The returned root can then be asserted to be the same as the provided root. + +```rust +let merkle_root = std::merkle::compute_merkle_root(leaf, index, hashpath); +assert (merkle_root == root); +``` + +> **Note:** It is possible to re-implement the merkle tree implementation without standard library. +> However, for most usecases, it is enough. In general, the standard library will always opt to be +> as conservative as possible, while striking a balance with efficiency. + +An example, the merkle membership proof, only requires a hash function that has collision +resistance, hence a hash function like Pedersen is allowed, which in most cases is more efficient +than the even more conservative sha256. + +[View an example on the starter repo](https://github.com/noir-lang/noir-examples/blob/3ea09545cabfa464124ec2f3ea8e60c608abe6df/stealthdrop/circuits/src/main.nr#L20) diff --git a/docs/versioned_docs/version-0.17.0/getting_started/00_nargo_installation.md b/docs/versioned_docs/version-0.17.0/getting_started/00_nargo_installation.md new file mode 100644 index 00000000000..4ff5fc46334 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/getting_started/00_nargo_installation.md @@ -0,0 +1,249 @@ +--- +title: Nargo Installation +description: + nargo is a command line tool for interacting with Noir programs (e.g. compiling, proving, + verifying and more). Learn how to install and use Nargo for your projects with this comprehensive + guide. +keywords: [Nargo, command line tool, Noir programs, installation guide, how to use Nargo] +--- + +`nargo` is a command line tool for interacting with Noir programs (e.g. compiling, proving, +verifying and more). + +Alternatively, the interactions can also be performed in [NoirJS](../noir_js/noir_js.md). + +### UltraPlonk + +Nargo versions <0.5.0 of `aztec_backend` and `aztec_wasm_backend` are based on the TurboPlonk +version of Aztec Backend, which lacks efficient implementations of useful primitives (e.g. Keccak256 in 18k constraints, ECDSA verification in 36k constraints) that the UltraPlonk version offers. + +## Installation + +There are four approaches for installing Nargo: + +- [Option 1: Noirup](#option-1-noirup) +- [Option 2: Binaries](#option-2-binaries) +- [Option 3: Compile from Source](#option-3-compile-from-source) +- [Option 4: WSL for Windows](#option-4-wsl-for-windows) + +Optionally you can also install [Noir VS Code extension] for syntax highlighting. + +### Option 1: Noirup + +If you're on OSX or Linux, the easiest way to start using Noir and Nargo is via noirup. Just open a +terminal and run: + +```bash +curl -L https://raw.githubusercontent.com/noir-lang/noirup/main/install | bash +``` + +Close the terminal, open another one, and run + +```bash +noirup +``` + +Done, you should have the latest version working. You can check with `nargo --version`. + +You can also install nightlies, specific versions +or branches, check out the [noirup repository](https://github.com/noir-lang/noirup) for more +information. + +#### GitHub Actions + +You can use `noirup` with GitHub Actions for CI/CD and automated testing. It is as simple as +installing `noirup` and running tests in your GitHub Action `yml` file. + +See the +[config file](https://github.com/TomAFrench/noir-hashes/blob/master/.github/workflows/noir.yml) in +this repo containing hash functions in Noir for an example. + +#### Nightly versions + +To install the nightly version of Noir (updated daily) run: + +```bash +noirup -n +``` + +### Option 2: Binaries + +See [GitHub Releases](https://github.com/noir-lang/noir/releases) for the latest and previous +platform specific binaries. + +#### Step 1 + +Paste and run the following in the terminal to extract and install the binary: + +> **macOS / Linux:** If you are prompted with `Permission denied` when running commands, prepend +> `sudo` and re-run it. + +##### macOS (Apple Silicon) + +```bash +mkdir -p $HOME/.nargo/bin && \ +curl -o $HOME/.nargo/bin/nargo-aarch64-apple-darwin.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.6.0/nargo-aarch64-apple-darwin.tar.gz && \ +tar -xvf $HOME/.nargo/bin/nargo-aarch64-apple-darwin.tar.gz -C $HOME/.nargo/bin/ && \ +echo '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.zshrc && \ +source ~/.zshrc +``` + +##### macOS (Intel) + +```bash +mkdir -p $HOME/.nargo/bin && \ +curl -o $HOME/.nargo/bin/nargo-x86_64-apple-darwin.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.6.0/nargo-x86_64-apple-darwin.tar.gz && \ +tar -xvf $HOME/.nargo/bin/nargo-x86_64-apple-darwin.tar.gz -C $HOME/.nargo/bin/ && \ +echo '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.zshrc && \ +source ~/.zshrc +``` + +##### Linux (Bash) + +```bash +mkdir -p $HOME/.nargo/bin && \ +curl -o $HOME/.nargo/bin/nargo-x86_64-unknown-linux-gnu.tar.gz -L https://github.com/noir-lang/noir/releases/download/v0.6.0/nargo-x86_64-unknown-linux-gnu.tar.gz && \ +tar -xvf $HOME/.nargo/bin/nargo-x86_64-unknown-linux-gnu.tar.gz -C $HOME/.nargo/bin/ && \ +echo -e '\nexport PATH=$PATH:$HOME/.nargo/bin' >> ~/.bashrc && \ +source ~/.bashrc +``` + +#### Step 2 + +Check if the installation was successful by running `nargo --help`. + +> **macOS:** If you are prompted with an OS alert, right-click and open the _nargo_ executable from +> Finder. Close the new terminal popped up and `nargo` should now be accessible. + +For a successful installation, you should see something similar to the following after running the +command: + +```sh +$ nargo --help + +Noir's package manager + +Usage: nargo + +Commands: + check Checks the constraint system for errors + codegen-verifier Generates a Solidity verifier smart contract for the program + compile Compile the program and its secret execution trace into ACIR format + new Create a new binary project + execute Executes a circuit to calculate its return value + prove Create proof for this program. The proof is returned as a hex encoded string + verify Given a proof and a program, verify whether the proof is valid + test Run the tests for this program + gates Counts the occurrences of different gates in circuit + help Print this message or the help of the given subcommand(s) +``` + +### Option 3: Compile from Source + +Due to the large number of native dependencies, Noir projects uses [Nix](https://nixos.org/) and [direnv](https://direnv.net/) to streamline the development experience. It helps mitigating ssues commonly associated with dependency management, such as conflicts between required package versions for different projects (often referred to as "dependency hell"). + +Combined with direnv, which automatically sets or unsets environment variables based on the directory, it further simplifies the development process by seamlessly integrating with the developer's shell, facilitating an efficient and reliable workflow for managing and deploying Noir projects with multiple dependencies. + +#### Setting up your environment + +For the best experience, please follow these instructions to setup your environment: + +1. Install Nix following [their guide](https://nixos.org/download.html) for your operating system. +2. Create the file `~/.config/nix/nix.conf` with the contents: + +```ini +experimental-features = nix-command +extra-experimental-features = flakes +``` + +3. Install direnv into your Nix profile by running: + +```sh +nix profile install nixpkgs#direnv +``` + +4. Add direnv to your shell following [their guide](https://direnv.net/docs/hook.html). + 1. For bash or zshell, add `eval "$(direnv hook bash)"` or `eval "$(direnv hook zsh)"` to your ~/.bashrc or ~/.zshrc file, respectively. +5. Restart your shell. + +#### Shell & editor experience + +Now that your environment is set up, you can get to work on the project. + +1. Clone the repository, such as: + +```sh +git clone git@github.com:noir-lang/noir +``` + +> Replacing `noir` with whichever repository you want to work on. + +2. Navigate to the directory: + +```sh +cd noir +``` + +> Replacing `noir` with whichever repository you cloned. + +3. You should see a **direnv error** because projects aren't allowed by default. Make sure you've reviewed and trust our `.envrc` file, then you need to run: + +```sh +direnv allow +``` + +4. Now, wait awhile for all the native dependencies to be built. This will take some time and direnv will warn you that it is taking a long time, but we just need to let it run. + +5. Once you are presented with your prompt again, you can start your editor within the project directory (we recommend [VSCode](https://code.visualstudio.com/)): + +```sh +code . +``` + +6. (Recommended) When launching VSCode for the first time, you should be prompted to install our recommended plugins. We highly recommend installing these for the best development experience. + +#### Building and testing + +Assuming you are using `direnv` to populate your environment, building and testing the project can be done +with the typical `cargo build`, `cargo test`, and `cargo clippy` commands. You'll notice that the `cargo` version matches the version we specify in `flake.nix`, which is 1.66.0 at the time of this writing. + +If you want to build the entire project in an isolated sandbox, you can use Nix commands: + +1. `nix build .` (or `nix build . -L` for verbose output) to build the project in a Nix sandbox. +2. `nix flake check` (or `nix flake check -L` for verbose output) to run clippy and tests in a Nix sandbox. + +#### Without `direnv` + +If you have hesitations with using direnv, you can launch a subshell with `nix develop` and then launch your editor from within the subshell. However, if VSCode was already launched in the project directory, the environment won't be updated. + +Advanced: If you aren't using direnv nor launching your editor within the subshell, you can try to install Barretenberg and other global dependencies the package needs. This is an advanced workflow and likely won't receive support! + +### Option 4: WSL (for Windows) + +Windows is not directly supported at this time. To install Noir on a Windows machine, it is recommended to use WSL. + +Step 1: Follow the instructions [here](https://learn.microsoft.com/en-us/windows/wsl/install) to install and run WSL. + +step 2: Follow the [Noirup instructions](#option-1-noirup). + +## Uninstalling Nargo + +### Noirup + +If you installed Noir with `noirup`, you can uninstall Noir by removing the files in `~/.nargo`, `~/nargo` and `~/noir_cache`. + +```bash +rm -r ~/.nargo +rm -r ~/nargo +rm -r ~/noir_cache +``` + +### Nix + +If you installed Noir with Nix or from source, you can remove the binary located at `~/.nix-profile/bin/nargo`. + +```bash +rm ~/.nix-profile/bin/nargo +``` + +[noir vs code extension]: https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir diff --git a/docs/versioned_docs/version-0.17.0/getting_started/01_hello_world.md b/docs/versioned_docs/version-0.17.0/getting_started/01_hello_world.md new file mode 100644 index 00000000000..8b4416beba1 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/getting_started/01_hello_world.md @@ -0,0 +1,147 @@ +--- +title: Create A Project +description: + Learn how to create and verify your first Noir program using Nargo, a programming language for + zero-knowledge proofs. +keywords: + [ + Nargo, + Noir, + zero-knowledge proofs, + programming language, + create Noir program, + verify Noir program, + step-by-step guide, + ] +--- + +Now that we have installed Nargo, it is time to make our first hello world program! + +## Create a Project Directory + +Noir code can live anywhere on your computer. Let us create a _projects_ folder in the home +directory to house our Noir programs. + +For Linux, macOS, and Windows PowerShell, create the directory and change directory into it by +running: + +```sh +mkdir ~/projects +cd ~/projects +``` + +For Windows CMD, run: + +```sh +> mkdir "%USERPROFILE%\projects" +> cd /d "%USERPROFILE%\projects" +``` + +## Create Our First Nargo Project + +Now that we are in the projects directory, create a new Nargo project by running: + +```sh +nargo new hello_world +``` + +> **Note:** `hello_world` can be any arbitrary project name, we are simply using `hello_world` for +> demonstration. +> +> In production, the common practice is to name the project folder as `circuits` for better +> identifiability when sitting alongside other folders in the codebase (e.g. `contracts`, `scripts`, +> `test`). + +A `hello_world` folder would be created. Similar to Rust, the folder houses _src/main.nr_ and +_Nargo.toml_ that contains the source code and environmental options of your Noir program +respectively. + +### Intro to Noir Syntax + +Let us take a closer look at _main.nr_. The default _main.nr_ generated should look like this: + +```rust +fn main(x : Field, y : pub Field) { + assert(x != y); +} +``` + +The first line of the program specifies the program's inputs: + +```rust +x : Field, y : pub Field +``` + +Program inputs in Noir are private by default (e.g. `x`), but can be labeled public using the +keyword `pub` (e.g. `y`). To learn more about private and public values, check the +[Data Types](../language_concepts/data_types) section. + +The next line of the program specifies its body: + +```rust +assert(x != y); +``` + +The Noir syntax `assert` can be interpreted as something similar to constraints in other zk-contract languages. + +For more Noir syntax, check the [Language Concepts](../language_concepts/comments) chapter. + +## Build In/Output Files + +Change directory into _hello_world_ and build in/output files for your Noir program by running: + +```sh +cd hello_world +nargo check +``` + +Two additional files would be generated in your project directory: + +_Prover.toml_ houses input values, and _Verifier.toml_ houses public values. + +## Prove Our Noir Program + +Now that the project is set up, we can create a proof of correct execution on our Noir program. + +Fill in input values for execution in the _Prover.toml_ file. For example: + +```toml +x = "1" +y = "2" +``` + +Prove the valid execution of your Noir program: + +```sh +nargo prove +``` + +A new folder _proofs_ would then be generated in your project directory, containing the proof file +`.proof`, where the project name is defined in Nargo.toml. + +The _Verifier.toml_ file would also be updated with the public values computed from program +execution (in this case the value of `y`): + +```toml +y = "0x0000000000000000000000000000000000000000000000000000000000000002" +``` + +> **Note:** Values in _Verifier.toml_ are computed as 32-byte hex values. + +## Verify Our Noir Program + +Once a proof is generated, we can verify correct execution of our Noir program by verifying the +proof file. + +Verify your proof by running: + +```sh +nargo verify +``` + +The verification will complete in silence if it is successful. If it fails, it will log the +corresponding error instead. + +Congratulations, you have now created and verified a proof for your very first Noir program! + +In the [next section](breakdown), we will go into more detail on each step performed. diff --git a/docs/versioned_docs/version-0.17.0/getting_started/02_breakdown.md b/docs/versioned_docs/version-0.17.0/getting_started/02_breakdown.md new file mode 100644 index 00000000000..bc0e742fb4e --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/getting_started/02_breakdown.md @@ -0,0 +1,198 @@ +--- +title: Project Breakdown +description: + Learn about the anatomy of a Nargo project, including the purpose of the Prover and Verifier TOML + files, and how to prove and verify your program. +keywords: + [Nargo, Nargo project, Prover.toml, Verifier.toml, proof verification, private asset transfer] +--- + +This section breaks down our hello world program in section _1.2_. We elaborate on the project +structure and what the `prove` and `verify` commands did in the previous section. + +## Anatomy of a Nargo Project + +Upon creating a new project with `nargo new` and building the in/output files with `nargo check` +commands, you would get a minimal Nargo project of the following structure: + + - src + - Prover.toml + - Verifier.toml + - Nargo.toml + +The source directory _src_ holds the source code for your Noir program. By default only a _main.nr_ +file will be generated within it. + +### Prover.toml + +_Prover.toml_ is used for specifying the input values for executing and proving the program. You can specify `toml` files with different names by using the `--prover-name` or `-p` flags, see the [Prover](#provertoml) section below. Optionally you may specify expected output values for prove-time checking as well. + +### Verifier.toml + +_Verifier.toml_ contains public in/output values computed when executing the Noir program. + +### Nargo.toml + +_Nargo.toml_ contains the environmental options of your project. It contains a "package" section and a "dependencies" section. + +Example Nargo.toml: + +```toml +[package] +name = "noirstarter" +type = "bin" +authors = ["Alice"] +compiler_version = "0.9.0" +description = "Getting started with Noir" +entry = "circuit/main.nr" +license = "MIT" + +[dependencies] +ecrecover = {tag = "v0.9.0", git = "https://github.com/colinnielsen/ecrecover-noir.git"} +``` + +Nargo.toml for a [workspace](../modules_packages_crates/workspaces) will look a bit different. For example: + +```toml +[workspace] +members = ["crates/a", "crates/b"] +default-member = "crates/a" +``` + +#### Package section + +The package section requires a number of fields including: + +- `name` (**required**) - the name of the package +- `type` (**required**) - can be "bin", "lib", or "contract" to specify whether its a binary, library or Aztec contract +- `authors` (optional) - authors of the project +- `compiler_version` (optional) - specifies the version of the compiler to use. This is not currently enforced by the compiler, but will be in future versions. +- `description` (optional) +- `entry` (optional) - a relative filepath to use as the entry point into your package (overrides the default of `src/lib.nr` or `src/main.nr`) +- `backend` (optional) +- `license` (optional) + +#### Dependencies section + +This is where you will specify any dependencies for your project. See the [Dependencies page](../modules_packages_crates/dependencies) for more info. + +`./proofs/` and `./contract/` directories will not be immediately visible until you create a proof or +verifier contract respectively. + +### main.nr + +The _main.nr_ file contains a `main` method, this method is the entry point into your Noir program. + +In our sample program, _main.nr_ looks like this: + +```rust +fn main(x : Field, y : Field) { + assert(x != y); +} +``` + +The parameters `x` and `y` can be seen as the API for the program and must be supplied by the +prover. Since neither `x` nor `y` is marked as public, the verifier does not supply any inputs, when +verifying the proof. + +The prover supplies the values for `x` and `y` in the _Prover.toml_ file. + +As for the program body, `assert` ensures the satisfaction of the condition (e.g. `x != y`) is +constrained by the proof of the execution of said program (i.e. if the condition was not met, the +verifier would reject the proof as an invalid proof). + +### Prover.toml + +The _Prover.toml_ file is a file which the prover uses to supply his witness values(both private and +public). + +In our hello world program the _Prover.toml_ file looks like this: + +```toml +x = "1" +y = "2" +``` + +When the command `nargo prove` is executed, two processes happen: + +1. Noir creates a proof that `x` which holds the value of `1` and `y` which holds the value of `2` + is not equal. This not equal constraint is due to the line `assert(x != y)`. + +2. Noir creates and stores the proof of this statement in the _proofs_ directory in a file called your-project.proof. So if your project is named "private_voting" (defined in the project Nargo.toml), the proof will be saved at `./proofs/private_voting.proof`. Opening this file will display the proof in hex format. + +#### Arrays of Structs + +The following code shows how to pass an array of structs to a Noir program to generate a proof. + +```rust +// main.nr +struct Foo { + bar: Field, + baz: Field, +} + +fn main(foos: [Foo; 3]) -> pub Field { + foos[2].bar + foos[2].baz +} +``` + +Prover.toml: + +```toml +[[foos]] # foos[0] +bar = 0 +baz = 0 + +[[foos]] # foos[1] +bar = 0 +baz = 0 + +[[foos]] # foos[2] +bar = 1 +baz = 2 +``` + +#### Custom toml files + +You can specify a `toml` file with a different name to use for proving by using the `--prover-name` or `-p` flags. + +This command looks for proof inputs in the default **Prover.toml** and generates the proof and saves it at `./proofs/.proof`: + +```bash +nargo prove +``` + +This command looks for proof inputs in the custom **OtherProver.toml** and generates proof and saves it at `./proofs/.proof`: + +```bash +nargo prove -p OtherProver +``` + +## Verifying a Proof + +When the command `nargo verify` is executed, two processes happen: + +1. Noir checks in the _proofs_ directory for a proof file with the project name (eg. test_project.proof) + +2. If that file is found, the proof's validity is checked + +> **Note:** The validity of the proof is linked to the current Noir program; if the program is +> changed and the verifier verifies the proof, it will fail because the proof is not valid for the +> _modified_ Noir program. + +In production, the prover and the verifier are usually two separate entities. A prover would +retrieve the necessary inputs, execute the Noir program, generate a proof and pass it to the +verifier. The verifier would then retrieve the public inputs from usually external sources and +verifies the validity of the proof against it. + +Take a private asset transfer as an example: + +A user on browser as the prover would retrieve private inputs (e.g. the user's private key) and +public inputs (e.g. the user's encrypted balance on-chain), compute the transfer, generate a proof +and submit it to the verifier smart contract. + +The verifier contract would then draw the user's encrypted balance directly from the blockchain and +verify the proof submitted against it. If the verification passes, additional functions in the +verifier contract could trigger (e.g. approve the asset transfer). + +Now that you understand the concepts, you'll probably want some editor feedback while you are writing more complex code. diff --git a/docs/versioned_docs/version-0.17.0/index.md b/docs/versioned_docs/version-0.17.0/index.md new file mode 100644 index 00000000000..9ebe1d54944 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/index.md @@ -0,0 +1,99 @@ +--- +title: Introducing Noir +description: + Learn about the public alpha release of Noir, a domain specific language heavily influenced by + Rust that compiles to an intermediate language which can be compiled to an arithmetic circuit or a + rank-1 constraint system. +keywords: + [ + Noir, + Domain Specific Language, + Rust, + Intermediate Language, + Arithmetic Circuit, + Rank-1 Constraint System, + Ethereum Developers, + Protocol Developers, + Blockchain Developers, + Proving System, + Smart Contract Language, + ] +slug: / +--- + +## What is Noir? + +Noir is a Domain Specific Language for SNARK proving systems. It has been designed to use any ACIR compatible proving system. + +It's design choices are influenced heavily by Rust and focuses on a simple, familiar syntax. + +## Who is Noir for? + +Noir can be used for a variety of purposes. + +### Solidity Developers + +Noir currently includes a command to create a Solidity contract which verifies your Noir program. This will +be modularised in the future; however, as of the alpha, you can use the [`nargo codegen-verifier`](./nargo/commands#nargo-codegen-verifier) command to create +a verifier contract. + +### Protocol Developers + +As a protocol developer, you may not want to use the Aztec backend due to it not being a fit for +your stack, or maybe you simply want to use a different proving system. Since Noir does not compile +to a specific proof system, it is possible for protocol developers to replace the PLONK-based +proving system with a different proving system altogether. + +### Blockchain developers + +As a blockchain developer, you will be constrained by parameters set by your blockchain (for example, the +proving system and smart contract language has been pre-defined). In order for you to use Noir in +your blockchain, a proving system backend and a smart contract interface +must be implemented for it. + +## What's new about Noir? + +Noir is simple and flexible in its design, as it does not compile immediately to a fixed +NP-complete language. Instead, Noir compiles to an intermediate language (ACIR), which itself can be compiled +to an arithmetic circuit (if choosing to target Aztec's barretenberg backend) or a rank-1 constraint system (if choosing to target an R1CS backend like Arkwork's Marlin backend, or others). + +This in itself brings up a few challenges within the design process, but allows one to decouple the programming language completely from the backend. This is similar in theory to LLVM. + +## Current Features + +Compiler: + +- Module System +- For expressions +- Arrays +- Bit Operations +- Binary operations (<, <=, >, >=, +, -, \*, /, %) [See documentation for an extensive list] +- Unsigned integers +- If statements +- Structures and Tuples +- Generics + +ACIR Supported OPCODES: + +- Sha256 +- Blake2s +- Schnorr signature verification +- MerkleMembership +- Pedersen +- HashToField + +## Libraries + +Noir does not currently have an official package manager. You can find a list of available Noir libraries in the [awesome-noir repo here](https://github.com/noir-lang/awesome-noir#libraries). + +Some libraries that are available today include: + +- [Standard Library](https://github.com/noir-lang/noir/tree/master/noir_stdlib) - the Noir Standard Library +- [Ethereum Storage Proof Verification](https://github.com/aragonzkresearch/noir-trie-proofs) - a library that contains the primitives necessary for RLP decoding (in the form of look-up table construction) and Ethereum state and storage proof verification (or verification of any trie proof involving 32-byte long keys) +- [BigInt](https://github.com/shuklaayush/noir-bigint) - a library that provides a custom BigUint56 data type, allowing for computations on large unsigned integers +- [ECrecover](https://github.com/colinnielsen/ecrecover-noir/tree/main) - a library to verify an ECDSA signature and return the source Ethereum address +- [Sparse Merkle Tree Verifier](https://github.com/vocdoni/smtverifier-noir/tree/main) - a library for verification of sparse Merkle trees +- [Signed Int](https://github.com/resurgencelabs/signed_int) - a library for accessing a custom Signed Integer data type, allowing access to negative numbers on Noir +- [Fraction](https://github.com/resurgencelabs/fraction) - a library for accessing fractional number data type in Noir, allowing results that aren't whole numbers + +See the section on [dependencies](./modules_packages_crates/dependencies) for more information. diff --git a/docs/versioned_docs/version-0.17.0/language_concepts/01_functions.md b/docs/versioned_docs/version-0.17.0/language_concepts/01_functions.md new file mode 100644 index 00000000000..47cdea0cf04 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/language_concepts/01_functions.md @@ -0,0 +1,225 @@ +--- +title: Functions +description: + Learn how to declare functions and methods in Noir, a programming language with Rust semantics. + This guide covers parameter declaration, return types, call expressions, and more. +keywords: [Noir, Rust, functions, methods, parameter declaration, return types, call expressions] +--- + +Functions in Noir follow the same semantics of Rust, though Noir does not support early returns. + +To declare a function the `fn` keyword is used. + +```rust +fn foo() {} +``` + +By default, functions are visible only within the package they are defined. To make them visible outside of that package (for example, as part of a [library](../modules_packages_crates/crates_and_packages.md#libraries)), you should mark them as `pub`: + +```rust +pub fn foo() {} +``` + +You can also restrict the visibility of the function to only the crate it was defined in, by specifying `pub(crate)`: + +```rust +pub(crate) fn foo() {} //foo can only be called within its crate +``` + +All parameters in a function must have a type and all types are known at compile time. The parameter +is pre-pended with a colon and the parameter type. Multiple parameters are separated using a comma. + +```rust +fn foo(x : Field, y : pub Field){} +``` + +The return type of a function can be stated by using the `->` arrow notation. The function below +states that the foo function must return a `Field`. If the function returns no value, then the arrow +is omitted. + +```rust +fn foo(x : Field, y : pub Field) -> Field { + x + y +} +``` + +Note that a `return` keyword is unneeded in this case - the last expression in a function's body is +returned. + +## Main function + +If you're writing a binary, the `main` function is the starting point of your program. You can pass all types of expressions to it, as long as they have a fixed size at compile time: + +```rust +fn main(x : Field) // this is fine: passing a Field +fn main(x : [Field; 2]) // this is also fine: passing a Field with known size at compile-time +fn main(x : (Field, bool)) // 👌: passing a (Field, bool) tuple means size 2 +fn main(x : str<5>) // this is fine, as long as you pass a string of size 5 + +fn main(x : Vec) // can't compile, has variable size +fn main(x : [Field]) // can't compile, has variable size +fn main(....// i think you got it by now +``` + +Keep in mind [tests](../nargo/02_testing.md) don't differentiate between `main` and any other function. The following snippet passes tests, but won't compile or prove: + +```rust +fn main(x : [Field]) { + assert(x[0] == 1); +} + +#[test] +fn test_one() { + main([1, 2]); +} +``` + +```bash +$ nargo test +[testing] Running 1 test functions +[testing] Testing test_one... ok +[testing] All tests passed + +$ nargo check +The application panicked (crashed). +Message: Cannot have variable sized arrays as a parameter to main +``` + +## Call Expressions + +Calling a function in Noir is executed by using the function name and passing in the necessary +arguments. + +Below we show how to call the `foo` function from the `main` function using a call expression: + +```rust +fn main(x : Field, y : Field) { + let z = foo(x); +} + +fn foo(x : Field) -> Field { + x + x +} +``` + +## Methods + +You can define methods in Noir on any struct type in scope. + +```rust +struct MyStruct { + foo: Field, + bar: Field, +} + +impl MyStruct { + fn new(foo: Field) -> MyStruct { + MyStruct { + foo, + bar: 2, + } + } + + fn sum(self) -> Field { + self.foo + self.bar + } +} + +fn main() { + let s = MyStruct::new(40); + assert(s.sum() == 42); +} +``` + +Methods are just syntactic sugar for functions, so if we wanted to we could also call `sum` as +follows: + +```rust +assert(MyStruct::sum(s) == 42); +``` + +It is also possible to specialize which method is chosen depending on the [generic](./06_generics.md) type that is used. In this example, the `foo` function returns different values depending on its type: + +```rust +struct Foo {} + +impl Foo { + fn foo(self) -> Field { 1 } +} + +impl Foo { + fn foo(self) -> Field { 2 } +} + +fn main() { + let f1: Foo = Foo{}; + let f2: Foo = Foo{}; + assert(f1.foo() + f2.foo() == 3); +} +``` + +Also note that impls with the same method name defined in them cannot overlap. For example, if we already have `foo` defined for `Foo` and `Foo` like we do above, we cannot also define `foo` in an `impl Foo` since it would be ambiguous which version of `foo` to choose. + +```rust +// Including this impl in the same project as the above snippet would +// cause an overlapping impls error +impl Foo { + fn foo(self) -> Field { 3 } +} +``` + +## Lambdas + +Lambdas are anonymous functions. They follow the syntax of Rust - `|arg1, arg2, ..., argN| return_expression`. + +```rust +let add_50 = |val| val + 50; +assert(add_50(100) == 150); +``` + +See [Lambdas](./08_lambdas.md) for more details. + +## Attributes + +Attributes are metadata that can be applied to a function, using the following syntax: `#[attribute(value)]`. + +Supported attributes include: + +- **builtin**: the function is implemented by the compiler, for efficiency purposes. +- **deprecated**: mark the function as _deprecated_. Calling the function will generate a warning: `warning: use of deprecated function` +- **field**: Used to enable conditional compilation of code depending on the field size. See below for more details +- **oracle**: mark the function as _oracle_; meaning it is an external unconstrained function, implemented in noir_js. See [Unconstrained](./05_unconstrained.md) and [NoirJS](../noir_js/noir_js.md) for more details. +- **test**: mark the function as unit tests. See [Tests](../nargo/02_testing.md) for more details + +### Field Attribute + +The field attribute defines which field the function is compatible for. The function is conditionally compiled, under the condition that the field attribute matches the Noir native field. +The field can be defined implicitly, by using the name of the elliptic curve usually associated to it - for instance bn254, bls12_381 - or explicitly by using the field (prime) order, in decimal or hexadecimal form. +As a result, it is possible to define multiple versions of a function with each version specialized for a different field attribute. This can be useful when a function requires different parameters depending on the underlying elliptic curve. + +Example: we define the function `foo()` three times below. Once for the default Noir bn254 curve, once for the field $\mathbb F_{23}$, which will normally never be used by Noir, and once again for the bls12_381 curve. + +```rust +#[field(bn254)] +fn foo() -> u32 { + 1 +} + +#[field(23)] +fn foo() -> u32 { + 2 +} + +// This commented code would not compile as foo would be defined twice because it is the same field as bn254 +// #[field(21888242871839275222246405745257275088548364400416034343698204186575808495617)] +// fn foo() -> u32 { +// 2 +// } + +#[field(bls12_381)] +fn foo() -> u32 { + 3 +} +``` + +If the field name is not known to Noir, it will discard the function. Field names are case insensitive. diff --git a/docs/versioned_docs/version-0.17.0/language_concepts/02_control_flow.md b/docs/versioned_docs/version-0.17.0/language_concepts/02_control_flow.md new file mode 100644 index 00000000000..a7f85360197 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/language_concepts/02_control_flow.md @@ -0,0 +1,44 @@ +--- +title: Control Flow +description: + Learn how to use loops and if expressions in the Noir programming language. Discover the syntax + and examples for for loops and if-else statements. +keywords: [Noir programming language, loops, for loop, if-else statements, Rust syntax] +--- + +## Loops + +Noir has one kind of loop: the `for` loop. `for` loops allow you to repeat a block of code multiple +times. + +The following block of code between the braces is run 10 times. + +```rust +for i in 0..10 { + // do something +}; +``` + +The index for loops is of type `u64`. + +## If Expressions + +Noir supports `if-else` statements. The syntax is most similar to Rust's where it is not required +for the statement's conditional to be surrounded by parentheses. + +```rust +let a = 0; +let mut x: u32 = 0; + +if a == 0 { + if a != 0 { + x = 6; + } else { + x = 2; + } +} else { + x = 5; + assert(x == 5); +} +assert(x == 2); +``` diff --git a/docs/versioned_docs/version-0.17.0/language_concepts/03_ops.md b/docs/versioned_docs/version-0.17.0/language_concepts/03_ops.md new file mode 100644 index 00000000000..da02b126059 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/language_concepts/03_ops.md @@ -0,0 +1,97 @@ +--- +title: Logical Operations +description: + Learn about the supported arithmetic and logical operations in the Noir programming language. + Discover how to perform operations on private input types, integers, and booleans. +keywords: + [ + Noir programming language, + supported operations, + arithmetic operations, + logical operations, + predicate operators, + bitwise operations, + short-circuiting, + backend, + ] +--- + +# Operations + +## Table of Supported Operations + +| Operation | Description | Requirements | +| :-------- | :------------------------------------------------------------: | -------------------------------------: | +| + | Adds two private input types together | Types must be private input | +| - | Subtracts two private input types together | Types must be private input | +| \* | Multiplies two private input types together | Types must be private input | +| / | Divides two private input types together | Types must be private input | +| ^ | XOR two private input types together | Types must be integer | +| & | AND two private input types together | Types must be integer | +| \| | OR two private input types together | Types must be integer | +| << | Left shift an integer by another integer amount | Types must be integer | +| >> | Right shift an integer by another integer amount | Types must be integer | +| ! | Bitwise not of a value | Type must be integer or boolean | +| < | returns a bool if one value is less than the other | Upper bound must have a known bit size | +| <= | returns a bool if one value is less than or equal to the other | Upper bound must have a known bit size | +| > | returns a bool if one value is more than the other | Upper bound must have a known bit size | +| >= | returns a bool if one value is more than or equal to the other | Upper bound must have a known bit size | +| == | returns a bool if one value is equal to the other | Both types must not be constants | +| != | returns a bool if one value is not equal to the other | Both types must not be constants | + +### Predicate Operators + +`<,<=, !=, == , >, >=` are known as predicate/comparison operations because they compare two values. +This differs from the operations such as `+` where the operands are used in _computation_. + +### Bitwise Operations Example + +```rust +fn main(x : Field) { + let y = x as u32; + let z = y & y; +} +``` + +`z` is implicitly constrained to be the result of `y & y`. The `&` operand is used to denote bitwise +`&`. + +> `x & x` would not compile as `x` is a `Field` and not an integer type. + +### Logical Operators + +Noir has no support for the logical operators `||` and `&&`. This is because encoding the +short-circuiting that these operators require can be inefficient for Noir's backend. Instead you can +use the bitwise operators `|` and `&` which operate indentically for booleans, just without the +short-circuiting. + +```rust +let my_val = 5; + +let mut flag = 1; +if (my_val > 6) | (my_val == 0) { + flag = 0; +} +assert(flag == 1); + +if (my_val != 10) & (my_val < 50) { + flag = 0; +} +assert(flag == 0); +``` + +### Shorthand operators + +Noir shorthand operators for most of the above operators, namely `+=, -=, *=, /=, %=, &=, |=, ^=, <<=`, and `>>=`. These allow for more concise syntax. For example: + +```rust +let mut i = 0; +i = i + 1; +``` + +could be written as: + +```rust +let mut i = 0; +i += 1; +``` diff --git a/docs/versioned_docs/version-0.17.0/language_concepts/04_assert.md b/docs/versioned_docs/version-0.17.0/language_concepts/04_assert.md new file mode 100644 index 00000000000..7427ec6cc63 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/language_concepts/04_assert.md @@ -0,0 +1,26 @@ +--- +title: Assert Function +description: + Learn about the assert function in Noir, which can be used to explicitly constrain the predicate or + comparison expression that follows to be true, and what happens if the expression is false at + runtime. +keywords: [Noir programming language, assert statement, predicate expression, comparison expression] +--- + +Noir includes a special `assert` function which will explicitly constrain the predicate/comparison +expression that follows to be true. If this expression is false at runtime, the program will fail to +be proven. Example: + +```rust +fn main(x : Field, y : Field) { + assert(x == y); +} +``` + +You can optionally provide a message to be logged when the assertion fails: + +```rust +assert(x == y, "x and y are not equal"); +``` + +> Assertions only work for predicate operations, such as `==`. If there's any ambiguity on the operation, the program will fail to compile. For example, it is unclear if `assert(x + y)` would check for `x + y == 0` or simply would return `true`. diff --git a/docs/versioned_docs/version-0.17.0/language_concepts/05_unconstrained.md b/docs/versioned_docs/version-0.17.0/language_concepts/05_unconstrained.md new file mode 100644 index 00000000000..6b621eda3eb --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/language_concepts/05_unconstrained.md @@ -0,0 +1,96 @@ +--- +title: Unconstrained Functions +description: "Learn about what unconstrained functions in Noir are, how to use them and when you'd want to." + +keywords: [Noir programming language, unconstrained, open] +--- + + + +Unconstrained functions are functions which do not constrain any of the included computation and allow for non-determinisitic computation. + +## Why? + +Zero-knowledge (ZK) domain-specific languages (DSL) enable developers to generate ZK proofs from their programs by compiling code down to the constraints of an NP complete language (such as R1CS or PLONKish languages). However, the hard bounds of a constraint system can be very limiting to the functionality of a ZK DSL. + +Enabling a circuit language to perform unconstrained execution is a powerful tool. Said another way, unconstrained execution lets developers generate witnesses from code that does not generate any constraints. Being able to execute logic outside of a circuit is critical for both circuit performance and constructing proofs on information that is external to a circuit. + +Fetching information from somewhere external to a circuit can also be used to enable developers to improve circuit efficiency. + +A ZK DSL does not just prove computation, but proves that some computation was handled correctly. Thus, it is necessary that when we switch from performing some operation directly inside of a circuit to inside of an unconstrained environment that the appropriate constraints are still laid down elsewhere in the circuit. + +## Example + +An in depth example might help drive the point home. This example comes from the excellent [post](https://discord.com/channels/1113924620781883405/1124022445054111926/1128747641853972590) by Tom in the Noir Discord. + +Let's look at how we can optimize a function to turn a `u72` into an array of `u8`s. + +```rust +fn main(num: u72) -> pub [u8; 8] { + let mut out: [u8; 8] = [0; 8]; + for i in 0..8 { + out[i] = (num >> (56 - (i * 8)) as u72 & 0xff) as u8; + } + + out +} +``` + +``` +Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 91 +Backend circuit size: 3619 +``` + +A lot of the operations in this function are optimized away by the compiler (all the bit-shifts turn into divisions by constants). However we can save a bunch of gates by casting to u8 a bit earlier. This automatically truncates the bit-shifted value to fit in a u8 which allows us to remove the XOR against 0xff. This saves us ~480 gates in total. + +```rust +fn main(num: u72) -> pub [u8; 8] { + let mut out: [u8; 8] = [0; 8]; + for i in 0..8 { + out[i] = (num >> (56 - (i * 8)) as u8; + } + + out +} +``` + +``` +Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 75 +Backend circuit size: 3143 +``` + +Those are some nice savings already but we can do better. This code is all constrained so we're proving every step of calculating out using num, but we don't actually care about how we calculate this, just that it's correct. This is where brillig comes in. + +It turns out that truncating a u72 into a u8 is hard to do inside a snark, each time we do as u8 we lay down 4 ACIR opcodes which get converted into multiple gates. It's actually much easier to calculate num from out than the other way around. All we need to do is multiply each element of out by a constant and add them all together, both relatively easy operations inside a snark. + +We can then run u72_to_u8 as unconstrained brillig code in order to calculate out, then use that result in our constrained function and assert that if we were to do the reverse calculation we'd get back num. This looks a little like the below: + +```rust +fn main(num: u72) -> pub [u8; 8] { + let out = u72_to_u8(num); + + let mut reconstructed_num: u72 = 0; + for i in 0..8 { + reconstructed_num += (out[i] as u72 << (56 - (8 * i))); + } + assert(num == reconstructed_num); + out +} + +unconstrained fn u72_to_u8(num: u72) -> [u8; 8] { + let mut out: [u8; 8] = [0; 8]; + for i in 0..8 { + out[i] = (num >> (56 - (i * 8))) as u8; + } + out +} +``` + +``` +Total ACIR opcodes generated for language PLONKCSat { width: 3 }: 78 +Backend circuit size: 2902 +``` + +This ends up taking off another ~250 gates from our circuit! We've ended up with more ACIR opcodes than before but they're easier for the backend to prove (resulting in fewer gates). + +Generally we want to use brillig whenever there's something that's easy to verify but hard to compute within the circuit. For example, if you wanted to calculate a square root of a number it'll be a much better idea to calculate this in brillig and then assert that if you square the result you get back your number. diff --git a/docs/versioned_docs/version-0.17.0/language_concepts/06_generics.md b/docs/versioned_docs/version-0.17.0/language_concepts/06_generics.md new file mode 100644 index 00000000000..b700bd5bc5b --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/language_concepts/06_generics.md @@ -0,0 +1,113 @@ +--- +title: Generics +description: Learn how to use Generics in Noir +keywords: [Noir, Rust, generics, functions, structs] +--- + +Generics allow you to use the same functions with multiple different concrete data types. You can +read more about the concept of generics in the Rust documentation +[here](https://doc.rust-lang.org/book/ch10-01-syntax.html). + +Here is a trivial example showing the identity function that supports any type. In Rust, it is +common to refer to the most general type as `T`. We follow the same convention in Noir. + +```rust +fn id(x: T) -> T { + x +} +``` + +## In Structs + +Generics are useful for specifying types in structs. For example, we can specify that a field in a +struct will be of a certain generic type. In this case `value` is of type `T`. + +```rust +struct RepeatedValue { + value: T, + count: Field, +} + +impl RepeatedValue { + fn new(value: T) -> Self { + Self { value, count: 1 } + } + + fn increment(mut repeated: Self) -> Self { + repeated.count += 1; + repeated + } + + fn print(self) { + for _i in 0 .. self.count { + dep::std::println(self.value); + } + } +} + +fn main() { + let mut repeated = RepeatedValue::new("Hello!"); + repeated = repeated.increment(); + repeated.print(); +} +``` + +The `print` function will print `Hello!` an arbitrary number of times, twice in this case. + +If we want to be generic over array lengths (which are type-level integers), we can use numeric +generics. Using these looks just like using regular generics, but these generics can resolve to +integers at compile-time, rather than resolving to types. Here's an example of a struct that is +generic over the size of the array it contains internally: + +```rust +struct BigInt { + limbs: [u32; N], +} + +impl BigInt { + // `N` is in scope of all methods in the impl + fn first(first: BigInt, second: BigInt) -> Self { + assert(first.limbs != second.limbs); + first + + fn second(first: BigInt, second: Self) -> Self { + assert(first.limbs != second.limbs); + second + } +} +``` + +## Calling functions on generic parameters + +Unlike Rust, Noir does not have traits, so how can one translate the equivalent of a trait bound in +Rust into Noir? That is, how can we write a function that is generic over some type `T`, while also +requiring there is a function like `eq: fn(T, T) -> bool` that works on the type? + +The answer is that we can translate this by passing in the function manually. Here's an example of +implementing array equality in Noir: + +```rust +fn array_eq(array1: [T; N], array2: [T; N], elem_eq: fn(T, T) -> bool) -> bool { + if array1.len() != array2.len() { + false + } else { + let mut result = true; + for i in 0 .. array1.len() { + result &= elem_eq(array1[i], array2[i]); + } + result + } +} + +fn main() { + assert(array_eq([1, 2, 3], [1, 2, 3], |a, b| a == b)); + + // We can use array_eq even for arrays of structs, as long as we have + // an equality function for these structs we can pass in + let array = [MyStruct::new(), MyStruct::new()]; + assert(array_eq(array, array, MyStruct::eq)); +} +``` + +You can see an example of generics in the tests +[here](https://github.com/noir-lang/noir/blob/master/crates/nargo_cli/tests/test_data/generics/src/main.nr). diff --git a/docs/versioned_docs/version-0.17.0/language_concepts/07_mutability.md b/docs/versioned_docs/version-0.17.0/language_concepts/07_mutability.md new file mode 100644 index 00000000000..4641521b1d9 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/language_concepts/07_mutability.md @@ -0,0 +1,92 @@ +--- +title: Mutability +description: + Learn about mutable variables, constants, and globals in Noir programming language. Discover how + to declare, modify, and use them in your programs. +keywords: [noir programming language, mutability in noir, mutable variables, constants, globals] +--- + +Variables in noir can be declared mutable via the `mut` keyword. Mutable variables can be reassigned +to via an assignment expression. + +```rust +let x = 2; +x = 3; // error: x must be mutable to be assigned to + +let mut y = 3; +let y = 4; // OK +``` + +The `mut` modifier can also apply to patterns: + +```rust +let (a, mut b) = (1, 2); +a = 11; // error: a must be mutable to be assigned to +b = 12; // OK + +let mut (c, d) = (3, 4); +c = 13; // OK +d = 14; // OK + +// etc. +let MyStruct { x: mut y } = MyStruct { x: a }; +// y is now in scope +``` + +Note that mutability in noir is local and everything is passed by value, so if a called function +mutates its parameters then the parent function will keep the old value of the parameters. + +```rust +fn main() -> Field { + let x = 3; + helper(x); + x // x is still 3 +} + +fn helper(mut x: i32) { + x = 4; +} +``` + +## Comptime Values + +:::warning + +The 'comptime' keyword was removed in version 0.10. The comptime keyword and syntax are currently still kept and parsed for backwards compatibility, but are now deprecated and will issue a warning when used. `comptime` has been removed because it is no longer needed for accessing arrays. + +::: + +## Globals + +Noir also supports global variables. However, they must be known at compile-time. The global type can also be inferred by the compiler entirely. Globals can also be used to specify array +annotations for function parameters and can be imported from submodules. + +```rust +global N: Field = 5; // Same as `global N: Field = 5` + +fn main(x : Field, y : [Field; N]) { + let res = x * N; + + assert(res == y[0]); + + let res2 = x * mysubmodule::N; + assert(res != res2); +} + +mod mysubmodule { + use dep::std; + + global N: Field = 10; + + fn my_helper() -> Field { + let x = N; + x + } +} +``` + +## Why only local mutability? + +Witnesses in a proving system are immutable in nature. Noir aims to _closely_ mirror this setting +without applying additional overhead to the user. Modeling a mutable reference is not as +straightforward as on conventional architectures and would incur some possibly unexpected overhead. diff --git a/docs/versioned_docs/version-0.17.0/language_concepts/08_lambdas.md b/docs/versioned_docs/version-0.17.0/language_concepts/08_lambdas.md new file mode 100644 index 00000000000..ae1e6aecab1 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/language_concepts/08_lambdas.md @@ -0,0 +1,80 @@ +--- +title: Lambdas +description: Learn how to use anonymous functions in Noir programming language. +keywords: [Noir programming language, lambda, closure, function, anonymous function] +--- + +## Introduction + +Lambdas are anonymous functions. The syntax is `|arg1, arg2, ..., argN| return_expression`. + +```rust +let add_50 = |val| val + 50; +assert(add_50(100) == 150); +``` + +A block can be used as the body of a lambda, allowing you to declare local variables inside it: + +```rust +let cool = || { + let x = 100; + let y = 100; + x + y +} + +assert(cool() == 200); +``` + +## Closures + +Inside the body of a lambda, you can use variables defined in the enclosing function. Such lambdas are called **closures**. In this example `x` is defined inside `main` and is accessed from within the lambda: + +```rust +fn main() { + let x = 100; + let closure = || x + 150; + assert(closure() == 250); +} +``` + +## Passing closures to higher-order functions + +It may catch you by surprise that the following code fails to compile: + +```rust +fn foo(f: fn () -> Field) -> Field { + f() +} + +fn main() { + let (x, y) = (50, 50); + assert(foo(|| x + y) == 100); // error :( +} +``` + +The reason is that the closure's capture environment affects its type - we have a closure that captures two Fields and `foo` +expects a regular function as an argument - those are incompatible. +:::note + +Variables contained within the `||` are the closure's parameters, and the expression that follows it is the closure's body. The capture environment is comprised of any variables used in the closure's body that are not parameters. + +E.g. in |x| x + y, y would be a captured variable, but x would not be, since it is a parameter of the closure. + +::: +The syntax for the type of a closure is `fn[env](args) -> ret_type`, where `env` is the capture environment of the closure - +in this example that's `(Field, Field)`. + +The best solution in our case is to make `foo` generic over the environment type of its parameter, so that it can be called +with closures with any environment, as well as with regular functions: + +```rust +fn foo(f: fn[Env]() -> Field) -> Field { + f() +} + +fn main() { + let (x, y) = (50, 50); + assert(foo(|| x + y) == 100); // compiles fine + assert(foo(|| 60) == 60); // compiles fine +} +``` diff --git a/docs/versioned_docs/version-0.17.0/language_concepts/09_comments.md b/docs/versioned_docs/version-0.17.0/language_concepts/09_comments.md new file mode 100644 index 00000000000..3bb4d2f25a4 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/language_concepts/09_comments.md @@ -0,0 +1,32 @@ +--- +title: Comments +description: + Learn how to write comments in Noir programming language. A comment is a line of code that is + ignored by the compiler, but it can be read by programmers. Single-line and multi-line comments + are supported in Noir. +keywords: [Noir programming language, comments, single-line comments, multi-line comments] +--- + +A comment is a line in your codebase which the compiler ignores, however it can be read by +programmers. + +Here is a single line comment: + +```rust +// This is a comment and is ignored +``` + +`//` is used to tell the compiler to ignore the rest of the line. + +Noir also supports multi-line block comments. Start a block comment with `/*` and end the block with `*/`. + +Noir does not natively support doc comments. You may be able to use [Rust doc comments](https://doc.rust-lang.org/reference/comments.html) in your code to leverage some Rust documentation build tools with Noir code. + +```rust +/* + This is a block comment describing a complex function. +*/ +fn main(x : Field, y : pub Field) { + assert(x != y); +} +``` diff --git a/docs/versioned_docs/version-0.17.0/language_concepts/10_distinct.md b/docs/versioned_docs/version-0.17.0/language_concepts/10_distinct.md new file mode 100644 index 00000000000..e7ff7f5017a --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/language_concepts/10_distinct.md @@ -0,0 +1,63 @@ +--- +title: Distinct Witnesses +--- + +The `distinct` keyword prevents repetitions of witness indices in the program's ABI. This ensures +that the witnesses being returned as public inputs are all unique. + +The `distinct` keyword is only used for return values on program entry points (usually the `main()` +function). + +When using `distinct` and `pub` simultaneously, `distinct` comes first. See the example below. + +You can read more about the problem this solves +[here](https://github.com/noir-lang/noir/issues/1183). + +## Example + +Without the `distinct` keyword, the following program + +```rust +fn main(x : pub Field, y : pub Field) -> pub [Field; 4] { + let a = 1; + let b = 1; + [x + 1, y, a, b] +} +``` + +compiles to + +```json +{ + //... + "abi": { + //... + "param_witnesses": { "x": [1], "y": [2] }, + "return_witnesses": [3, 2, 4, 4] + } +} +``` + +Whereas (with the `distinct` keyword) + +```rust +fn main(x : pub Field, y : pub Field) -> distinct pub [Field; 4] { + let a = 1; + let b = 1; + [x + 1, y, a, b] +} +``` + +compiles to + +```json +{ + //... + "abi": { + //... + "param_witnesses": { "x": [1], "y": [2] }, + //... + "return_witnesses": [3, 4, 5, 6] + } +} +``` diff --git a/docs/versioned_docs/version-0.17.0/language_concepts/11_shadowing.md b/docs/versioned_docs/version-0.17.0/language_concepts/11_shadowing.md new file mode 100644 index 00000000000..efd743e764f --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/language_concepts/11_shadowing.md @@ -0,0 +1,43 @@ +--- +title: Shadowing +--- + +Noir allows for inheriting variables' values and re-declaring them with the same name similar to Rust, known as shadowing. + +For example, the following function is valid in Noir: + +```rust +fn main() { + let x = 5; + + { + let x = x * 2; + assert (x == 10); + } + + assert (x == 5); +} +``` + +In this example, a variable x is first defined with the value 5. + +The local scope that follows shadows the original x, i.e. creates a local mutable x based on the value of the original x. It is given a value of 2 times the original x. + +When we return to the main scope, x once again refers to just the original x, which stays at the value of 5. + +## Temporal mutability + +One way that shadowing is useful, in addition to ergonomics across scopes, is for temporarily mutating variables. + +```rust +fn main() { + let age = 30; + // age = age + 5; // Would error as `age` is immutable by default. + + let mut age = age + 5; // Temporarily mutates `age` with a new value. + + let age = age; // Locks `age`'s mutability again. + + assert (age == 35); +} +``` diff --git a/docs/versioned_docs/version-0.17.0/language_concepts/data_types.md b/docs/versioned_docs/version-0.17.0/language_concepts/data_types.md new file mode 100644 index 00000000000..d546cc463a8 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/language_concepts/data_types.md @@ -0,0 +1,96 @@ +--- +title: Data Types +description: + Get a clear understanding of the two categories of Noir data types - primitive types and compound + types. Learn about their characteristics, differences, and how to use them in your Noir + programming. +keywords: + [ + noir, + data types, + primitive types, + compound types, + private types, + public types, + ] +--- + +Every value in Noir has a type, which determines which operations are valid for it. + +All values in Noir are fundamentally composed of `Field` elements. For a more approachable +developing experience, abstractions are added on top to introduce different data types in Noir. + +Noir has two category of data types: primitive types (e.g. `Field`, integers, `bool`) and compound +types that group primitive types (e.g. arrays, tuples, structs). Each value can either be private or +public. + +## Private & Public Types + +A **private value** is known only to the Prover, while a **public value** is known by both the +Prover and Verifier. Mark values as `private` when the value should only be known to the prover. All +primitive types (including individual fields of compound types) in Noir are private by default, and +can be marked public when certain values are intended to be revealed to the Verifier. + +> **Note:** For public values defined in Noir programs paired with smart contract verifiers, once +> the proofs are verified on-chain the values can be considered known to everyone that has access to +> that blockchain. + +Public data types are treated no differently to private types apart from the fact that their values +will be revealed in proofs generated. Simply changing the value of a public type will not change the +circuit (where the same goes for changing values of private types as well). + +_Private values_ are also referred to as _witnesses_ sometimes. + +> **Note:** The terms private and public when applied to a type (e.g. `pub Field`) have a different +> meaning than when applied to a function (e.g. `pub fn foo() {}`). +> +> The former is a visibility modifier for the Prover to interpret if a value should be made known to +> the Verifier, while the latter is a visibility modifier for the compiler to interpret if a +> function should be made accessible to external Noir programs like in other languages. + +### pub Modifier + +All data types in Noir are private by default. Types are explicitly declared as public using the +`pub` modifier: + +```rust +fn main(x : Field, y : pub Field) -> pub Field { + x + y +} +``` + +In this example, `x` is **private** while `y` and `x + y` (the return value) are **public**. Note +that visibility is handled **per variable**, so it is perfectly valid to have one input that is +private and another that is public. + +> **Note:** Public types can only be declared through parameters on `main`. + +## Type Aliases + +A type alias is a new name for an existing type. Type aliases are declared with the keyword `type`: + +```rust +type Id = u8; + +fn main() { + let id: Id = 1; + let zero: u8 = 0; + assert(zero + 1 == id); +} +``` + +Type aliases can also be used with [generics](./06_generics.md): + +```rust +type Id = Size; + +fn main() { + let id: Id = 1; + let zero: u32 = 0; + assert(zero + 1 == id); +} +``` + +### BigInt + +You can acheive BigInt functionality using the [Noir BigInt](https://github.com/shuklaayush/noir-bigint) library. diff --git a/docs/versioned_docs/version-0.17.0/language_concepts/data_types/00_fields.md b/docs/versioned_docs/version-0.17.0/language_concepts/data_types/00_fields.md new file mode 100644 index 00000000000..658a0441ffb --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/language_concepts/data_types/00_fields.md @@ -0,0 +1,165 @@ +--- +title: Fields +description: + Dive deep into the Field data type in Noir. Understand its methods, practical examples, and best practices to effectively use Fields in your Noir programs. +keywords: + [ + noir, + field type, + methods, + examples, + best practices, + ] +--- + +The field type corresponds to the native field type of the proving backend. + +The size of a Noir field depends on the elliptic curve's finite field for the proving backend +adopted. For example, a field would be a 254-bit integer when paired with the default backend that +spans the Grumpkin curve. + +Fields support integer arithmetic and are often used as the default numeric type in Noir: + +```rust +fn main(x : Field, y : Field) { + let z = x + y; +} +``` + +`x`, `y` and `z` are all private fields in this example. Using the `let` keyword we defined a new +private value `z` constrained to be equal to `x + y`. + +If proving efficiency is of priority, fields should be used as a default for solving problems. +Smaller integer types (e.g. `u64`) incur extra range constraints. + +## Methods + +After declaring a Field, you can use these common methods on it: + +### to_le_bits + +Transforms the field into an array of bits, Little Endian. + +```rust +fn to_le_bits(_x : Field, _bit_size: u32) -> [u1; N] +``` + +example: + +```rust +fn main() { + let field = 2; + let bits = field.to_le_bits(32); +} +``` + +### to_be_bits + +Transforms the field into an array of bits, Big Endian. + +```rust +fn to_be_bits(_x : Field, _bit_size: u32) -> [u1; N] +``` + +example: + +```rust +fn main() { + let field = 2; + let bits = field.to_be_bits(32); +} +``` + +### to_le_bytes + +Transforms into an array of bytes, Little Endian + +```rust +fn to_le_bytes(_x : Field, byte_size: u32) -> [u8] +``` + +example: + +```rust +fn main() { + let field = 2; + let bytes = field.to_le_bytes(4); +} +``` + +### to_be_bytes + +Transforms into an array of bytes, Big Endian + +```rust +fn to_be_bytes(_x : Field, byte_size: u32) -> [u8] +``` + +example: + +```rust +fn main() { + let field = 2; + let bytes = field.to_be_bytes(4); +} +``` + +### to_le_radix + +Decomposes into a vector over the specified base, Little Endian + +```rust +fn to_le_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] +``` + +example: + +```rust +fn main() { + let field = 2; + let radix = field.to_le_radix(256, 4); +} +``` + +### to_be_radix + +Decomposes into a vector over the specified base, Big Endian + +```rust +fn to_be_radix(_x : Field, _radix: u32, _result_len: u32) -> [u8] +``` + +example: + +```rust +fn main() { + let field = 2; + let radix = field.to_be_radix(256, 4); +} +``` + +### pow_32 + +Returns the value to the power of the specified exponent + +```rust +fn pow_32(self, exponent: Field) -> Field +``` + +example: + +```rust +fn main() { + let field = 2 + let pow = field.pow_32(4); + assert(pow == 16); +} +``` + +### sgn0 + +Parity of (prime) Field element, i.e. sgn0(x mod p) = 0 if x ∈ {0, ..., p-1} is even, otherwise sgn0(x mod p) = 1. + +```rust +fn sgn0(self) -> u1 +``` diff --git a/docs/versioned_docs/version-0.17.0/language_concepts/data_types/01_integers.md b/docs/versioned_docs/version-0.17.0/language_concepts/data_types/01_integers.md new file mode 100644 index 00000000000..d9c5e20e795 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/language_concepts/data_types/01_integers.md @@ -0,0 +1,33 @@ +--- +title: Integers +description: + Explore the Integer data type in Noir. Learn about its methods, see real-world examples, and grasp how to efficiently use Integers in your Noir code. +keywords: + [ + noir, + integer types, + methods, + examples, + arithmetic, + ] +--- + +An integer type is a range constrained field type. The Noir frontend currently supports unsigned, +arbitrary-sized integer types. + +An integer type is specified first with the letter `u`, indicating its unsigned nature, followed by +its length in bits (e.g. `32`). For example, a `u32` variable can store a value in the range of +$\\([0,2^{32}-1]\\)$: + +```rust +fn main(x : Field, y : u32) { + let z = x as u32 + y; +} +``` + +`x`, `y` and `z` are all private values in this example. However, `x` is a field while `y` and `z` +are unsigned 32-bit integers. If `y` or `z` exceeds the range $\\([0,2^{32}-1]\\)$, proofs created +will be rejected by the verifier. + +> **Note:** The default backend supports both even (e.g. `u16`, `u48`) and odd (e.g. `u5`, `u3`) +> sized integer types. diff --git a/docs/versioned_docs/version-0.17.0/language_concepts/data_types/02_booleans.md b/docs/versioned_docs/version-0.17.0/language_concepts/data_types/02_booleans.md new file mode 100644 index 00000000000..885db167d83 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/language_concepts/data_types/02_booleans.md @@ -0,0 +1,30 @@ +--- +title: Booleans +description: + Delve into the Boolean data type in Noir. Understand its methods, practical examples, and best practices for using Booleans in your Noir programs. +keywords: + [ + noir, + boolean type, + methods, + examples, + logical operations, + ] +--- + + +The `bool` type in Noir has two possible values: `true` and `false`: + +```rust +fn main() { + let t = true; + let f: bool = false; +} +``` + +> **Note:** When returning a boolean value, it will show up as a value of 1 for `true` and 0 for +> `false` in _Verifier.toml_. + +The boolean type is most commonly used in conditionals like `if` expressions and `assert` +statements. More about conditionals is covered in the [Control Flow](../control_flow) and +[Assert Function](../assert) sections. diff --git a/docs/versioned_docs/version-0.17.0/language_concepts/data_types/03_strings.md b/docs/versioned_docs/version-0.17.0/language_concepts/data_types/03_strings.md new file mode 100644 index 00000000000..c42f34ec3ad --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/language_concepts/data_types/03_strings.md @@ -0,0 +1,63 @@ +--- +title: Strings +description: + Discover the String data type in Noir. Learn about its methods, see real-world examples, and understand how to effectively manipulate and use Strings in Noir. +keywords: + [ + noir, + string type, + methods, + examples, + concatenation, + ] +--- + + +The string type is a fixed length value defined with `str`. + +You can use strings in `assert()` functions or print them with +`std::println()`. See more about [Logging](../../standard_library/logging). + +```rust +use dep::std; + +fn main(message : pub str<11>, hex_as_string : str<4>) { + std::println(message); + assert(message == "hello world"); + assert(hex_as_string == "0x41"); +} +``` + +You can convert a `str` to a byte array by calling `as_bytes()` +or a vector by calling `as_bytes_vec()`. + +```rust +fn main() { + let message = "hello world"; + let message_bytes = message.as_bytes(); + let mut message_vec = message.as_bytes_vec(); + assert(message_bytes.len() == 11); + assert(message_bytes[0] == 104); + assert(message_bytes[0] == message_vec.get(0)); +} +``` + +## Escape characters + +You can use escape characters for your strings: + +| Escape Sequence | Description | +|-----------------|-----------------| +| `\r` | Carriage Return | +| `\n` | Newline | +| `\t` | Tab | +| `\0` | Null Character | +| `\"` | Double Quote | +| `\\` | Backslash | + +Example: + +```rust +let s = "Hello \"world" // prints "Hello "world" +let s = "hey \tyou"; // prints "hey you" +``` diff --git a/docs/versioned_docs/version-0.17.0/language_concepts/data_types/04_arrays.md b/docs/versioned_docs/version-0.17.0/language_concepts/data_types/04_arrays.md new file mode 100644 index 00000000000..bdbd1798bef --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/language_concepts/data_types/04_arrays.md @@ -0,0 +1,244 @@ +--- +title: Arrays +description: + Dive into the Array data type in Noir. Grasp its methods, practical examples, and best practices for efficiently using Arrays in your Noir code. +keywords: + [ + noir, + array type, + methods, + examples, + indexing, + ] +--- + +An array is one way of grouping together values into one compound type. Array types can be inferred +or explicitly specified via the syntax `[; ]`: + +```rust +fn main(x : Field, y : Field) { + let my_arr = [x, y]; + let your_arr: [Field; 2] = [x, y]; +} +``` + +Here, both `my_arr` and `your_arr` are instantiated as an array containing two `Field` elements. + +Array elements can be accessed using indexing: + +```rust +fn main() { + let a = [1, 2, 3, 4, 5]; + + let first = a[0]; + let second = a[1]; +} +``` + +All elements in an array must be of the same type (i.e. homogeneous). That is, an array cannot group +a `Field` value and a `u8` value together for example. + +You can write mutable arrays, like: + +```rust +fn main() { + let mut arr = [1, 2, 3, 4, 5]; + assert(arr[0] == 1); + + arr[0] = 42; + assert(arr[0] == 42); +} +``` + +You can instantiate a new array of a fixed size with the same value repeated for each element. The following example instantiates an array of length 32 where each element is of type Field and has the value 0. + +```rust +let array: [Field; 32] = [0; 32]; +``` + +Like in Rust, arrays in Noir are a fixed size. However, if you wish to convert an array to a [slice](./slices), you can just call `as_slice` on your array: + +```rust +let array: [Field; 32] = [0; 32]; +let sl = array.as_slice() +``` + +You can define multidimensional arrays: + +```rust +let array : [[Field; 2]; 2]; +let element = array[0][0]; +``` + +## Types + +You can create arrays of primitive types or structs. There is not yet support for nested arrays +(arrays of arrays) or arrays of structs that contain arrays. + +## Methods + +For convenience, the STD provides some ready-to-use, common methods for arrays: + +### len + +Returns the length of an array + +```rust +fn len(_array: [T; N]) -> comptime Field +``` + +example + +```rust +fn main() { + let array = [42, 42]; + assert(array.len() == 2); +} +``` + +### sort + +Returns a new sorted array. The original array remains untouched. Notice that this function will +only work for arrays of fields or integers, not for any arbitrary type. This is because the sorting +logic it uses internally is optimized specifically for these values. If you need a sort function to +sort any type, you should use the function `sort_via` described below. + +```rust +fn sort(_array: [T; N]) -> [T; N] +``` + +example + +```rust +fn main() { + let arr = [42, 32]; + let sorted = arr.sort(); + assert(sorted == [32, 42]); +} +``` + +### sort_via + +Sorts the array with a custom comparison function + +```rust +fn sort_via(mut a: [T; N], ordering: fn(T, T) -> bool) -> [T; N] +``` + +example + +```rust +fn main() { + let arr = [42, 32] + let sorted_ascending = arr.sort_via(|a, b| a < b); + assert(sorted_ascending == [32, 42]); // verifies + + let sorted_descending = arr.sort_via(|a, b| a > b); + assert(sorted_descending == [32, 42]); // does not verify +} +``` + +### map + +Applies a function to each element of the array, returning a new array containing the mapped elements. + +```rust +fn map(f: fn(T) -> U) -> [U; N] +``` + +example + +```rust +let a = [1, 2, 3]; +let b = a.map(|a| a * 2); // b is now [2, 4, 6] +``` + +### fold + +Applies a function to each element of the array, returning the final accumulated value. The first +parameter is the initial value. + +```rust +fn fold(mut accumulator: U, f: fn(U, T) -> U) -> U +``` + +This is a left fold, so the given function will be applied to the accumulator and first element of +the array, then the second, and so on. For a given call the expected result would be equivalent to: + +```rust +let a1 = [1]; +let a2 = [1, 2]; +let a3 = [1, 2, 3]; + +let f = |a, b| a - b; +a1.fold(10, f) //=> f(10, 1) +a2.fold(10, f) //=> f(f(10, 1), 2) +a3.fold(10, f) //=> f(f(f(10, 1), 2), 3) +``` + +example: + +```rust + +fn main() { + let arr = [2, 2, 2, 2, 2]; + let folded = arr.fold(0, |a, b| a + b); + assert(folded == 10); +} + +``` + +### reduce + +Same as fold, but uses the first element as starting element. + +```rust +fn reduce(f: fn(T, T) -> T) -> T +``` + +example: + +```rust +fn main() { + let arr = [2, 2, 2, 2, 2]; + let reduced = arr.reduce(|a, b| a + b); + assert(reduced == 10); +} +``` + +### all + +Returns true if all the elements satisfy the given predicate + +```rust +fn all(predicate: fn(T) -> bool) -> bool +``` + +example: + +```rust +fn main() { + let arr = [2, 2, 2, 2, 2]; + let all = arr.all(|a| a == 2); + assert(all); +} +``` + +### any + +Returns true if any of the elements satisfy the given predicate + +```rust +fn any(predicate: fn(T) -> bool) -> bool +``` + +example: + +```rust +fn main() { + let arr = [2, 2, 2, 2, 5]; + let any = arr.any(|a| a == 5); + assert(any); +} + +``` diff --git a/docs/versioned_docs/version-0.17.0/language_concepts/data_types/05_slices.mdx b/docs/versioned_docs/version-0.17.0/language_concepts/data_types/05_slices.mdx new file mode 100644 index 00000000000..f45f56daee1 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/language_concepts/data_types/05_slices.mdx @@ -0,0 +1,146 @@ +--- +title: Slices +description: Explore the Slice data type in Noir. Understand its methods, see real-world examples, and learn how to effectively use Slices in your Noir programs. +keywords: [noir, slice type, methods, examples, subarrays] +--- + +import Experimental from '@site/src/components/Notes/_experimental.mdx'; + + + +A slice is a dynamically-sized view into a sequence of elements. They can be resized at runtime, but because they don't own the data, they cannot be returned from a circuit. You can treat slices as arrays without a constrained size. + +```rust +use dep::std::slice; + +fn main() -> pub Field { + let mut slice: [Field] = [0; 2]; + + let mut new_slice = slice.push_back(6); + new_slice.len() +} +``` + +View the corresponding test file [here]([test-file]. + +[test-file]: https://github.com/noir-lang/noir/blob/f387ec1475129732f72ba294877efdf6857135ac/crates/nargo_cli/tests/test_data_ssa_refactor/slices/src/main.nr + +## Methods + +For convenience, the STD provides some ready-to-use, common methods for slices: + +### push_back + +Pushes a new element to the end of the slice, returning a new slice with a length one greater than the original unmodified slice. + +```rust +fn push_back(_self: [T], _elem: T) -> [T] +``` + +example: + +```rust +fn main() -> pub Field { + let mut slice: [Field] = [0; 2]; + + let mut new_slice = slice.push_back(6); + new_slice.len() +} +``` + +View the corresponding test file [here][test-file]. + +### push_front + +Returns a new array with the specified element inserted at index 0. The existing elements indexes are incremented by 1. + +```rust +fn push_front(_self: Self, _elem: T) -> Self +``` + +Example: + +```rust +let mut new_slice: [Field] = []; +new_slice = new_slice.push_front(20); +assert(new_slice[0] == 20); // returns true +``` + +View the corresponding test file [here][test-file]. + +### pop_front + +Returns a tuple of two items, the first element of the array and the rest of the array. + +```rust +fn pop_front(_self: Self) -> (T, Self) +``` + +Example: + +```rust +let (first_elem, rest_of_slice) = slice.pop_front(); +``` + +View the corresponding test file [here][test-file]. + +### pop_back + +Returns a tuple of two items, the beginning of the array with the last element omitted and the last element. + +```rust +fn pop_back(_self: Self) -> (Self, T) +``` + +Example: + +```rust +let (popped_slice, last_elem) = slice.pop_back(); +``` + +View the corresponding test file [here][test-file]. + +### append + +Loops over a slice and adds it to the end of another. + +```rust +fn append(mut self, other: Self) -> Self +``` + +Example: + +```rust +let append = [1, 2].append([3, 4, 5]); +``` + +### insert + +Inserts an element at a specified index and shifts all following elements by 1. + +```rust +fn insert(_self: Self, _index: Field, _elem: T) -> Self +``` + +Example: + +```rust +new_slice = rest_of_slice.insert(2, 100); +assert(new_slice[2] == 100); +``` + +View the corresponding test file [here][test-file]. + +### remove + +Remove an element at a specified index, shifting all elements after it to the left, returning the altered slice and the removed element. + +```rust +fn remove(_self: Self, _index: Field) -> (Self, T) +``` + +Example: + +```rust +let (remove_slice, removed_elem) = slice.remove(3); +``` diff --git a/docs/versioned_docs/version-0.17.0/language_concepts/data_types/06_vectors.mdx b/docs/versioned_docs/version-0.17.0/language_concepts/data_types/06_vectors.mdx new file mode 100644 index 00000000000..4617e90d038 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/language_concepts/data_types/06_vectors.mdx @@ -0,0 +1,172 @@ +--- +title: Vectors +description: Delve into the Vector data type in Noir. Learn about its methods, practical examples, and best practices for using Vectors in your Noir code. +keywords: [noir, vector type, methods, examples, dynamic arrays] +--- + +import Experimental from '@site/src/components/Notes/_experimental.mdx'; + + + +A vector is a collection type similar to Rust's Vector type. It's convenient way to use slices as mutable arrays. + +Example: + +```rust +use dep::std::collections::vec::Vec; + +let mut vector: Vec = Vec::new(); +for i in 0..5 { + vector.push(i); +} +assert(vector.len() == 5); +``` + +## Methods + +### new + +Creates a new, empty vector. + +```rust +pub fn new() -> Self { + Self { slice: [] } +} +``` + +Example: + +```rust +let empty_vector: Vec = Vec::new(); +assert(empty_vector.len() == 0); +``` + +### from_slice + +Creates a vector containing each element from a given slice. Mutations to the resulting vector will not affect the original slice. + +```rust +pub fn from_slice(slice: [T]) -> Self { + Self { slice } +} +``` + +Example: + +```rust +let arr: [Field] = [1, 2, 3]; +let vector_from_slice = Vec::from_slice(arr); +assert(vector_from_slice.len() == 3); +``` + +### get + +Retrieves an element from the vector at a given index. Panics if the index points beyond the vector's end. + +```rust +pub fn get(self, index: Field) -> T { + self.slice[index] +} +``` + +Example: + +```rust +let vector: Vec = Vec::from_slice([10, 20, 30]); +assert(vector.get(1) == 20); +``` + +### push + +Adds a new element to the vector's end, returning a new vector with a length one greater than the original unmodified vector. + +```rust +pub fn push(&mut self, elem: T) { + self.slice = self.slice.push_back(elem); +} +``` + +Example: + +```rust +let mut vector: Vec = Vec::new(); +vector.push(10); +assert(vector.len() == 1); +``` + +### pop + +Removes an element from the vector's end, returning a new vector with a length one less than the original vector, along with the removed element. Panics if the vector's length is zero. + +```rust +pub fn pop(&mut self) -> T { + let (popped_slice, last_elem) = self.slice.pop_back(); + self.slice = popped_slice; + last_elem +} +``` + +Example: + +```rust +let mut vector = Vec::from_slice([10, 20]); +let popped_elem = vector.pop(); +assert(popped_elem == 20); +assert(vector.len() == 1); +``` + +### insert + +Inserts an element at a specified index, shifting subsequent elements to the right. + +```rust +pub fn insert(&mut self, index: Field, elem: T) { + self.slice = self.slice.insert(index, elem); +} +``` + +Example: + +```rust +let mut vector = Vec::from_slice([10, 30]); +vector.insert(1, 20); +assert(vector.get(1) == 20); +``` + +### remove + +Removes an element at a specified index, shifting subsequent elements to the left, and returns the removed element. + +```rust +pub fn remove(&mut self, index: Field) -> T { + let (new_slice, elem) = self.slice.remove(index); + self.slice = new_slice; + elem +} +``` + +Example: + +```rust +let mut vector = Vec::from_slice([10, 20, 30]); +let removed_elem = vector.remove(1); +assert(removed_elem == 20); +assert(vector.len() == 2); +``` + +### len + +Returns the number of elements in the vector. + +```rust +pub fn len(self) -> Field { + self.slice.len() +} +``` + +Example: + +```rust +let empty_vector: Vec = Vec::new(); +assert(empty_vector.len() == 0); +``` diff --git a/docs/versioned_docs/version-0.17.0/language_concepts/data_types/07_tuples.md b/docs/versioned_docs/version-0.17.0/language_concepts/data_types/07_tuples.md new file mode 100644 index 00000000000..5f6cab974a8 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/language_concepts/data_types/07_tuples.md @@ -0,0 +1,47 @@ +--- +title: Tuples +description: + Dive into the Tuple data type in Noir. Understand its methods, practical examples, and best practices for efficiently using Tuples in your Noir code. +keywords: + [ + noir, + tuple type, + methods, + examples, + multi-value containers, + ] +--- + +A tuple collects multiple values like an array, but with the added ability to collect values of +different types: + +```rust +fn main() { + let tup: (u8, u64, Field) = (255, 500, 1000); +} +``` + +One way to access tuple elements is via destructuring using pattern matching: + +```rust +fn main() { + let tup = (1, 2); + + let (one, two) = tup; + + let three = one + two; +} +``` + +Another way to access tuple elements is via direct member access, using a period (`.`) followed by +the index of the element we want to access. Index `0` corresponds to the first tuple element, `1` to +the second and so on: + +```rust +fn main() { + let tup = (5, 6, 7, 8); + + let five = tup.0; + let eight = tup.3; +} +``` diff --git a/docs/versioned_docs/version-0.17.0/language_concepts/data_types/08_structs.md b/docs/versioned_docs/version-0.17.0/language_concepts/data_types/08_structs.md new file mode 100644 index 00000000000..85649dfb389 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/language_concepts/data_types/08_structs.md @@ -0,0 +1,73 @@ +--- +title: Structs +description: + Explore the Struct data type in Noir. Learn about its methods, see real-world examples, and grasp how to effectively define and use Structs in your Noir programs. +keywords: + [ + noir, + struct type, + methods, + examples, + data structures, + ] +--- + +A struct also allows for grouping multiple values of different types. Unlike tuples, we can also +name each field. + +> **Note:** The usage of _field_ here refers to each element of the struct and is unrelated to the +> field type of Noir. + +Defining a struct requires giving it a name and listing each field within as `: ` pairs: + +```rust +struct Animal { + hands: Field, + legs: Field, + eyes: u8, +} +``` + +An instance of a struct can then be created with actual values in `: ` pairs in any +order. Struct fields are accessible using their given names: + +```rust +fn main() { + let legs = 4; + + let dog = Animal { + eyes: 2, + hands: 0, + legs, + }; + + let zero = dog.hands; +} +``` + +Structs can also be destructured in a pattern, binding each field to a new variable: + +```rust +fn main() { + let Animal { hands, legs: feet, eyes } = get_octopus(); + + let ten = hands + feet + eyes as u8; +} + +fn get_octopus() -> Animal { + let octopus = Animal { + hands: 0, + legs: 8, + eyes: 2, + }; + + octopus +} +``` + +The new variables can be bound with names different from the original struct field names, as +showcased in the `legs --> feet` binding in the example above. + +:::note +You can use Structs as inputs to the `main` function, but you can't output them +::: diff --git a/docs/versioned_docs/version-0.17.0/language_concepts/data_types/09_references.md b/docs/versioned_docs/version-0.17.0/language_concepts/data_types/09_references.md new file mode 100644 index 00000000000..b0c35ce2cb9 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/language_concepts/data_types/09_references.md @@ -0,0 +1,22 @@ +--- +title: References +--- + +Noir supports first-class references. References are a bit like pointers: they point to a specific address that can be followed to access the data stored at that address. You can use Rust-like syntax to use pointers in Noir: the `&` operator references the variable, the `*` operator dereferences it. + +Example: + +```rust +fn main() { + let mut x = 2; + + // you can reference x as &mut and pass it to multiplyBy2 + multiplyBy2(&mut x); +} + +// you can access &mut here +fn multiplyBy2(x: &mut Field) { + // and dereference it with * + *x = *x * 2; +} +``` diff --git a/docs/versioned_docs/version-0.17.0/language_concepts/data_types/10_function_types.md b/docs/versioned_docs/version-0.17.0/language_concepts/data_types/10_function_types.md new file mode 100644 index 00000000000..1ec92efd594 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/language_concepts/data_types/10_function_types.md @@ -0,0 +1,25 @@ +--- +title: Function types +--- + +Noir supports higher-order functions. The syntax for a function type is as follows: + +```rust +fn(arg1_type, arg2_type, ...) -> return_type +``` + +Example: + +```rust +fn assert_returns_100(f: fn() -> Field) { // f takes no args and returns a Field + assert(f() == 100); +} + +fn main() { + assert_returns_100(|| 100); // ok + assert_returns_100(|| 150); // fails +} +``` + +A function type also has an optional capture environment - this is necessary to support closures. +See [Lambdas](../08_lambdas.md) for more details. diff --git a/docs/versioned_docs/version-0.17.0/migration_notes.md b/docs/versioned_docs/version-0.17.0/migration_notes.md new file mode 100644 index 00000000000..48a8abcf22e --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/migration_notes.md @@ -0,0 +1,83 @@ +--- +title: Migration notes +description: Read about migration notes from previous versions, which could solve problems while updating +keywords: [Noir, notes, migration, updating, upgrading] +--- + +Noir is in full-speed development. Things break fast, wild, and often. This page attempts to leave some notes on errors you might encounter when upgrading and how to resolve them until proper patches are built. + +## ≥0.14 + +The index of the [for loops](./language_concepts/02_control_flow.md#loops) is now of type `u64` instead of `Field`. An example refactor would be: + +```rust +for i in 0..10 { + let i = i as Field; +} +``` + +## ≥v0.11.0 and Nargo backend + +From this version onwards, Nargo starts managing backends through the `nargo backend` command. Upgrading to the versions per usual steps might lead to: + +### `backend encountered an error` + +This is likely due to the existing locally installed version of proving backend (e.g. barretenberg) is incompatible with the version of Nargo in use. + +To fix the issue: + +1. Uninstall the existing backend + +```bash +nargo backend uninstall acvm-backend-barretenberg +``` + +You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. + +2. Reinstall a compatible version of the proving backend. + +If you are using the default barretenberg backend, simply run: + +``` +nargo prove +``` + +with you Noir program. + +This will trigger the download and installation of the latest version of barretenberg compatible with your Nargo in use. + +### `backend encountered an error: illegal instruction` + +On certain Intel-based systems, an `illegal instruction` error may arise due to incompatibility of barretenberg with certain CPU instructions. + +To fix the issue: + +1. Uninstall the existing backend + +```bash +nargo backend uninstall acvm-backend-barretenberg +``` + +You may replace _acvm-backend-barretenberg_ with the name of your backend listed in `nargo backend ls` or in ~/.nargo/backends. + +2. Reinstall a compatible version of the proving backend. + +If you are using the default barretenberg backend, simply run: + +``` +nargo backend install acvm-backend-barretenberg https://github.com/noir-lang/barretenberg-js-binary/raw/master/run-bb.tar.gz +``` + +This downloads and installs a specific bb.js based version of barretenberg binary from GitHub. + +The gzipped filed is running this bash script: , where we need to gzip it as the Nargo currently expect the backend to be zipped up. + +Then run: + +``` +DESIRED_BINARY_VERSION=0.8.1 nargo info +``` + +This overrides the bb native binary with a bb.js node application instead, which should be compatible with most if not all hardware. This does come with the drawback of being generally slower than native binary. + +0.8.1 indicates bb.js version 0.8.1, so if you change that it will update to a different version or the default version in the script if none was supplied. diff --git a/docs/versioned_docs/version-0.17.0/modules_packages_crates/crates_and_packages.md b/docs/versioned_docs/version-0.17.0/modules_packages_crates/crates_and_packages.md new file mode 100644 index 00000000000..fb83a33d94e --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/modules_packages_crates/crates_and_packages.md @@ -0,0 +1,42 @@ +--- +title: Crates and Packages +description: Learn how to use Crates and Packages in your Noir project +keywords: [Nargo, dependencies, package management, crates, package] +--- + +## Crates + +A crate is the smallest amount of code that the Noir compiler considers at a time. +Crates can contain modules, and the modules may be defined in other files that get compiled with the crate, as we’ll see in the coming sections. + +### Crate Types + +A Noir crate can come in several forms: binaries, libraries or contracts. + +#### Binaries + +_Binary crates_ are programs which you can compile to an ACIR circuit which you can then create proofs against. Each must have a function called `main` that defines the ACIR circuit which is to be proved. + +#### Libraries + +_Library crates_ don't have a `main` function and they don't compile down to ACIR. Instead they define functionality intended to be shared with multiple projects, and eventually included in a binary crate. + +#### Contracts + +Contract crates are similar to binary crates in that they compile to ACIR which you can create proofs against. They are different in that they do not have a single `main` function, but are a collection of functions to be deployed to the [Aztec network](https://aztec.network). You can learn more about the technical details of Aztec in the [monorepo](https://github.com/AztecProtocol/aztec-packages) or contract [examples](https://github.com/AztecProtocol/aztec-packages/tree/master/yarn-project/noir-contracts/src/contracts). + +### Crate Root + +Every crate has a root, which is the source file that the compiler starts, this is also known as the root module. The Noir compiler does not enforce any conditions on the name of the file which is the crate root, however if you are compiling via Nargo the crate root must be called `lib.nr` or `main.nr` for library or binary crates respectively. + +## Packages + +A Nargo _package_ is a collection of one of more crates that provides a set of functionality. A package must include a Nargo.toml file. + +A package _must_ contain either a library or a binary crate, but not both. + +### Differences from Cargo Packages + +One notable difference between Rust's Cargo and Noir's Nargo is that while Cargo allows a package to contain an unlimited number of binary crates and a single library crate, Nargo currently only allows a package to contain a single crate. + +In future this restriction may be lifted to allow a Nargo package to contain both a binary and library crate or multiple binary crates. diff --git a/docs/versioned_docs/version-0.17.0/modules_packages_crates/dependencies.md b/docs/versioned_docs/version-0.17.0/modules_packages_crates/dependencies.md new file mode 100644 index 00000000000..75f95aaa305 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/modules_packages_crates/dependencies.md @@ -0,0 +1,123 @@ +--- +title: Dependencies +description: + Learn how to specify and manage dependencies in Nargo, allowing you to upload packages to GitHub + and use them easily in your project. +keywords: [Nargo, dependencies, GitHub, package management, versioning] +--- + +Nargo allows you to upload packages to GitHub and use them as dependencies. + +## Specifying a dependency + +Specifying a dependency requires a tag to a specific commit and the git url to the url containing +the package. + +Currently, there are no requirements on the tag contents. If requirements are added, it would follow +semver 2.0 guidelines. + +> Note: Without a `tag` , there would be no versioning and dependencies would change each time you +> compile your project. + +For example, to add the [ecrecover-noir library](https://github.com/colinnielsen/ecrecover-noir) to your project, add it to `Nargo.toml`: + +```toml +# Nargo.toml + +[dependencies] +ecrecover = {tag = "v0.8.0", git = "https://github.com/colinnielsen/ecrecover-noir"} +``` + +If the module is in a subdirectory, you can define a subdirectory in your git repository, for example: + +```toml +# Nargo.toml + +[dependencies] +easy_private_token_contract = {tag ="v0.1.0-alpha62", git = "https://github.com/AztecProtocol/aztec-packages", directory = "yarn-project/noir-contracts/src/contracts/easy_private_token_contract"} +``` + +## Specifying a local dependency + +You can also specify dependencies that are local to your machine. + +For example, this file structure has a library and binary crate + +```tree +├── binary_crate +│   ├── Nargo.toml +│   └── src +│   └── main.nr +└── liba + ├── Nargo.toml + └── src + └── lib.nr +``` + +Inside of the binary crate, you can specify: + +```toml +# Nargo.toml + +[dependencies] +libA = { path = "../liba" } +``` + +## Importing dependencies + +You can import a dependency to a Noir file using the following syntax. For example, to import the +ecrecover-noir library and local liba referenced above: + +```rust +use dep::ecrecover; +use dep::libA; +``` + +You can also import only the specific parts of dependency that you want to use, like so: + +```rust +use dep::std::hash::sha256; +use dep::std::scalar_mul::fixed_base_embedded_curve; +``` + +Lastly, as demonstrated in the +[elliptic curve example](../standard_library/cryptographic_primitives/ec_primitives#examples), you +can import multiple items in the same line by enclosing them in curly braces: + +```rust +use dep::std::ec::tecurve::affine::{Curve, Point}; +``` + +We don't have a way to consume libraries from inside a [workspace](./workspaces) as external dependencies right now. + +Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. + +## Dependencies of Dependencies + +Note that when you import a dependency, you also get access to all of the dependencies of that package. + +For example, the [phy_vector](https://github.com/resurgencelabs/phy_vector) library imports an [fraction](https://github.com/resurgencelabs/fraction) library. If you're importing the phy_vector library, then you can access the functions in fractions library like so: + +```rust +use dep::phy_vector; + +fn main(x : Field, y : pub Field) { + //... + let f = phy_vector::fraction::toFraction(true, 2, 1); + //... +} +``` + +## Available Libraries + +Noir does not currently have an official package manager. You can find a list of available Noir libraries in the [awesome-noir repo here](https://github.com/noir-lang/awesome-noir#libraries). + +Some libraries that are available today include: + +- [Standard Library](https://github.com/noir-lang/noir/tree/master/noir_stdlib) - the Noir Standard Library +- [Ethereum Storage Proof Verification](https://github.com/aragonzkresearch/noir-trie-proofs) - a library that contains the primitives necessary for RLP decoding (in the form of look-up table construction) and Ethereum state and storage proof verification (or verification of any trie proof involving 32-byte long keys) +- [BigInt](https://github.com/shuklaayush/noir-bigint) - a library that provides a custom BigUint56 data type, allowing for computations on large unsigned integers +- [ECrecover](https://github.com/colinnielsen/ecrecover-noir/tree/main) - a library to verify an ECDSA signature and return the source Ethereum address +- [Sparse Merkle Tree Verifier](https://github.com/vocdoni/smtverifier-noir/tree/main) - a library for verification of sparse Merkle trees +- [Signed Int](https://github.com/resurgencelabs/signed_int) - a library for accessing a custom Signed Integer data type, allowing access to negative numbers on Noir +- [Fraction](https://github.com/resurgencelabs/fraction) - a library for accessing fractional number data type in Noir, allowing results that aren't whole numbers diff --git a/docs/versioned_docs/version-0.17.0/modules_packages_crates/modules.md b/docs/versioned_docs/version-0.17.0/modules_packages_crates/modules.md new file mode 100644 index 00000000000..147c9b284e8 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/modules_packages_crates/modules.md @@ -0,0 +1,104 @@ +--- +title: Modules +description: + Learn how to organize your files using modules in Noir, following the same convention as Rust's + module system. Examples included. +keywords: [Noir, Rust, modules, organizing files, sub-modules] +--- + +Noir's module system follows the same convention as the _newer_ version of Rust's module system. + +## Purpose of Modules + +Modules are used to organise files. Without modules all of your code would need to live in a single +file. In Noir, the compiler does not automatically scan all of your files to detect modules. This +must be done explicitly by the developer. + +## Examples + +### Importing a module in the crate root + +Filename : `src/main.nr` + +```rust +mod foo; + +fn main() { + foo::hello_world(); +} +``` + +Filename : `src/foo.nr` + +```rust +fn from_foo() {} +``` + +In the above snippet, the crate root is the `src/main.nr` file. The compiler sees the module +declaration `mod foo` which prompts it to look for a foo.nr file. + +Visually this module hierarchy looks like the following : + +``` +crate + ├── main + │ + └── foo + └── from_foo + +``` + +### Importing a module throughout the tree + +All modules are accessible from the `crate::` namespace. + +``` +crate + ├── bar + ├── foo + └── main + +``` + +In the above snippet, if `bar` would like to use functions in `foo`, it can do so by `use crate::foo::function_name`. + +### Sub-modules + +Filename : `src/main.nr` + +```rust +mod foo; + +fn main() { + foo::from_foo(); +} +``` + +Filename : `src/foo.nr` + +```rust +mod bar; +fn from_foo() {} +``` + +Filename : `src/foo/bar.nr` + +```rust +fn from_bar() {} +``` + +In the above snippet, we have added an extra module to the module tree; `bar`. `bar` is a submodule +of `foo` hence we declare bar in `foo.nr` with `mod bar`. Since `foo` is not the crate root, the +compiler looks for the file associated with the `bar` module in `src/foo/bar.nr` + +Visually the module hierarchy looks as follows: + +``` +crate + ├── main + │ + └── foo + ├── from_foo + └── bar + └── from_bar +``` diff --git a/docs/versioned_docs/version-0.17.0/modules_packages_crates/workspaces.md b/docs/versioned_docs/version-0.17.0/modules_packages_crates/workspaces.md new file mode 100644 index 00000000000..d9ac92667c9 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/modules_packages_crates/workspaces.md @@ -0,0 +1,39 @@ +--- +title: Workspaces +--- + +Workspaces are a feature of nargo that allow you to manage multiple related Noir packages in a single repository. A workspace is essentially a group of related projects that share common build output directories and configurations. + +Each Noir project (with it's own Nargo.toml file) can be thought of as a package. Each package is expected to contain exactly one "named circuit", being the "name" defined in Nargo.toml with the program logic defined in `./src/main.nr`. + +For a project with the following structure: + +```tree +├── crates +│   ├── a +│   │   ├── Nargo.toml +│   │   └── src +│   │   └── main.nr +│   └── b +│   ├── Nargo.toml +│   └── src +│   └── main.nr +├── Nargo.toml +└── Prover.toml +``` + +You can define a workspace in Nargo.toml like so: + +```toml +[workspace] +members = ["crates/a", "crates/b"] +default-member = "crates/a" +``` + +`members` indicates which packages are included in the workspace. As such, all member packages of a workspace will be processed when the `--workspace` flag is used with various commands or if a `default-member` is not specified. + +`default-member` indicates which package various commands process by default. + +Libraries can be defined in a workspace. Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. + +Inside a workspace, these are consumed as `{ path = "../to_lib" }` dependencies in Nargo.toml. diff --git a/docs/versioned_docs/version-0.17.0/nargo/01_commands.md b/docs/versioned_docs/version-0.17.0/nargo/01_commands.md new file mode 100644 index 00000000000..65e2bdb44e3 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/nargo/01_commands.md @@ -0,0 +1,250 @@ +--- +title: Commands +description: + Noir CLI Commands for Noir Prover and Verifier to create, execute, prove and verify programs, + generate Solidity verifier smart contract and compile into JSON file containing ACIR + representation and ABI of circuit. +keywords: + [ + Nargo, + Noir CLI, + Noir Prover, + Noir Verifier, + generate Solidity verifier, + compile JSON file, + ACIR representation, + ABI of circuit, + TypeScript, + ] +--- + +## General options + +| Option | Description | +| -------------------- | -------------------------------------------------- | +| `--show-ssa` | Emit debug information for the intermediate SSA IR | +| `--deny-warnings` | Quit execution when warnings are emitted | +| `--silence-warnings` | Suppress warnings | +| `-h, --help` | Print help | + +## `nargo help [subcommand]` + +Prints the list of available commands or specific information of a subcommand. + +_Arguments_ + +| Argument | Description | +| -------------- | -------------------------------------------- | +| `` | The subcommand whose help message to display | + +## `nargo backend` + +Installs and selects custom backends used to generate and verify proofs. + +### Commands + +| Command | Description | +| ----------- | --------------------------------------------------------- | +| `current` | Prints the name of the currently active backend | +| `ls` | Prints the list of currently installed backends | +| `use` | Select the backend to use | +| `install` | Install a new backend from a URL | +| `uninstall` | Uninstalls a backend | +| `help` | Print this message or the help of the given subcommand(s) | + +### Options + +| Option | Description | +| ------------ | ----------- | +| `-h, --help` | Print help | + +## `nargo check` + +Generate the `Prover.toml` and `Verifier.toml` files for specifying prover and verifier in/output +values of the Noir program respectively. + +### Options + +| Option | Description | +| --------------------- | ------------------------------------- | +| `--package ` | The name of the package to check | +| `--workspace` | Check all packages in the workspace | +| `--print-acir` | Display the ACIR for compiled circuit | +| `--deny-warnings` | Treat all warnings as errors | +| `--silence-warnings` | Suppress warnings | +| `-h, --help` | Print help | + +### `nargo codegen-verifier` + +Generate a Solidity verifier smart contract for the program. + +### Options + +| Option | Description | +| --------------------- | ------------------------------------- | +| `--package ` | The name of the package to codegen | +| `--workspace` | Codegen all packages in the workspace | +| `--print-acir` | Display the ACIR for compiled circuit | +| `--deny-warnings` | Treat all warnings as errors | +| `--silence-warnings` | Suppress warnings | +| `-h, --help` | Print help | + +## `nargo compile` + +Compile the program into a JSON build artifact file containing the ACIR representation and the ABI +of the circuit. This build artifact can then be used to generate and verify proofs. + +You can also use "build" as an alias for compile (e.g. `nargo build`). + +### Options + +| Option | Description | +| --------------------- | ------------------------------------------------------------ | +| `--include-keys` | Include Proving and Verification keys in the build artifacts | +| `--package ` | The name of the package to compile | +| `--workspace` | Compile all packages in the workspace | +| `--print-acir` | Display the ACIR for compiled circuit | +| `--deny-warnings` | Treat all warnings as errors | +| `--silence-warnings` | Suppress warnings | +| `-h, --help` | Print help | + +## `nargo new ` + +Creates a new Noir project in a new folder. + +**Arguments** + +| Argument | Description | +| -------- | -------------------------------- | +| `` | The path to save the new project | + +### Options + +| Option | Description | +| --------------- | ----------------------------------------------------- | +| `--name ` | Name of the package [default: package directory name] | +| `--lib` | Use a library template | +| `--bin` | Use a binary template [default] | +| `--contract` | Use a contract template | +| `-h, --help` | Print help | + +## `nargo init` + +Creates a new Noir project in the current directory. + +### Options + +| Option | Description | +| --------------- | ----------------------------------------------------- | +| `--name ` | Name of the package [default: current directory name] | +| `--lib` | Use a library template | +| `--bin` | Use a binary template [default] | +| `--contract` | Use a contract template | +| `-h, --help` | Print help | + +## `nargo execute [WITNESS_NAME]` + +Runs the Noir program and prints its return value. + +**Arguments** + +| Argument | Description | +| ---------------- | ----------------------------------------- | +| `[WITNESS_NAME]` | Write the execution witness to named file | + +### Options + +| Option | Description | +| --------------------------------- | ------------------------------------------------------------------------------------ | +| `-p, --prover-name ` | The name of the toml file which contains the inputs for the prover [default: Prover] | +| `--package ` | The name of the package to execute | +| `--workspace` | Execute all packages in the workspace | +| `--print-acir` | Display the ACIR for compiled circuit | +| `--deny-warnings` | Treat all warnings as errors | +| `--silence-warnings` | Suppress warnings | +| `-h, --help` | Print help | + +_Usage_ + +The inputs to the circuit are read from the `Prover.toml` file generated by `nargo check`, which +must be filled in. + +To save the witness to file, run the command with a value for the `WITNESS_NAME` argument. A +`.tr` file will then be saved in the `./target` folder. + +## `nargo prove` + +Creates a proof for the program. + +### Options + +| Option | Description | +| ------------------------------------- | ---------------------------------------------------------------------------------------- | +| `-p, --prover-name ` | The name of the toml file which contains the inputs for the prover [default: Prover] | +| `-v, --verifier-name ` | The name of the toml file which contains the inputs for the verifier [default: Verifier] | +| `--verify` | Verify proof after proving | +| `--package ` | The name of the package to prove | +| `--workspace` | Prove all packages in the workspace | +| `--print-acir` | Display the ACIR for compiled circuit | +| `--deny-warnings` | Treat all warnings as errors | +| `--silence-warnings` | Suppress warnings | +| `-h, --help` | Print help | + +## `nargo verify` + +Given a proof and a program, verify whether the proof is valid. + +### Options + +| Option | Description | +| ------------------------------------- | ---------------------------------------------------------------------------------------- | +| `-v, --verifier-name ` | The name of the toml file which contains the inputs for the verifier [default: Verifier] | +| `--package ` | The name of the package to verify | +| `--workspace` | Verify all packages in the workspace | +| `--print-acir` | Display the ACIR for compiled circuit | +| `--deny-warnings` | Treat all warnings as errors | +| `--silence-warnings` | Suppress warnings | +| `-h, --help` | Print help | + +## `nargo test [TEST_NAME]` + +Nargo will automatically compile and run any functions which have the decorator `#[test]` on them if +you run `nargo test`. To print `println` statements in tests, use the `--show-output` flag. + +Takes an optional `--exact` flag which allows you to select tests based on an exact name. + +See an example on the [testing page](./testing). + +### Options + +| Option | Description | +| --------------------- | -------------------------------------- | +| `--show-output` | Display output of `println` statements | +| `--exact` | Only run tests that match exactly | +| `--package ` | The name of the package to test | +| `--workspace` | Test all packages in the workspace | +| `--print-acir` | Display the ACIR for compiled circuit | +| `--deny-warnings` | Treat all warnings as errors | +| `--silence-warnings` | Suppress warnings | +| `-h, --help` | Print help | + +## `nargo info` + +Prints a table containing the information of the package. + +Currently the table provide + +1. The number of ACIR opcodes +2. The final number gates in the circuit used by a backend + +If the file contains a contract the table will provide the +above information about each function of the contract. + +## `nargo lsp` + +Start a long-running Language Server process that communicates over stdin/stdout. +Usually this command is not run by a user, but instead will be run by a Language Client, such as [vscode-noir](https://github.com/noir-lang/vscode-noir). + +## `nargo fmt` + +Automatically formats your Noir source code based on the default formatting settings. diff --git a/docs/versioned_docs/version-0.17.0/nargo/02_testing.md b/docs/versioned_docs/version-0.17.0/nargo/02_testing.md new file mode 100644 index 00000000000..da767274efd --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/nargo/02_testing.md @@ -0,0 +1,61 @@ +--- +title: Testing in Noir +description: Learn how to use Nargo to test your Noir program in a quick and easy way +keywords: [Nargo, testing, Noir, compile, test] +--- + +You can test your Noir programs using Noir circuits. + +Nargo will automatically compile and run any functions which have the decorator `#[test]` on them if +you run `nargo test`. + +For example if you have a program like: + +```rust +fn add(x: u64, y: u64) -> u64 { + x + y +} +#[test] +fn test_add() { + assert(add(2,2) == 4); + assert(add(0,1) == 1); + assert(add(1,0) == 1); +} +``` + +Running `nargo test` will test that the `test_add` function can be executed while satisfying the all +the contraints which allows you to test that add returns the expected values. Test functions can't +have any arguments currently. + +### Test fail + +You can write tests that are expected to fail by using the decorator `#[test(should_fail)]`. For example: + +```rust +fn add(x: u64, y: u64) -> u64 { + x + y +} +#[test(should_fail)] +fn test_add() { + assert(add(2,2) == 5); +} +``` + +You can be more specific and make it fail with a specific reason by using `should_fail_with = "`: + +```rust +fn main(african_swallow_avg_speed : Field) { + assert(african_swallow_avg_speed == 65, "What is the airspeed velocity of an unladen swallow"); +} + +#[test] +fn test_king_arthur() { + main(65); +} + +#[test(should_fail_with = "What is the airspeed velocity of an unladen swallow")] +fn test_bridgekeeper() { + main(32); +} + +``` diff --git a/docs/versioned_docs/version-0.17.0/nargo/03_solidity_verifier.md b/docs/versioned_docs/version-0.17.0/nargo/03_solidity_verifier.md new file mode 100644 index 00000000000..9ac60cb0ba7 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/nargo/03_solidity_verifier.md @@ -0,0 +1,129 @@ +--- +title: Solidity Verifier +description: + Learn how to run the verifier as a smart contract on the blockchain. Compile a Solidity verifier + contract for your Noir program and deploy it on any EVM blockchain acting as a verifier smart + contract. Read more to find out! +keywords: + [ + solidity verifier, + smart contract, + blockchain, + compiler, + plonk_vk.sol, + EVM blockchain, + verifying Noir programs, + proving backend, + Barretenberg, + ] +--- + +For certain applications, it may be desirable to run the verifier as a smart contract instead of on +a local machine. + +Compile a Solidity verifier contract for your Noir program by running: + +```sh +nargo codegen-verifier +``` + +A new `contract` folder would then be generated in your project directory, containing the Solidity +file `plonk_vk.sol`. It can be deployed on any EVM blockchain acting as a verifier smart contract. + +> **Note:** It is possible to compile verifier contracts of Noir programs for other smart contract +> platforms as long as the proving backend supplies an implementation. +> +> Barretenberg, the default proving backend for Nargo, supports compilation of verifier contracts in +> Solidity only for the time being. + +## Verify + +To verify a proof using the Solidity verifier contract, call the `verify` function with the +following signature: + +```solidity +function verify(bytes calldata _proof, bytes32[] calldata _publicInputs) external view returns (bool) +``` + +You can see an example of how the `verify` function is called in the example zk voting application [here](https://github.com/noir-lang/noir-examples/blob/33e598c257e2402ea3a6b68dd4c5ad492bce1b0a/foundry-voting/src/zkVote.sol#L35): + +```solidity +function castVote(bytes calldata proof, uint proposalId, uint vote, bytes32 nullifierHash) public returns (bool) { + // ... + bytes32[] memory publicInputs = new bytes32[](4); + publicInputs[0] = merkleRoot; + publicInputs[1] = bytes32(proposalId); + publicInputs[2] = bytes32(vote); + publicInputs[3] = nullifierHash; + require(verifier.verify(proof, publicInputs), "Invalid proof"); +``` + +### Public Inputs + +:::tip + +A circuit doesn't have the concept of a return value. Return values are just syntactic sugar in +Noir. + +Under the hood, the return value is passed as an input to the circuit and is checked at the end of +the circuit program. + +::: + +The verifier contract uses the output (return) value of a Noir program as a public input. So if you +have the following function + +```rust +fn main( + // Public inputs + pubkey_x: pub Field, + pubkey_y: pub Field, + // Private inputs + priv_key: Field, +) -> pub Field +``` + +then `verify` in `plonk_vk.sol` will expect 3 public inputs. Passing two inputs will result in an +error like `Reason: PUBLIC_INPUT_COUNT_INVALID(3, 2)`. + +In this case the 3 inputs to `verify` would be ordered as `[pubkey_x, pubkey_y, return]`. + +#### Struct inputs + +Consider the following program: + +```rust +struct Type1 { + val1: Field, + val2: Field, +} + +struct Nested { + t1: Type1, + is_true: bool, +} + +fn main(x: pub Field, nested: pub Nested, y: pub Field) { + //... +} +``` + +Structs will be flattened so that the array of inputs is 1-dimensional array. The order of these inputs would be flattened to: `[x, nested.t1.val1, nested.t1.val2, nested.is_true, y]` + +## Noir for EVM chains + +You can currently deploy the Solidity verifier contracts to most EVM compatible chains. EVM chains that have been tested and are known to work include: + +- Optimism +- Arbitrum +- Polygon PoS +- Scroll +- Celo + +Other EVM chains should work, but have not been tested directly by our team. If you test any other chains, please open a PR on this page to update the list. See [this doc](https://github.com/noir-lang/noir-starter/tree/main/with-foundry#testing-on-chain) for more info about testing verifier contracts on different EVM chains. + +### Unsupported chains + +Unfortunately not all "EVM" chains are supported. + +**zkSync** and the **Polygon zkEVM** do _not_ currently support proof verification via Solidity verifier contracts. They are missing the bn256 precompile contract that the verifier contract requires. Once these chains support this precompile, they may work. diff --git a/docs/versioned_docs/version-0.17.0/nargo/04_language_server.md b/docs/versioned_docs/version-0.17.0/nargo/04_language_server.md new file mode 100644 index 00000000000..48c01465f6e --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/nargo/04_language_server.md @@ -0,0 +1,42 @@ +--- +title: Language Server +description: Learn about the Noir Language Server, how to install the components, and configuration that may be required. +keywords: [Nargo, Language Server, LSP, VSCode, Visual Studio Code] +--- + +This section helps you install and configure the Noir Language Server. + +The Language Server Protocol (LSP) has two components, the [Server](#language-server) and the [Client](#language-client). Below we describe each in the context of Noir. + +## Language Server + +The Server component is provided by the Nargo command line tool that you installed at the beginning of this guide. +As long as Nargo is installed and you've used it to run other commands in this guide, it should be good to go! + +If you'd like to verify that the `nargo lsp` command is available, you can run `nargo --help` and look for `lsp` in the list of commands. If you see it, you're using a version of Noir with LSP support. + +## Language Client + +The Client component is usually an editor plugin that launches the Server. It communicates LSP messages between the editor and the Server. For example, when you save a file, the Client will alert the Server, so it can try to compile the project and report any errors. + +Currently, Noir provides a Language Client for Visual Studio Code via the [vscode-noir](https://github.com/noir-lang/vscode-noir) extension. You can install it via the [Visual Studio Marketplace](https://marketplace.visualstudio.com/items?itemName=noir-lang.vscode-noir). + +> **Note:** Noir's Language Server Protocol support currently assumes users' VSCode workspace root to be the same as users' Noir project root (i.e. where Nargo.toml lies). +> +> If LSP features seem to be missing / malfunctioning, make sure you are opening your Noir project directly (instead of as a sub-folder) in your VSCode instance. + +When your language server is running correctly and the VSCode plugin is installed, you should see handy codelens buttons for compilation, measuring circuit size, execution, and tests: + +![Compile and Execute](@site/static/img/codelens_compile_execute.png) +![Run test](@site/static/img/codelens_run_test.png) + +You should also see your tests in the `testing` panel: + +![Testing panel](@site/static/img/codelens_testing_panel.png) + +### Configuration + +- **Noir: Enable LSP** - If checked, the extension will launch the Language Server via `nargo lsp` and communicate with it. +- **Noir: Nargo Flags** - Additional flags may be specified if you require them to be added when the extension calls `nargo lsp`. +- **Noir: Nargo Path** - An absolute path to a Nargo binary with the `lsp` command. This may be useful if Nargo is not within the `PATH` of your editor. +- **Noir > Trace: Server** - Setting this to `"messages"` or `"verbose"` will log LSP messages between the Client and Server. Useful for debugging. diff --git a/docs/versioned_docs/version-0.17.0/noir_js/getting_started/01_tiny_noir_app.md b/docs/versioned_docs/version-0.17.0/noir_js/getting_started/01_tiny_noir_app.md new file mode 100644 index 00000000000..6955f7a1e64 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/noir_js/getting_started/01_tiny_noir_app.md @@ -0,0 +1,256 @@ +--- +title: End-to-end +description: Learn how to setup a new app that uses Noir to generate and verify zero-knowledge SNARK proofs in a typescript or javascript environment +keywords: [how to, guide, javascript, typescript, noir, barretenberg, zero-knowledge, proofs] +--- + +NoirJS works both on the browser and on the server, and works for both ESM and CJS module systems. In this page, we will learn how can we write a simple test and a simple web app to verify the standard Noir example. + +## Before we start + +:::note + +Feel free to use whatever versions, just keep in mind that Nargo and the NoirJS packages are meant to be in sync. For example, Nargo 0.18.x matches `noir_js@0.18.x`, etc. + +In this guide, we will be pinned to 0.17.0. + +::: + +Make sure you have Node installed on your machine by opening a terminal and executing `node --version`. If you don't see a version, you should install [node](https://github.com/nvm-sh/nvm). You can also use `yarn` if you prefer that package manager over npm (which comes with node). + +First of all, follow the the [Nargo guide](../../getting_started/00_nargo_installation.md) to install nargo version 0.17.0 and create a new project with `nargo new circuit`. Once there, `cd` into the `circuit` folder. You should then be able to compile your circuit into `json` format and see it inside the `target` folder: + +```bash +nargo compile +``` + +Your folder structure should look like: + +```tree +. +└── circuit + ├── Nargo.toml + ├── src + │ └── main.nr + └── target + └── circuit.json +``` + +## Starting a new project + +Go back to the previous folder and start a new project by running run `npm init`. You can configure your project or just leave the defaults, and see a `package.json` appear in your root folder. + +## Installing dependencies + +We'll need two `npm` packages. These packages will provide us the methods we need to run and verify proofs: + +```bash +npm i @noir-lang/backend_barretenberg@^0.17.0 @noir-lang/noir_js@^0.17.0 +``` + +To serve our page, we can use a build tool such as `vite`. Because we're gonna use some `wasm` files, we need to install a plugin as well. Run: + +```bash +npm i --save-dev vite rollup-plugin-copy +``` + +Since we're on the dependency world, we may as well define a nice starting script. Vite makes it easy. Just open `package.json`, find the block "scripts" and add this just below the line with `"test" : "echo......."`: + +```json + "start": "vite --open" +``` + +If you want do build a static website, you can also add some build and preview scripts: + +```json + "build": "vite build", + "preview": "vite preview" +``` + +## Vite plugins + +Vite is great, but support from `wasm` doesn't work out-of-the-box. We're gonna write a quick plugin and use another one. Just copy and paste this into a file named `vite.config.js`. You don't need to understand it, just trust me bro. + +```js +import { defineConfig } from 'vite'; +import copy from 'rollup-plugin-copy'; +import fs from 'fs'; +import path from 'path'; + +const wasmContentTypePlugin = { + name: 'wasm-content-type-plugin', + configureServer(server) { + server.middlewares.use(async (req, res, next) => { + if (req.url.endsWith('.wasm')) { + res.setHeader('Content-Type', 'application/wasm'); + const newPath = req.url.replace('deps', 'dist'); + const targetPath = path.join(__dirname, newPath); + const wasmContent = fs.readFileSync(targetPath); + return res.end(wasmContent); + } + next(); + }); + }, +}; + +export default defineConfig(({ command }) => { + if (command === 'serve') { + return { + plugins: [ + copy({ + targets: [{ src: 'node_modules/**/*.wasm', dest: 'node_modules/.vite/dist' }], + copySync: true, + hook: 'buildStart', + }), + command === 'serve' ? wasmContentTypePlugin : [], + ], + }; + } + + return {}; +}); +``` + +## HTML + +Here's the simplest HTML with some terrible UI. Create a file called `index.html` and paste this: + +```html + + + + + + +

Very basic Noir app

+
+

Logs

+

Proof

+
+ + +``` + +## Some good old vanilla Javascript + +Create a new file `app.js`, which is where our javascript code will live. Let's start with this code inside: + +```js +document.addEventListener('DOMContentLoaded', async () => { + // here's where the magic happens +}); + +function display(container, msg) { + const c = document.getElementById(container); + const p = document.createElement('p'); + p.textContent = msg; + c.appendChild(p); +} +``` + +We can manipulate our website with this little function, so we can see our website working. + +## Adding Noir + +If you come from the previous page, your folder structure should look like this: + +```tree +├── app.js +├── circuit +│ ├── Nargo.toml +│ ├── src +│ │ └── main.nr +│ └── target +│ └── circuit.json +├── index.html +├── package.json +└── vite.config.js +``` + +You'll see other files and folders showing up (like `package-lock.json`, `yarn.lock`, `node_modules`) but you shouldn't have to care about those. + +## Importing our dependencies + +We're starting with the good stuff now. At the top of the new javascript file, import the packages: + +```ts +import { BarretenbergBackend } from '@noir-lang/backend_barretenberg'; +import { Noir } from '@noir-lang/noir_js'; +``` + +We also need to import the `circuit` JSON file we created. If you have the suggested folder structure, you can add this line: + +```ts +import circuit from './circuit/target/circuit.json'; +``` + +## Write code + +:::note + +We're gonna be adding code inside the `document.addEventListener...etc` block: + +```js +// forget stuff here +document.addEventListener('DOMContentLoaded', async () => { + // here's where the magic happens +}); +// forget stuff here +``` + +::: + +Our dependencies exported two classes: `BarretenbergBackend` and `Noir`. Let's `init` them and add some logs, just to flex: + +```ts +const backend = new BarretenbergBackend(circuit); +const noir = new Noir(circuit, backend); +``` + +## Proving + +Now we're ready to prove stuff! Let's feed some inputs to our circuit and calculate the proof: + +```js +const input = { x: 1, y: 2 }; +display('logs', 'Generating proof... ⌛'); +const proof = await noir.generateFinalProof(input); +display('logs', 'Generating proof... ✅'); +display('results', proof.proof); +``` + +You're probably eager to see stuff happening, so go and run your app now! + +From your terminal, run `npm start` (or `yarn start`). If it doesn't open a browser for you, just visit `localhost:5173`. On a modern laptop, proof will generate in less than 100ms, and you'll see this: + +![Getting Started 0](@site/static/img/noir_getting_started_1.png) + +If you're human, you shouldn't be able to understand anything on the "proof" box. That's OK. We like you, human. + +In any case, this means your proof was generated! But you shouldn't trust me just yet. Add these lines to see it being verified: + +```js +display('logs', 'Verifying proof... ⌛'); +const verification = await noir.verifyFinalProof(proof); +if (verification) display('logs', 'Verifying proof... ✅'); +``` + +By saving, your app will refresh and here's our complete Tiny Noir App! + +## Further Reading + +You can see how noirjs is used in a full stack Next.js hardhat application in the [noir-starter repo here](https://github.com/noir-lang/noir-starter/tree/main/next-hardhat). The example shows how to calculate a proof in the browser and verify it with a deployed Solidity verifier contract from noirjs. + +You should also check out the more advanced examples in the [noir-examples repo](https://github.com/noir-lang/noir-examples), where you'll find reference usage for some cool apps. diff --git a/docs/versioned_docs/version-0.17.0/noir_js/noir_js.md b/docs/versioned_docs/version-0.17.0/noir_js/noir_js.md new file mode 100644 index 00000000000..23ea550e156 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/noir_js/noir_js.md @@ -0,0 +1,36 @@ +--- +title: NoirJS +description: Interact with Noir in Typescript or Javascript +keywords: [Noir project, javascript, typescript, node.js, browser, react] +--- + +NoirJS is a TypeScript library that make it easy to use Noir on your dapp, webapp, Node.js server, website, etc. + +A typical workflow would be composed of two major elements: + +- NoirJS +- Proving backend of choice's JavaScript package + + + +To install NoirJS, install Node.js if you have not already and run this in your JavaScript project: + +```bash +npm i @noir-lang/noir_js +``` + +## Proving backend + +Since Noir is backend agnostic, you can instantiate NoirJS without any backend (i.e. to execute a function). But for proving, you would have to instantiate NoirJS with any of the supported backends through their own `js` interface. + +### Barretenberg + +Aztec Labs maintains the `barretenberg` proving backend, which you can instantiate and make use of alongside NoirJS. It is also the default proving backend installed and used with Nargo, the Noir CLI tool. + +To install its JavaScript library, run this in your project: + +```bash +npm i @noir-lang/backend_barretenberg +``` + +For more details on how to instantiate and use the libraries, refer to the [Full Noir App Guide](./getting_started/01_tiny_noir_app.md) and [Reference](./reference/01_noirjs.md) sections. diff --git a/docs/versioned_docs/version-0.17.0/noir_js/reference/01_noirjs.md b/docs/versioned_docs/version-0.17.0/noir_js/reference/01_noirjs.md new file mode 100644 index 00000000000..d9e5a0c6115 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/noir_js/reference/01_noirjs.md @@ -0,0 +1,143 @@ +--- +title: Noir +description: Reference to noir_js library and the Noir class +keywords: [Noir project, javascript, typescript, node.js, browser, react, class, reference] +--- + +## Table of Contents + +- [constructor](#constructor) +- [init](#init) +- [generateFinalProof](#generatefinalproof) +- [verifyFinalProof](#verifyfinalproof) + +## `constructor` + +The `constructor` is a method used to create and initialize objects created within the `Noir` class. In the `Noir` class constructor, you need to pass two parameters: `circuit` and `backend`. + +### Syntax + +```js +constructor(circuit, backend); +``` + +### Parameters + +| Parameter | Type | Description | +| --------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `circuit` | Object | A circuit represented in a `json` format, containing the ABI and bytecode. Typically obtained by running [`nargo compile`](../../nargo/01_commands.md) | +| `backend` | Object | A backend instance, before initialization. | + +### Usage + +```js +const noir = new Noir(circuit, backend); +``` + +## `init` + +This async method should be called after class instantiation. It will run processes on the ACVM, instantiate your backend, etc. + +### Syntax + +```js +async init() +``` + +### Parameters + +This method takes no parameters + +### Usage + +```js +await noirInstance.init(); +``` + +## `execute` + +This async method allows to execute a circuit to get its witness and return value. [`generateFinalProof`](#generatefinalproof) calls it for you, but you can call it directly (i.e. to feed directly to a backend, or to get the return value). + +### Syntax + +```js +async execute(inputs) +``` + +### Parameters + +| Parameter | Type | Description | +| --------- | ------ | ------------------------------------------------ | +| `inputs` | Object | An object containing the inputs to your circuit. | + +### Returns + +| Return value | Type | Description | +| ------------ | --------------------- | --------------------------------------------------- | +| `witness` | Promise | The witness | +| `returnValue` | Promise | The return value | + +### Usage + +```js +const { witness, returnValue } = await noir.execute(inputs) +``` + +## `generateFinalProof` + +This async method generates a witness and a proof given an object as input. + +### Syntax + +```js +async generateFinalproof(input) +``` + +### Parameters + +| Parameter | Type | Description | +| --------- | ------ | ------------------------------------------------ | +| `input` | Object | An object containing the inputs to your circuit. | + +### Returns + +| Return value | Type | Description | +| ------------ | --------------------- | --------------------------------------------------- | +| `proof` | Promise | An array with the byte representation of the proof. | + +### Usage + +```js +// consider the Standard Noir Example given with nargo init +const input = { x: 1, y: 2 }; +noirInstance.generateProof(input); +``` + +## `verifyFinalProof` + +This async method instantiates the verification key and verifies your proof. + +### Syntax + +```js +async verifyFinalProof(proof) +``` + +### Parameters + +| Parameter | Type | Description | +| --------- | ---------- | --------------------------------------------------------------------------------------------- | +| `proof` | Uint8Array | The Uint8Array representation of your proof, usually obtained by calling `generateFinalProof` | + +### Returns + +| Return value | Type | Description | +| ------------ | ------------------ | -------------------------------------------- | +| `verified` | Promise | A boolean for whether the proof was verified | + +### Usage + +```js +const proof = noirInstance.generateProof(input); +noirInstance.verifyFinalProof(proof); +``` diff --git a/docs/versioned_docs/version-0.17.0/noir_js/reference/02_bb_backend.md b/docs/versioned_docs/version-0.17.0/noir_js/reference/02_bb_backend.md new file mode 100644 index 00000000000..21c2ff32b57 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/noir_js/reference/02_bb_backend.md @@ -0,0 +1,272 @@ +--- +title: BarretenbergBackend +description: Reference documentation for the barretenberg_backend library and the BarretenbergBackend class +keywords: + [ + BarretenbergBackend, + Barretenberg, + javascript, + typescript, + node.js, + browser, + class, + reference, + noir_js, + ] +--- + +## Table of Contents + +- [constructor](#constructor) +- [generateFinalProof](#generatefinalproof) +- [generateIntermediateProof](#generateintermediateproof) +- [generateProof](#generateproof) +- [generateIntermediateProofArtifacts](#generateintermediateproofartifacts) +- [verifyFinalProof](#verifyfinalproof) +- [verifyIntermediateProof](#verifyintermediateproof) +- [verifyProof](#verifyproof) +- [destroy](#destroy) + +## `constructor` + +The `constructor` is a method used to create and initialize objects created within the `BarretenbergBackend` class. In this class, you should pass at least one argument for the `circuit`. + +### Syntax + +```js +constructor(acirCircuit, (numberOfThreads = 1)); +``` + +### Parameters + +| Parameter | Type | Description | +| ----------------- | ----------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `acirCircuit` | Object | A circuit represented in a `json` format, containing the ABI and bytecode Tipically obtained by running [`nargo compile`](../../nargo/01_commands.md). This is the same circuit expected to be passed to [the Noir class](01_noirjs.md) | +| `numberOfThreads` | Number (optional) | The number of threads to be used by the backend. Defaults to 1. | + +### Usage + +```js +const backend = new BarretenbergBackend(acirCircuit); +``` + +## `generateFinalProof` + +An async wrapper around the [generateProof](#generateproof) method that passes a `false` flag. Usually called by the Noir class. + +### Syntax + +```js +async generateFinalProof(decompressedWitness) +``` + +### Parameters + +| Parameter | Type | Description | +| --------------------- | ------ | -------------------------------------------------------- | +| `decompressedWitness` | Object | The decompressed witness for generating the final proof. | + +### Returns + +| Return value | Type | Description | +| ------------ | -------------------- | --------------------------------------------------------- | +| `proof` | Promise | An array with the byte representation of the final proof. | + +### Usage + +```js +const finalProof = await backend.generateFinalProof(decompressedWitness); +``` + +## `generateIntermediateProof` + +An async wrapper around the [generateProof](#generateproof) method that passes a `true` flag. It's not currently being used by the Noir class, but developers can call this method directly to use Noir's recursive features. + +### Syntax + +```js +async generateIntermediateProof(witness) +``` + +### Parameters + +| Parameter | Type | Description | +| --------- | ------ | -------------------------------------------------- | +| `witness` | Object | The witness for generating the intermediate proof. | + +### Returns + +| Return value | Type | Description | +| ------------ | -------------------- | --------------------------------------------------------------- | +| `proof` | Promise | An array with the byte representation of the intermediate proof | + +### Usage + +```js +const intermediateProof = await backend.generateIntermediateProof(witness); +``` + +## `generateProof` + +This async method generates a proof. Takes the witness generated by ACVM, and a boolean that evaluates to `true` when the proof _is_ meant to be verified in another circuit. Not currently used by the Noir class. + +### Syntax + +```js +async generateProof(decompressedWitness, makeEasyToVerifyInCircuit) +``` + +### Parameters + +| Parameter | Type | Description | +| --------------------------- | ------- | ---------------------------------------------------------------------------------------------- | +| `decompressedWitness` | Object | The decompressed witness for generating the proof. | +| `makeEasyToVerifyInCircuit` | Boolean | A flag indicating whether to generate proof components for easy verification within a circuit. | + +### Returns + +| Return value | Type | Description | +| ------------ | -------------------- | -------------------------------------------------- | +| `proof` | Promise | An array with the byte representation of the proof | + +### Usage + +```js +const proof = await backend.generateProof(decompressedWitness, makeEasyToVerifyInCircuit); +``` + +## `generateIntermediateProofArtifacts` + +This async method returns the artifacts needed to verify the intermediate proof in another circuit. It's not currently being used by the Noir class, but developers can call this method directly to use Noir's recursive features. + +### Syntax + +```js +async generateIntermediateProofArtifacts(proof, numOfPublicInputs = 0) +``` + +### Parameters + +| Parameter | Type | Description | +| ------------------- | ----------------- | ---------------------------------------------------------------- | +| `proof` | Object | The proof object. | +| `numOfPublicInputs` | Number (optional) | The number of public inputs in the inner proof, defaulting to 0. | + +### Returns + +| Return value | Type | Description | +| --------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `proofAsFields` | string[] | An array of strings with the hexadecimal representation of the [Fields](../../language_concepts/data_types/00_fields.md) that make up a proof | +| `vkAsFields` | string[] | An array of strings with the hexadecimal representation of the [Fields](../../language_concepts/data_types/00_fields.md) that make up the verification key | +| `vkHash` | string | A pedersen hash of the verification key | + +### Usage + +```js +const artifacts = await backend.generateIntermediateProofArtifacts(proof, numOfPublicInputs); +``` + +## `verifyFinalProof` + +An async wrapper around [verifyProof](#verifyproof) that sets the `false` flag. Usually called by the Noir class. + +### Syntax + +```js +async verifyFinalProof(proof) +``` + +### Parameters + +| Parameter | Type | Description | +| --------- | ------ | --------------------------- | +| `proof` | Object | The proof object to verify. | + +### Returns + +| Return value | Type | Description | +| ------------ | ------------------ | -------------------------------------------- | +| `verified` | Promise | A boolean for whether the proof was verified | + +### Usage + +```js +const isValidFinal = await backend.verifyFinalProof(proof); +``` + +## `verifyIntermediateProof` + +An async wrapper around [verifyProof](#verifyproof) that sets the `true` flag. It's not currently being used by the Noir class, but developers can call this method directly to use Noir's recursive features. + +### Syntax + +```js +async verifyIntermediateProof(proof) +``` + +### Parameters + +| Parameter | Type | Description | +| --------- | ------ | ---------------------------------------- | +| `proof` | Object | The intermediate proof object to verify. | + +### Returns + +| Return value | Type | Description | +| ------------ | ------------------ | -------------------------------------------- | +| `verified` | Promise | A boolean for whether the proof was verified | + +### Usage + +```js +const isValidIntermediate = await backend.verifyIntermediateProof(proof); +``` + +## `verifyProof` + +This async method verifies a proof. Takes the proof, and a boolean that evaluates to `true` when the proof is intermediate. + +### Syntax + +```js +async verifyProof(proof, makeEasyToVerifyInCircuit) +``` + +### Parameters + +| Parameter | Type | Description | +| --------------------------- | ------- | ------------------------------------------------------------ | +| `proof` | Object | The proof object to verify | +| `makeEasyToVerifyInCircuit` | Boolean | A flag indicating whether the proof is intermediate or final | + +### Returns + +| Parameter | Type | Description | +| ---------- | ------------------ | -------------------------------------------- | +| `verified` | Promise\ | A boolean for whether the proof was verified | + +### Usage + +```js +const isValid = await backend.verifyProof(proof, makeEasyToVerifyInCircuit); +``` + +## `destroy` + +This method destroys the resources allocated in the [instantiate](#instantiate) method. Noir doesn't currently call this method, but it's highly recommended that developers do so in order to save resources. + +### Syntax + +```js +async destroy() +``` + +### Parameters + +This method takes no parameters. + +### Usage + +```js +await backend.destroy(); +``` diff --git a/docs/versioned_docs/version-0.17.0/standard_library/black_box_fns.md b/docs/versioned_docs/version-0.17.0/standard_library/black_box_fns.md new file mode 100644 index 00000000000..c758846b688 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/standard_library/black_box_fns.md @@ -0,0 +1,45 @@ +--- +title: Black Box Functions +description: Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. +keywords: [noir, black box functions] +--- + +Black box functions are functions in Noir that rely on backends implementing support for specialized constraints. This makes certain zk-snark unfriendly computations cheaper than if they were implemented in Noir. + +:::warning + +It is likely that not all backends will support a particular black box function. + +::: + +Because it is not guaranteed that all backends will support black box functions, it is possible that certain Noir programs won't compile against a particular backend if they use an unsupported black box function. It is possible to fallback to less efficient implementations written in Noir/ACIR in some cases. + +Black box functions are specified with the `#[foreign(black_box_fn)]` attribute. For example, the SHA256 function in the Noir [source code](https://github.com/noir-lang/noir/blob/v0.5.1/noir_stdlib/src/hash.nr) looks like: + +```rust +#[foreign(sha256)] +fn sha256(_input : [u8; N]) -> [u8; 32] {} +``` + +## Function list + +Here is a list of the current black box functions that are supported by UltraPlonk: + +- AES +- [SHA256](./cryptographic_primitives/hashes#sha256) +- [Schnorr signature verification](./cryptographic_primitives/schnorr) +- [Blake2s](./cryptographic_primitives/hashes#blake2s) +- [Pedersen](./cryptographic_primitives/hashes#pedersen) +- [HashToField128Security](./cryptographic_primitives/hashes#hash_to_field) +- [ECDSA signature verification](./cryptographic_primitives/ecdsa_sig_verification) +- [Fixed base scalar multiplication](./cryptographic_primitives/scalar) +- [Compute merkle root](./merkle_trees#compute_merkle_root) +- AND +- XOR +- RANGE +- [Keccak256](./cryptographic_primitives/hashes#keccak256) +- [Recursive proof verification](./recursion) + +Most black box functions are included as part of the Noir standard library, however `AND`, `XOR` and `RANGE` are used as part of the Noir language syntax. For instance, using the bitwise operator `&` will invoke the `AND` black box function. To ensure compatibility across backends, the ACVM has fallback implementations of `AND`, `XOR` and `RANGE` defined in its standard library which it can seamlessly fallback to if the backend doesn't support them. + +You can view the black box functions defined in the ACVM code [here](https://github.com/noir-lang/acvm/blob/acir-v0.12.0/acir/src/circuit/black_box_functions.rs). diff --git a/docs/versioned_docs/version-0.17.0/standard_library/cryptographic_primitives.md b/docs/versioned_docs/version-0.17.0/standard_library/cryptographic_primitives.md new file mode 100644 index 00000000000..2df4f929474 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/standard_library/cryptographic_primitives.md @@ -0,0 +1,14 @@ +--- +title: Cryptographic primitives in Noir +description: + Learn about the cryptographic primitives ready to use for any Noir project +keywords: + [ + cryptographic primitives, + Noir project, + ] +--- + +The Noir team is progressively adding new cryptographic primitives to the standard library. Reach out for news or if you would be interested in adding more of these calculations in Noir. + +Some methods are available thanks to the Aztec backend, not being performed using Noir. When using other backends, these methods may or may not be supplied. diff --git a/docs/versioned_docs/version-0.17.0/standard_library/cryptographic_primitives/00_hashes.mdx b/docs/versioned_docs/version-0.17.0/standard_library/cryptographic_primitives/00_hashes.mdx new file mode 100644 index 00000000000..2cc3cd81e4e --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/standard_library/cryptographic_primitives/00_hashes.mdx @@ -0,0 +1,146 @@ +--- +title: Hash methods +description: + Learn about the cryptographic primitives ready to use for any Noir project, including sha256, + blake2s, pedersen, mimc_bn254 and mimc +keywords: + [cryptographic primitives, Noir project, sha256, blake2s, pedersen, mimc_bn254, mimc, hash] +--- + +import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; + +## sha256 + +Given an array of bytes, returns the resulting sha256 hash. + +```rust +fn sha256(_input : [u8]) -> [u8; 32] +``` + +example: + +```rust +fn main() { + let x = [163, 117, 178, 149]; // some random bytes + let hash = std::hash::sha256(x); +} +``` + + + +## blake2s + +Given an array of bytes, returns an array with the Blake2 hash + +```rust +fn blake2s(_input : [u8]) -> [u8; 32] +``` + +example: + +```rust +fn main() { + let x = [163, 117, 178, 149]; // some random bytes + let hash = std::hash::blake2s(x); +} +``` + + + +## pedersen + +Given an array of Fields, returns the Pedersen hash. + +```rust +fn pedersen(_input : [Field]) -> [Field; 2] +``` + +example: + +```rust +fn main() { + let x = [163, 117, 178, 149]; // some random bytes + let hash = std::hash::pedersen(x); +} +``` + + + +## keccak256 + +Given an array of bytes (`u8`), returns the resulting keccak hash as an array of 32 bytes +(`[u8; 32]`). Specify a message_size to hash only the first `message_size` bytes +of the input. + +```rust +fn keccak256(_input : [u8; N], _message_size: u32) -> [u8; 32] +``` + +example: + +```rust +fn main() { + let x = [163, 117, 178, 149]; // some random bytes + let message_size = 4; + let hash = std::hash::keccak256(x, message_size); +} +``` + + + +## poseidon + +Given an array of Fields, returns a new Field with the Poseidon Hash. Mind that you need to specify +how many inputs are there to your Poseidon function. + +```rust +// example for hash_1, hash_2 accepts an array of length 2, etc +fn hash_1(input: [Field; 1]) -> Field +``` + +example: + +```rust +fn main() +{ + let hash1 = std::hash::poseidon::bn254::hash_2([1, 2]); + assert(hash1 == 0x115cc0f5e7d690413df64c6b9662e9cf2a3617f2743245519e19607a4417189a); +} +``` + +## mimc_bn254 and mimc + +`mimc_bn254` is `mimc`, but with hardcoded parameters for the BN254 curve. You can use it by +providing an array of Fields, and it returns a Field with the hash. You can use the `mimc` method if +you're willing to input your own constants: + +```rust +fn mimc(x: Field, k: Field, constants: [Field; N], exp : Field) -> Field +``` + +otherwise, use the `mimc_bn254` method: + +```rust +fn mimc_bn254(array: [Field; N]) -> Field +``` + +example: + +```rust + +fn main() { + let x = [163, 117, 178, 149]; // some random bytes + let hash = std::hash::mimc_bn254(x); +} +``` + +## hash_to_field + +```rust +fn hash_to_field(_input : [Field; N]) -> Field {} +``` + +Calculates the `blake2s` hash of the inputs and returns the hash modulo the field modulus to return +a value which can be represented as a `Field`. + + diff --git a/docs/versioned_docs/version-0.17.0/standard_library/cryptographic_primitives/01_scalar.mdx b/docs/versioned_docs/version-0.17.0/standard_library/cryptographic_primitives/01_scalar.mdx new file mode 100644 index 00000000000..c7eed820a80 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/standard_library/cryptographic_primitives/01_scalar.mdx @@ -0,0 +1,27 @@ +--- +title: Scalar multiplication +description: See how you can perform scalar multiplications over a fixed base in Noir +keywords: [cryptographic primitives, Noir project, scalar multiplication] +--- + +import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; + +## scalar_mul::fixed_base_embedded_curve + +Performs scalar multiplication over the embedded curve whose coordinates are defined by the +configured noir field. For the BN254 scalar field, this is BabyJubJub or Grumpkin. + +```rust +fn fixed_base_embedded_curve(_input : Field) -> [Field; 2] +``` + +example + +```rust +fn main(x : Field) { + let scal = std::scalar_mul::fixed_base_embedded_curve(x); + std::println(scal); +} +``` + + diff --git a/docs/versioned_docs/version-0.17.0/standard_library/cryptographic_primitives/02_schnorr.mdx b/docs/versioned_docs/version-0.17.0/standard_library/cryptographic_primitives/02_schnorr.mdx new file mode 100644 index 00000000000..c184ce28120 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/standard_library/cryptographic_primitives/02_schnorr.mdx @@ -0,0 +1,37 @@ +--- +title: Schnorr Signatures +description: Learn how you can verify Schnorr signatures using Noir +keywords: [cryptographic primitives, Noir project, schnorr, signatures] +--- + +import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; + +## schnorr::verify_signature + +Verifier for Schnorr signatures over the embedded curve (for BN254 it is Grumpkin). + +```rust +fn verify_signature(_public_key_x: Field, _public_key_y: Field, _signature: [u8; 64], _message: [u8]) -> bool +``` + +where `_signature` can be generated like so using the npm package +[@noir-lang/barretenberg](https://www.npmjs.com/package/@noir-lang/barretenberg) + +```js +const { BarretenbergWasm } = require('@noir-lang/barretenberg/dest/wasm'); +const { Schnorr } = require('@noir-lang/barretenberg/dest/crypto/schnorr'); + +... + +const barretenberg = await BarretenbergWasm.new(); +const schnorr = new Schnorr(barretenberg); +const pubKey = schnorr.computePublicKey(privateKey); +const message = ... +const signature = Array.from( + schnorr.constructSignature(hash, privateKey).toBuffer() +); + +... +``` + + diff --git a/docs/versioned_docs/version-0.17.0/standard_library/cryptographic_primitives/03_ecdsa_sig_verification.mdx b/docs/versioned_docs/version-0.17.0/standard_library/cryptographic_primitives/03_ecdsa_sig_verification.mdx new file mode 100644 index 00000000000..72bce984821 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/standard_library/cryptographic_primitives/03_ecdsa_sig_verification.mdx @@ -0,0 +1,45 @@ +--- +title: ECDSA Signature Verification +description: Learn about the cryptographic primitives regarding ECDSA over the secp256k1 and secp256r1 curves +keywords: [cryptographic primitives, Noir project, ecdsa, secp256k1, secp256r1, signatures] +--- + +import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; + +Noir supports ECDSA signatures verification over the secp256k1 and secp256r1 curves. + +## ecdsa_secp256k1::verify_signature + +Verifier for ECDSA Secp256k1 signatures + +```rust +fn verify_signature(_public_key_x : [u8; 32], _public_key_y : [u8; 32], _signature: [u8; 64], _message: [u8]) -> bool +``` + +example: + +```rust +fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { + let valid_signature = std::ecdsa_secp256k1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); + assert(valid_signature); +} +``` + +## ecdsa_secp256r1::verify_signature + +Verifier for ECDSA Secp256r1 signatures + +```rust +fn verify_signature(_public_key_x : [u8; 32], _public_key_y : [u8; 32], _signature: [u8; 64], _message: [u8]) -> bool +``` + +example: + +```rust +fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { + let valid_signature = std::ecdsa_secp256r1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); + assert(valid_signature); +} +``` + + diff --git a/docs/versioned_docs/version-0.17.0/standard_library/cryptographic_primitives/04_ec_primitives.md b/docs/versioned_docs/version-0.17.0/standard_library/cryptographic_primitives/04_ec_primitives.md new file mode 100644 index 00000000000..6e6b19b6861 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/standard_library/cryptographic_primitives/04_ec_primitives.md @@ -0,0 +1,101 @@ +--- +title: Elliptic Curve Primitives +keywords: [cryptographic primitives, Noir project] +--- + +Data structures and methods on them that allow you to carry out computations involving elliptic +curves over the (mathematical) field corresponding to `Field`. For the field currently at our +disposal, applications would involve a curve embedded in BN254, e.g. the +[Baby Jubjub curve](https://eips.ethereum.org/EIPS/eip-2494). + +## Data structures + +### Elliptic curve configurations + +(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Curve`), i.e. the specific elliptic +curve you want to use, which would be specified using any one of the methods +`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::new` which take the coefficients in the +defining equation together with a generator point as parameters. You can find more detail in the +comments in +[`noir_stdlib/src/ec.nr`](https://github.com/noir-lang/noir/blob/master/noir_stdlib/src/ec.nr), but +the gist of it is that the elliptic curves of interest are usually expressed in one of the standard +forms implemented here (Twisted Edwards, Montgomery and Short Weierstraß), and in addition to that, +you could choose to use `affine` coordinates (Cartesian coordinates - the usual (x,y) - possibly +together with a point at infinity) or `curvegroup` coordinates (some form of projective coordinates +requiring more coordinates but allowing for more efficient implementations of elliptic curve +operations). Conversions between all of these forms are provided, and under the hood these +conversions are done whenever an operation is more efficient in a different representation (or a +mixed coordinate representation is employed). + +### Points + +(`std::ec::{tecurve,montcurve,swcurve}::{affine,curvegroup}::Point`), i.e. points lying on the +elliptic curve. For a curve configuration `c` and a point `p`, it may be checked that `p` +does indeed lie on `c` by calling `c.contains(p1)`. + +## Methods + +(given a choice of curve representation, e.g. use `std::ec::tecurve::affine::Curve` and use +`std::ec::tecurve::affine::Point`) + +- The **zero element** is given by `Point::zero()`, and we can verify whether a point `p: Point` is + zero by calling `p.is_zero()`. +- **Equality**: Points `p1: Point` and `p2: Point` may be checked for equality by calling + `p1.eq(p2)`. +- **Addition**: For `c: Curve` and points `p1: Point` and `p2: Point` on the curve, adding these two + points is accomplished by calling `c.add(p1,p2)`. +- **Negation**: For a point `p: Point`, `p.negate()` is its negation. +- **Subtraction**: For `c` and `p1`, `p2` as above, subtracting `p2` from `p1` is accomplished by + calling `c.subtract(p1,p2)`. +- **Scalar multiplication**: For `c` as above, `p: Point` a point on the curve and `n: Field`, + scalar multiplication is given by `c.mul(n,p)`. If instead `n :: [u1; N]`, i.e. `n` is a bit + array, the `bit_mul` method may be used instead: `c.bit_mul(n,p)` +- **Multi-scalar multiplication**: For `c` as above and arrays `n: [Field; N]` and `p: [Point; N]`, + multi-scalar multiplication is given by `c.msm(n,p)`. +- **Coordinate representation conversions**: The `into_group` method converts a point or curve + configuration in the affine representation to one in the CurveGroup representation, and + `into_affine` goes in the other direction. +- **Curve representation conversions**: `tecurve` and `montcurve` curves and points are equivalent + and may be converted between one another by calling `into_montcurve` or `into_tecurve` on their + configurations or points. `swcurve` is more general and a curve c of one of the other two types + may be converted to this representation by calling `c.into_swcurve()`, whereas a point `p` lying + on the curve given by `c` may be mapped to its corresponding `swcurve` point by calling + `c.map_into_swcurve(p)`. +- **Map-to-curve methods**: The Elligator 2 method of mapping a field element `n: Field` into a + `tecurve` or `montcurve` with configuration `c` may be called as `c.elligator2_map(n)`. For all of + the curve configurations, the SWU map-to-curve method may be called as `c.swu_map(z,n)`, where + `z: Field` depends on `Field` and `c` and must be chosen by the user (the conditions it needs to + satisfy are specified in the comments + [here](https://github.com/noir-lang/noir/blob/master/noir_stdlib/src/ec.nr)). + +## Examples + +The +[ec_baby_jubjub test](https://github.com/noir-lang/noir/blob/master/crates/nargo_cli/tests/test_data/ec_baby_jubjub/src/main.nr) +illustrates all of the above primitives on various forms of the Baby Jubjub curve. A couple of more +interesting examples in Noir would be: + +Public-key cryptography: Given an elliptic curve and a 'base point' on it, determine the public key +from the private key. This is a matter of using scalar multiplication. In the case of Baby Jubjub, +for example, this code would do: + +```rust +use dep::std::ec::tecurve::affine::{Curve, Point}; + +fn bjj_pub_key(priv_key: Field) -> Point +{ + + let bjj = Curve::new(168700, 168696, G::new(995203441582195749578291179787384436505546430278305826713579947235728471134,5472060717959818805561601436314318772137091100104008585924551046643952123905)); + + let base_pt = Point::new(5299619240641551281634865583518297030282874472190772894086521144482721001553, 16950150798460657717958625567821834550301663161624707787222815936182638968203); + + bjj.mul(priv_key,base_pt) +} +``` + +This would come in handy in a Merkle proof. + +- EdDSA signature verification: This is a matter of combining these primitives with a suitable hash + function. See + [feat(stdlib): EdDSA sig verification noir#1136](https://github.com/noir-lang/noir/pull/1136) for + the case of Baby Jubjub and the Poseidon hash function. diff --git a/docs/versioned_docs/version-0.17.0/standard_library/cryptographic_primitives/05_eddsa.mdx b/docs/versioned_docs/version-0.17.0/standard_library/cryptographic_primitives/05_eddsa.mdx new file mode 100644 index 00000000000..9a5beb55ee9 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/standard_library/cryptographic_primitives/05_eddsa.mdx @@ -0,0 +1,17 @@ +--- +title: EdDSA Verification +description: Learn about the cryptographic primitives regarding EdDSA +keywords: [cryptographic primitives, Noir project, eddsa, signatures] +--- + +import BlackBoxInfo from '@site/src/components/Notes/_blackbox.mdx'; + +## eddsa::eddsa_poseidon_verify + +Verifier for EdDSA signatures + +```rust +fn eddsa_poseidon_verify(public_key_x : Field, public_key_y : Field, signature_s: Field, signature_r8_x: Field, signature_r8_y: Field, message: Field) -> bool +``` + + diff --git a/docs/versioned_docs/version-0.17.0/standard_library/logging.md b/docs/versioned_docs/version-0.17.0/standard_library/logging.md new file mode 100644 index 00000000000..7e2fd9b9aff --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/standard_library/logging.md @@ -0,0 +1,62 @@ +--- +title: Logging +description: + Learn how to use the println statement for debugging in Noir with this tutorial. Understand the + basics of logging in Noir and how to implement it in your code. +keywords: + [ + noir logging, + println statement, + debugging in noir, + noir std library, + logging tutorial, + basic logging in noir, + noir logging implementation, + noir debugging techniques, + rust, + ] +--- + +The standard library provides a familiar `println` statement you can use. Despite being a limited +implementation of rust's `println!` macro, this construct can be useful for debugging. + +You can print the output of println statements in your Noir code by using the `nargo execute` command or the `--show-output` flag when using `nargo test` (provided there are println statements in your tests). + +It is recommended to use `nargo execute` if you want to debug failing constrains with `println` statements. This is due to every input in a test being a constant rather than a witness, so we issue an error during compilation while we only print during execution (which comes after compilation). `println` will not work for failed constraints caught at compile time. + +The `println` statement is unconstrained, so it works for outputting integers, fields, strings, and even structs or expressions. For example: + +```rust +use dep::std; + +struct Person { + age : Field, + height : Field, +} + +fn main(age : Field, height : Field) { + let person = Person { age : age, height : height }; + std::println(person); + std::println(age + height); + std::println("Hello world!"); +} + +``` + +You can print multiple different types in the same statement and string as well as a new "fmtstr" type. A `fmtstr` can be specified in the same way as a normal string it just should be prepended with an "f" character: + +```rust + let fmt_str = f"i: {i}, j: {j}"; + std::println(fmt_str); + + let s = myStruct { y: x, x: y }; + std::println(s); + + std::println(f"i: {i}, s: {s}"); + + std::println(x); + std::println([x, y]); + + let foo = fooStruct { my_struct: s, foo: 15 }; + std::println(f"s: {s}, foo: {foo}"); +``` diff --git a/docs/versioned_docs/version-0.17.0/standard_library/merkle_trees.md b/docs/versioned_docs/version-0.17.0/standard_library/merkle_trees.md new file mode 100644 index 00000000000..9761105f4f2 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/standard_library/merkle_trees.md @@ -0,0 +1,58 @@ +--- +title: Merkle Trees +description: Learn about Merkle Trees in Noir with this tutorial. Explore the basics of computing a merkle root using a proof, with examples. +keywords: + [ + Merkle trees in Noir, + Noir programming language, + check membership, + computing root from leaf, + Noir Merkle tree implementation, + Merkle tree tutorial, + Merkle tree code examples, + Noir libraries, + pedersen hash., + ] +--- + +## compute_merkle_root + +Returns the root of the tree from the provided leaf and its hash path, using a [Pedersen hash](cryptographic_primitives/00_hashes.mdx#pedersen). + +```rust +fn compute_merkle_root(leaf : Field, index : Field, hash_path: [Field]) -> Field +``` + +example: + +```rust +/** + // these values are for this example only + index = "0" + priv_key = "0x000000000000000000000000000000000000000000000000000000616c696365" + secret = "0x1929ea3ab8d9106a899386883d9428f8256cfedb3c4f6b66bf4aa4d28a79988f" + note_hash_path = [ + "0x1e61bdae0f027b1b2159e1f9d3f8d00fa668a952dddd822fda80dc745d6f65cc", + "0x0e4223f3925f98934393c74975142bd73079ab0621f4ee133cee050a3c194f1a", + "0x2fd7bb412155bf8693a3bd2a3e7581a679c95c68a052f835dddca85fa1569a40" + ] + */ +fn main(index: Field, priv_key: Field, secret: Field, note_hash_path: [Field; 3]) { + + let pubkey = std::scalar_mul::fixed_base_embedded_curve(priv_key); + let pubkey_x = pubkey[0]; + let pubkey_y = pubkey[1]; + let note_commitment = std::hash::pedersen([pubkey_x, pubkey_y, secret]); + + let root = std::merkle::compute_merkle_root(note_commitment[0], index, note_hash_path); + std::println(root); +} +``` + +To check merkle tree membership: + +1. Include a merkle root as a program input. +2. Compute the merkle root of a given leaf, index and hash path. +3. Assert the merkle roots are equal. + +For more info about merkle trees, see the Wikipedia [page](https://en.wikipedia.org/wiki/Merkle_tree). diff --git a/docs/versioned_docs/version-0.17.0/standard_library/options.md b/docs/versioned_docs/version-0.17.0/standard_library/options.md new file mode 100644 index 00000000000..3d3139fb98b --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/standard_library/options.md @@ -0,0 +1,99 @@ +--- +title: Option Type +--- + +The `Option` type is a way to express that a value might be present (`Some(T))` or absent (`None`). It's a safer way to handle potential absence of values, compared to using nulls in many other languages. + +```rust +struct Option { + None, + Some(T), +} +``` + +You can import the Option type into your Noir program like so: + +```rust +use dep::std::option::Option; + +fn main() { + let none = Option::none(); + let some = Option::some(3); +} +``` + +See [this test](https://github.com/noir-lang/noir/blob/5cbfb9c4a06c8865c98ff2b594464b037d821a5c/crates/nargo_cli/tests/test_data/option/src/main.nr) for a more comprehensive set of examples of each of the methods described below. + +## Methods + +### none + +Constructs a none value. + +### some + +Constructs a some wrapper around a given value. + +### is_none + +Returns true if the Option is None. + +### is_some + +Returns true of the Option is Some. + +### unwrap + +Asserts `self.is_some()` and returns the wrapped value. + +### unwrap_unchecked + +Returns the inner value without asserting `self.is_some()`. This method can be useful within an if condition when we already know that `option.is_some()`. If the option is None, there is no guarantee what value will be returned, only that it will be of type T for an `Option`. + +### unwrap_or + +Returns the wrapped value if `self.is_some()`. Otherwise, returns the given default value. + +### unwrap_or_else + +Returns the wrapped value if `self.is_some()`. Otherwise, calls the given function to return a default value. + +### map + +If self is `Some(x)`, this returns `Some(f(x))`. Otherwise, this returns `None`. + +### map_or + +If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns the given default value. + +### map_or_else + +If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns `default()`. + +### and + +Returns None if self is None. Otherwise, this returns `other`. + +### and_then + +If self is None, this returns None. Otherwise, this calls the given function with the Some value contained within self, and returns the result of that call. In some languages this function is called `flat_map` or `bind`. + +### or + +If self is Some, return self. Otherwise, return `other`. + +### or_else + +If self is Some, return self. Otherwise, return `default()`. + +### xor + +If only one of the two Options is Some, return that option. Otherwise, if both options are Some or both are None, None is returned. + +### filter + +Returns `Some(x)` if self is `Some(x)` and `predicate(x)` is true. Otherwise, this returns `None`. + +### flatten + +Flattens an `Option>` into a `Option`. This returns `None` if the outer Option is None. Otherwise, this returns the inner Option. diff --git a/docs/versioned_docs/version-0.17.0/standard_library/recursion.md b/docs/versioned_docs/version-0.17.0/standard_library/recursion.md new file mode 100644 index 00000000000..ff4c63acaa7 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/standard_library/recursion.md @@ -0,0 +1,96 @@ +--- +title: Recursive Proofs +description: Learn about how to write recursive proofs in Noir. +keywords: [recursion, recursive proofs, verification_key, aggregation object, verify_proof] +--- + +Noir supports recursively verifying proofs, meaning you verify the proof of a Noir program in another Noir program. This enables creating proofs of arbitrary size by doing step-wise verification of smaller components of a large proof. + +The `verify_proof` function takes a verification key, proof and public inputs for a zk program, as well as a key hash and an input aggregation object. The key hash is used to check the validity of the verification key and the input aggregation object is required by some proving systems. The `verify_proof` function returns an output aggregation object that can then be fed into future iterations of the proof verification if required. + +```rust +#[foreign(verify_proof)] +fn verify_proof(_verification_key : [Field], _proof : [Field], _public_input : Field, _key_hash : Field, _input_aggregation_object : [Field]) -> [Field] {} +``` + +:::info + +This is a black box function. Read [this section](./black_box_fns) to learn more about black box functions in Noir. + +::: + +## Aggregation Object + +The purpose of the input aggregation object is a little less clear though (and the output aggregation object that is returned from the `std::verify_proof` method). Recursive zkSNARK schemes do not necessarily "verify a proof" in the sense that you expect a true or false to be spit out by the verifier. Rather an aggregation object is built over the public inputs. In the case of PLONK the recursive aggregation object is two G1 points (expressed as 16 witness values). The final verifier (in our case this is most often the smart contract verifier) has to be aware of this aggregation object to execute a pairing and check the validity of these points (thus completing the recursive verification). + +So for example in this circuit: + +```rust +use dep::std; + +fn main( + verification_key : [Field; 114], + proof : [Field; 94], + public_inputs : [Field; 1], + key_hash : Field, + input_aggregation_object : [Field; 16], + proof_b : [Field; 94], +) -> pub [Field; 16] { + let output_aggregation_object_a = std::verify_proof( + verification_key, + proof, + public_inputs, + key_hash, + input_aggregation_object + ); + + let output_aggregation_object = std::verify_proof( + verification_key, + proof_b, + public_inputs, + key_hash, + output_aggregation_object_a + ); + + let mut output = [0; 16]; + for i in 0..16 { + output[i] = output_aggregation_object[i]; + } + output +} +``` + +In this example we have a circuit, that generates proofs A and B, that is being verified in circuit C. Assuming that the proof being passed in is not already a recursive proof, the `input_aggregation_object` will be all zeros. It will then generate an `output_aggregation_object`. This blob of data then becomes the `input_aggregation_object` of the next recursive aggregation we wish to compute. We can see here as the same public inputs, verification key, and key hash are used that we are verifying two proofs generated from the same circuit in this single circuit. `std::verify_proof` returns a `[Field]` because the size of an aggregation object is proof system dependent--in barretenberg, aggregation objects are two G1 points, while in Halo2, the aggregation object is a list of G1 points that is log the circuit size. So for the final step we convert the slice into an array of size 16 because we are generating proofs using UltraPlonk. + +## Parameters + +### `verification_key` + +The verification key for the zk program that is being verified. + +### `proof` + +The proof for the zk program that is being verified. + +### `public_inputs` + +These represent the public inputs of the proof we are verifying. They should be checked against in the circuit after construction of a new aggregation state. + +### `key_hash` + +A key hash is used to check the validity of the verification key. The circuit implementing this opcode can use this hash to ensure that the key provided to the circuit matches the key produced by the circuit creator. + +### `input_aggregation_object` + +An aggregation object is blob of data that the top-level verifier must run some proof system specific algorithm on to complete verification. The size is proof system specific and will be set by the backend integrating this opcode. The input aggregation object is only not `None` when we are verifying a previous recursive aggregation in the current circuit. If this is the first recursive aggregation there is no input aggregation object. It is left to the backend to determine how to handle when there is no input aggregation object. + +## Return value + +### `output_aggregation_object` + +This is the result of a recursive aggregation and is what will be fed into the next verifier. +The next verifier can either perform a final verification (returning true or false) or perform another recursive aggregation where this output aggregation object will be the input aggregation object of the next recursive aggregation. + +## Example + +You can see an example of how to do recursive proofs in [this example recursion demo repo](https://github.com/noir-lang/noir-examples/tree/master/recursion). diff --git a/docs/versioned_docs/version-0.17.0/standard_library/zeroed.md b/docs/versioned_docs/version-0.17.0/standard_library/zeroed.md new file mode 100644 index 00000000000..97dab02dac2 --- /dev/null +++ b/docs/versioned_docs/version-0.17.0/standard_library/zeroed.md @@ -0,0 +1,25 @@ +--- +title: Zeroed Function +description: + The zeroed function returns a zeroed value of any type. +keywords: + [ + zeroed + ] +--- + +Implements `fn zeroed() -> T` to return a zeroed value of any type. This function is generally unsafe to use as the zeroed bit pattern is not guaranteed to be valid for all types. It can however, be useful in cases when the value is guaranteed not to be used such as in a BoundedVec library implementing a growable vector, up to a certain length, backed by an array. The array can be initialized with zeroed values which are guaranteed to be inaccessible until the vector is pushed to. Similarly, enumerations in noir can be implemented using this method by providing zeroed values for the unused variants. + +You can access the function at `std::unsafe::zeroed`. + +This function currently supports the following types: + +- Field +- Bool +- Uint +- Array +- String +- Tuple +- Function + +Using it on other types could result in unexpected behavior. diff --git a/docs/versioned_sidebars/version-0.17.0-sidebars.json b/docs/versioned_sidebars/version-0.17.0-sidebars.json new file mode 100644 index 00000000000..a9ec39925d9 --- /dev/null +++ b/docs/versioned_sidebars/version-0.17.0-sidebars.json @@ -0,0 +1,141 @@ +{ + "sidebar": [ + { + "type": "doc", + "id": "index", + "label": "Noir" + }, + { + "type": "category", + "label": "Getting Started", + "items": [ + { + "type": "autogenerated", + "dirName": "getting_started" + } + ] + }, + { + "type": "category", + "label": "Examples", + "items": [ + { + "type": "autogenerated", + "dirName": "examples" + } + ] + }, + { + "type": "category", + "label": "Nargo", + "items": [ + { + "type": "autogenerated", + "dirName": "nargo" + } + ] + }, + { + "type": "category", + "label": "Language Concepts", + "items": [ + { + "type": "category", + "label": "Data Types", + "link": { + "type": "doc", + "id": "language_concepts/data_types" + }, + "items": [ + { + "type": "autogenerated", + "dirName": "language_concepts/data_types" + } + ] + }, + "language_concepts/functions", + "language_concepts/control_flow", + "language_concepts/ops", + "language_concepts/assert", + "language_concepts/unconstrained", + "language_concepts/generics", + "language_concepts/mutability", + "language_concepts/lambdas", + "language_concepts/comments", + "language_concepts/distinct", + "language_concepts/shadowing" + ] + }, + { + "type": "category", + "label": "Noir Standard Library", + "items": [ + { + "type": "category", + "label": "Cryptographic Primitives", + "link": { + "type": "doc", + "id": "standard_library/cryptographic_primitives" + }, + "items": [ + { + "type": "autogenerated", + "dirName": "standard_library/cryptographic_primitives" + } + ] + }, + "standard_library/recursion", + "standard_library/logging", + "standard_library/merkle_trees", + "standard_library/zeroed", + "standard_library/black_box_fns", + "standard_library/options" + ] + }, + { + "type": "category", + "label": "Modules, Packages and Crates", + "items": [ + { + "type": "autogenerated", + "dirName": "modules_packages_crates" + } + ] + }, + { + "type": "category", + "label": "NoirJS", + "link": { + "type": "doc", + "id": "noir_js/noir_js" + }, + "items": [ + { + "type": "category", + "label": "Guides", + "items": [ + { + "type": "autogenerated", + "dirName": "noir_js/getting_started" + } + ] + }, + { + "type": "category", + "label": "Reference", + "items": [ + { + "type": "autogenerated", + "dirName": "noir_js/reference" + } + ] + } + ] + }, + { + "type": "doc", + "id": "migration_notes", + "label": "Migration notes" + } + ] +} diff --git a/docs/versions.json b/docs/versions.json index 26d22536e02..e1a95eeb06d 100644 --- a/docs/versions.json +++ b/docs/versions.json @@ -1,6 +1,4 @@ [ - "0.10.5", - "0.9.0", - "0.7.1", - "0.6.0" -] + "0.17.0", + "0.10.5" +] \ No newline at end of file diff --git a/flake.nix b/flake.nix index 1a52fcc639e..5b482d4c869 100644 --- a/flake.nix +++ b/flake.nix @@ -44,7 +44,7 @@ rustToolchain = fenix.packages.${system}.fromToolchainFile { file = ./rust-toolchain.toml; - sha256 = "sha256-riZUc+R9V35c/9e8KJUE+8pzpXyl0lRXt3ZkKlxoY0g="; + sha256 = "sha256-R0F0Risbr74xg9mEYydyebx/z0Wu6HI0/KWwrV30vZo="; }; craneLib = (crane.mkLib pkgs).overrideToolchain rustToolchain; diff --git a/noir_stdlib/Nargo.toml b/noir_stdlib/Nargo.toml index 9b7a79ad2a6..d2f8ebcb636 100644 --- a/noir_stdlib/Nargo.toml +++ b/noir_stdlib/Nargo.toml @@ -2,6 +2,4 @@ name = "std" type = "lib" authors = [""] -compiler_version = "0.1" - [dependencies] diff --git a/noir_stdlib/src/ec/consts/te.nr b/noir_stdlib/src/ec/consts/te.nr index b5847e77f34..1159ac558b0 100644 --- a/noir_stdlib/src/ec/consts/te.nr +++ b/noir_stdlib/src/ec/consts/te.nr @@ -8,9 +8,8 @@ struct BabyJubjub { suborder: Field, } +#[field(bn254)] pub fn baby_jubjub() -> BabyJubjub { - assert(compat::is_bn254()); - BabyJubjub { // Baby Jubjub (ERC-2494) parameters in affine representation curve: TECurve::new( diff --git a/noir_stdlib/src/eddsa.nr b/noir_stdlib/src/eddsa.nr index ff8c1da1397..31fac549fc5 100644 --- a/noir_stdlib/src/eddsa.nr +++ b/noir_stdlib/src/eddsa.nr @@ -33,7 +33,6 @@ pub fn eddsa_poseidon_verify( ) -> bool { // Verifies by testing: // S * B8 = R8 + H(R8, A, m) * A8 - let bjj = baby_jubjub(); let pub_key = TEPoint::new(pub_key_x, pub_key_y); @@ -46,13 +45,7 @@ pub fn eddsa_poseidon_verify( assert(lt_bytes32(signature_s, bjj.suborder)); // Calculate the h = H(R, A, msg) - let hash: Field = poseidon::bn254::hash_5([ - signature_r8_x, - signature_r8_y, - pub_key_x, - pub_key_y, - message, - ]); + let hash: Field = poseidon::bn254::hash_5([signature_r8_x, signature_r8_y, pub_key_x, pub_key_y, message]); // Calculate second part of the right side: right2 = h*8*A diff --git a/noir_stdlib/src/field.nr b/noir_stdlib/src/field.nr index 3959f1ea175..0c6e282f449 100644 --- a/noir_stdlib/src/field.nr +++ b/noir_stdlib/src/field.nr @@ -82,3 +82,20 @@ pub fn modulus_be_bytes() -> [u8] {} #[builtin(modulus_le_bytes)] pub fn modulus_le_bytes() -> [u8] {} + +// Convert a 32 byte array to a field element +pub fn bytes32_to_field(bytes32 : [u8; 32]) -> Field { + // Convert it to a field element + let mut v = 1; + let mut high = 0 as Field; + let mut low = 0 as Field; + + for i in 0..16 { + high = high + (bytes32[15 - i] as Field) * v; + low = low + (bytes32[16 + 15 - i] as Field) * v; + v = v * 256; + } + + // Abuse that a % p + b % p = (a + b) % p and that low < p + low + high * v +} \ No newline at end of file diff --git a/noir_stdlib/src/hash.nr b/noir_stdlib/src/hash.nr index fb79038a06c..f6a468048a0 100644 --- a/noir_stdlib/src/hash.nr +++ b/noir_stdlib/src/hash.nr @@ -1,4 +1,5 @@ mod poseidon; +mod mimc; #[foreign(sha256)] pub fn sha256(_input : [u8; N]) -> [u8; 32] {} @@ -6,12 +7,25 @@ pub fn sha256(_input : [u8; N]) -> [u8; 32] {} #[foreign(blake2s)] pub fn blake2s(_input : [u8; N]) -> [u8; 32] {} -pub fn pedersen(input : [Field; N]) -> [Field; 2] { - pedersen_with_separator(input, 0) +struct PedersenPoint { + x : Field, + y : Field, +} + +pub fn pedersen_commitment(input : [Field; N]) -> PedersenPoint { + pedersen_commitment_with_separator(input, 0) } #[foreign(pedersen)] -pub fn pedersen_with_separator(_input : [Field; N], _separator : u32) -> [Field; 2] {} +pub fn __pedersen_commitment_with_separator(_input : [Field; N], _separator : u32) -> [Field; 2] {} + +pub fn pedersen_commitment_with_separator(input : [Field; N], separator : u32) -> PedersenPoint { + let values = __pedersen_commitment_with_separator(input, separator); + PedersenPoint { + x: values[0], + y: values[1], + } +} pub fn pedersen_hash(input : [Field; N]) -> Field { pedersen_hash_with_separator(input, 0) @@ -20,134 +34,20 @@ pub fn pedersen_hash(input : [Field; N]) -> Field { #[foreign(pedersen_hash)] pub fn pedersen_hash_with_separator(_input : [Field; N], _separator : u32) -> Field {} -#[foreign(hash_to_field_128_security)] -pub fn hash_to_field(_input : [Field; N]) -> Field {} - -#[foreign(keccak256)] -pub fn keccak256(_input : [u8; N], _message_size: u32) -> [u8; 32] {} +pub fn hash_to_field(_input : [Field; N]) -> Field { + let mut inputs_as_bytes = []; + + for i in 0..N { + let input_bytes = _input[i].to_le_bytes(32); + for i in 0..32 { + inputs_as_bytes = inputs_as_bytes.push_back(input_bytes[i]); + } + } -// mimc-p/p implementation -// constants are (publicly generated) random numbers, for instance using keccak as a ROM. -// You must use constants generated for the native field -// Rounds number should be ~ log(p)/log(exp) -// For 254 bit primes, exponent 7 and 91 rounds seems to be recommended -fn mimc(x: Field, k: Field, constants: [Field; N], exp : Field) -> Field { - //round 0 - let mut t = x + k; - let mut h = t.pow_32(exp); - //next rounds - for i in 1 .. constants.len() { - t = h + k + constants[i]; - h = t.pow_32(exp); - }; - h + k + let hashed_input = blake2s(inputs_as_bytes); + crate::field::bytes32_to_field(hashed_input) } -global MIMC_BN254_ROUNDS = 91; - -//mimc implementation with hardcoded parameters for BN254 curve. -pub fn mimc_bn254(array: [Field; N]) -> Field { - //mimc parameters - let exponent = 7; - //generated from seed "mimc" using keccak256 - let constants: [Field; MIMC_BN254_ROUNDS] = [ - 0, - 20888961410941983456478427210666206549300505294776164667214940546594746570981, - 15265126113435022738560151911929040668591755459209400716467504685752745317193, - 8334177627492981984476504167502758309043212251641796197711684499645635709656, - 1374324219480165500871639364801692115397519265181803854177629327624133579404, - 11442588683664344394633565859260176446561886575962616332903193988751292992472, - 2558901189096558760448896669327086721003508630712968559048179091037845349145, - 11189978595292752354820141775598510151189959177917284797737745690127318076389, - 3262966573163560839685415914157855077211340576201936620532175028036746741754, - 17029914891543225301403832095880481731551830725367286980611178737703889171730, - 4614037031668406927330683909387957156531244689520944789503628527855167665518, - 19647356996769918391113967168615123299113119185942498194367262335168397100658, - 5040699236106090655289931820723926657076483236860546282406111821875672148900, - 2632385916954580941368956176626336146806721642583847728103570779270161510514, - 17691411851977575435597871505860208507285462834710151833948561098560743654671, - 11482807709115676646560379017491661435505951727793345550942389701970904563183, - 8360838254132998143349158726141014535383109403565779450210746881879715734773, - 12663821244032248511491386323242575231591777785787269938928497649288048289525, - 3067001377342968891237590775929219083706800062321980129409398033259904188058, - 8536471869378957766675292398190944925664113548202769136103887479787957959589, - 19825444354178182240559170937204690272111734703605805530888940813160705385792, - 16703465144013840124940690347975638755097486902749048533167980887413919317592, - 13061236261277650370863439564453267964462486225679643020432589226741411380501, - 10864774797625152707517901967943775867717907803542223029967000416969007792571, - 10035653564014594269791753415727486340557376923045841607746250017541686319774, - 3446968588058668564420958894889124905706353937375068998436129414772610003289, - 4653317306466493184743870159523234588955994456998076243468148492375236846006, - 8486711143589723036499933521576871883500223198263343024003617825616410932026, - 250710584458582618659378487568129931785810765264752039738223488321597070280, - 2104159799604932521291371026105311735948154964200596636974609406977292675173, - 16313562605837709339799839901240652934758303521543693857533755376563489378839, - 6032365105133504724925793806318578936233045029919447519826248813478479197288, - 14025118133847866722315446277964222215118620050302054655768867040006542798474, - 7400123822125662712777833064081316757896757785777291653271747396958201309118, - 1744432620323851751204287974553233986555641872755053103823939564833813704825, - 8316378125659383262515151597439205374263247719876250938893842106722210729522, - 6739722627047123650704294650168547689199576889424317598327664349670094847386, - 21211457866117465531949733809706514799713333930924902519246949506964470524162, - 13718112532745211817410303291774369209520657938741992779396229864894885156527, - 5264534817993325015357427094323255342713527811596856940387954546330728068658, - 18884137497114307927425084003812022333609937761793387700010402412840002189451, - 5148596049900083984813839872929010525572543381981952060869301611018636120248, - 19799686398774806587970184652860783461860993790013219899147141137827718662674, - 19240878651604412704364448729659032944342952609050243268894572835672205984837, - 10546185249390392695582524554167530669949955276893453512788278945742408153192, - 5507959600969845538113649209272736011390582494851145043668969080335346810411, - 18177751737739153338153217698774510185696788019377850245260475034576050820091, - 19603444733183990109492724100282114612026332366576932662794133334264283907557, - 10548274686824425401349248282213580046351514091431715597441736281987273193140, - 1823201861560942974198127384034483127920205835821334101215923769688644479957, - 11867589662193422187545516240823411225342068709600734253659804646934346124945, - 18718569356736340558616379408444812528964066420519677106145092918482774343613, - 10530777752259630125564678480897857853807637120039176813174150229243735996839, - 20486583726592018813337145844457018474256372770211860618687961310422228379031, - 12690713110714036569415168795200156516217175005650145422920562694422306200486, - 17386427286863519095301372413760745749282643730629659997153085139065756667205, - 2216432659854733047132347621569505613620980842043977268828076165669557467682, - 6309765381643925252238633914530877025934201680691496500372265330505506717193, - 20806323192073945401862788605803131761175139076694468214027227878952047793390, - 4037040458505567977365391535756875199663510397600316887746139396052445718861, - 19948974083684238245321361840704327952464170097132407924861169241740046562673, - 845322671528508199439318170916419179535949348988022948153107378280175750024, - 16222384601744433420585982239113457177459602187868460608565289920306145389382, - 10232118865851112229330353999139005145127746617219324244541194256766741433339, - 6699067738555349409504843460654299019000594109597429103342076743347235369120, - 6220784880752427143725783746407285094967584864656399181815603544365010379208, - 6129250029437675212264306655559561251995722990149771051304736001195288083309, - 10773245783118750721454994239248013870822765715268323522295722350908043393604, - 4490242021765793917495398271905043433053432245571325177153467194570741607167, - 19596995117319480189066041930051006586888908165330319666010398892494684778526, - 837850695495734270707668553360118467905109360511302468085569220634750561083, - 11803922811376367215191737026157445294481406304781326649717082177394185903907, - 10201298324909697255105265958780781450978049256931478989759448189112393506592, - 13564695482314888817576351063608519127702411536552857463682060761575100923924, - 9262808208636973454201420823766139682381973240743541030659775288508921362724, - 173271062536305557219323722062711383294158572562695717740068656098441040230, - 18120430890549410286417591505529104700901943324772175772035648111937818237369, - 20484495168135072493552514219686101965206843697794133766912991150184337935627, - 19155651295705203459475805213866664350848604323501251939850063308319753686505, - 11971299749478202793661982361798418342615500543489781306376058267926437157297, - 18285310723116790056148596536349375622245669010373674803854111592441823052978, - 7069216248902547653615508023941692395371990416048967468982099270925308100727, - 6465151453746412132599596984628739550147379072443683076388208843341824127379, - 16143532858389170960690347742477978826830511669766530042104134302796355145785, - 19362583304414853660976404410208489566967618125972377176980367224623492419647, - 1702213613534733786921602839210290505213503664731919006932367875629005980493, - 10781825404476535814285389902565833897646945212027592373510689209734812292327, - 4212716923652881254737947578600828255798948993302968210248673545442808456151, - 7594017890037021425366623750593200398174488805473151513558919864633711506220, - 18979889247746272055963929241596362599320706910852082477600815822482192194401, - 13602139229813231349386885113156901793661719180900395818909719758150455500533, - ]; +#[foreign(keccak256)] +pub fn keccak256(_input : [u8; N], _message_size: u32) -> [u8; 32] {} - let mut r = 0; - for elem in array { - let h = mimc(elem, r, constants, exponent); - r = r + elem + h; - } - r -} diff --git a/noir_stdlib/src/hash/mimc.nr b/noir_stdlib/src/hash/mimc.nr new file mode 100644 index 00000000000..7f778df14c1 --- /dev/null +++ b/noir_stdlib/src/hash/mimc.nr @@ -0,0 +1,126 @@ +// mimc-p/p implementation +// constants are (publicly generated) random numbers, for instance using keccak as a ROM. +// You must use constants generated for the native field +// Rounds number should be ~ log(p)/log(exp) +// For 254 bit primes, exponent 7 and 91 rounds seems to be recommended +fn mimc(x: Field, k: Field, constants: [Field; N], exp : Field) -> Field { + //round 0 + let mut t = x + k; + let mut h = t.pow_32(exp); + //next rounds + for i in 1 .. constants.len() { + t = h + k + constants[i]; + h = t.pow_32(exp); + }; + h + k +} + +global MIMC_BN254_ROUNDS = 91; + +//mimc implementation with hardcoded parameters for BN254 curve. +#[field(bn254)] +pub fn mimc_bn254(array: [Field; N]) -> Field { + //mimc parameters + let exponent = 7; + //generated from seed "mimc" using keccak256 + let constants: [Field; MIMC_BN254_ROUNDS] = [ + 0, + 20888961410941983456478427210666206549300505294776164667214940546594746570981, + 15265126113435022738560151911929040668591755459209400716467504685752745317193, + 8334177627492981984476504167502758309043212251641796197711684499645635709656, + 1374324219480165500871639364801692115397519265181803854177629327624133579404, + 11442588683664344394633565859260176446561886575962616332903193988751292992472, + 2558901189096558760448896669327086721003508630712968559048179091037845349145, + 11189978595292752354820141775598510151189959177917284797737745690127318076389, + 3262966573163560839685415914157855077211340576201936620532175028036746741754, + 17029914891543225301403832095880481731551830725367286980611178737703889171730, + 4614037031668406927330683909387957156531244689520944789503628527855167665518, + 19647356996769918391113967168615123299113119185942498194367262335168397100658, + 5040699236106090655289931820723926657076483236860546282406111821875672148900, + 2632385916954580941368956176626336146806721642583847728103570779270161510514, + 17691411851977575435597871505860208507285462834710151833948561098560743654671, + 11482807709115676646560379017491661435505951727793345550942389701970904563183, + 8360838254132998143349158726141014535383109403565779450210746881879715734773, + 12663821244032248511491386323242575231591777785787269938928497649288048289525, + 3067001377342968891237590775929219083706800062321980129409398033259904188058, + 8536471869378957766675292398190944925664113548202769136103887479787957959589, + 19825444354178182240559170937204690272111734703605805530888940813160705385792, + 16703465144013840124940690347975638755097486902749048533167980887413919317592, + 13061236261277650370863439564453267964462486225679643020432589226741411380501, + 10864774797625152707517901967943775867717907803542223029967000416969007792571, + 10035653564014594269791753415727486340557376923045841607746250017541686319774, + 3446968588058668564420958894889124905706353937375068998436129414772610003289, + 4653317306466493184743870159523234588955994456998076243468148492375236846006, + 8486711143589723036499933521576871883500223198263343024003617825616410932026, + 250710584458582618659378487568129931785810765264752039738223488321597070280, + 2104159799604932521291371026105311735948154964200596636974609406977292675173, + 16313562605837709339799839901240652934758303521543693857533755376563489378839, + 6032365105133504724925793806318578936233045029919447519826248813478479197288, + 14025118133847866722315446277964222215118620050302054655768867040006542798474, + 7400123822125662712777833064081316757896757785777291653271747396958201309118, + 1744432620323851751204287974553233986555641872755053103823939564833813704825, + 8316378125659383262515151597439205374263247719876250938893842106722210729522, + 6739722627047123650704294650168547689199576889424317598327664349670094847386, + 21211457866117465531949733809706514799713333930924902519246949506964470524162, + 13718112532745211817410303291774369209520657938741992779396229864894885156527, + 5264534817993325015357427094323255342713527811596856940387954546330728068658, + 18884137497114307927425084003812022333609937761793387700010402412840002189451, + 5148596049900083984813839872929010525572543381981952060869301611018636120248, + 19799686398774806587970184652860783461860993790013219899147141137827718662674, + 19240878651604412704364448729659032944342952609050243268894572835672205984837, + 10546185249390392695582524554167530669949955276893453512788278945742408153192, + 5507959600969845538113649209272736011390582494851145043668969080335346810411, + 18177751737739153338153217698774510185696788019377850245260475034576050820091, + 19603444733183990109492724100282114612026332366576932662794133334264283907557, + 10548274686824425401349248282213580046351514091431715597441736281987273193140, + 1823201861560942974198127384034483127920205835821334101215923769688644479957, + 11867589662193422187545516240823411225342068709600734253659804646934346124945, + 18718569356736340558616379408444812528964066420519677106145092918482774343613, + 10530777752259630125564678480897857853807637120039176813174150229243735996839, + 20486583726592018813337145844457018474256372770211860618687961310422228379031, + 12690713110714036569415168795200156516217175005650145422920562694422306200486, + 17386427286863519095301372413760745749282643730629659997153085139065756667205, + 2216432659854733047132347621569505613620980842043977268828076165669557467682, + 6309765381643925252238633914530877025934201680691496500372265330505506717193, + 20806323192073945401862788605803131761175139076694468214027227878952047793390, + 4037040458505567977365391535756875199663510397600316887746139396052445718861, + 19948974083684238245321361840704327952464170097132407924861169241740046562673, + 845322671528508199439318170916419179535949348988022948153107378280175750024, + 16222384601744433420585982239113457177459602187868460608565289920306145389382, + 10232118865851112229330353999139005145127746617219324244541194256766741433339, + 6699067738555349409504843460654299019000594109597429103342076743347235369120, + 6220784880752427143725783746407285094967584864656399181815603544365010379208, + 6129250029437675212264306655559561251995722990149771051304736001195288083309, + 10773245783118750721454994239248013870822765715268323522295722350908043393604, + 4490242021765793917495398271905043433053432245571325177153467194570741607167, + 19596995117319480189066041930051006586888908165330319666010398892494684778526, + 837850695495734270707668553360118467905109360511302468085569220634750561083, + 11803922811376367215191737026157445294481406304781326649717082177394185903907, + 10201298324909697255105265958780781450978049256931478989759448189112393506592, + 13564695482314888817576351063608519127702411536552857463682060761575100923924, + 9262808208636973454201420823766139682381973240743541030659775288508921362724, + 173271062536305557219323722062711383294158572562695717740068656098441040230, + 18120430890549410286417591505529104700901943324772175772035648111937818237369, + 20484495168135072493552514219686101965206843697794133766912991150184337935627, + 19155651295705203459475805213866664350848604323501251939850063308319753686505, + 11971299749478202793661982361798418342615500543489781306376058267926437157297, + 18285310723116790056148596536349375622245669010373674803854111592441823052978, + 7069216248902547653615508023941692395371990416048967468982099270925308100727, + 6465151453746412132599596984628739550147379072443683076388208843341824127379, + 16143532858389170960690347742477978826830511669766530042104134302796355145785, + 19362583304414853660976404410208489566967618125972377176980367224623492419647, + 1702213613534733786921602839210290505213503664731919006932367875629005980493, + 10781825404476535814285389902565833897646945212027592373510689209734812292327, + 4212716923652881254737947578600828255798948993302968210248673545442808456151, + 7594017890037021425366623750593200398174488805473151513558919864633711506220, + 18979889247746272055963929241596362599320706910852082477600815822482192194401, + 13602139229813231349386885113156901793661719180900395818909719758150455500533, + ]; + + let mut r = 0; + for elem in array { + let h = mimc(elem, r, constants, exponent); + r = r + elem + h; + } + r +} diff --git a/noir_stdlib/src/hash/poseidon/bn254.nr b/noir_stdlib/src/hash/poseidon/bn254.nr index fadf45138ab..f93ff577c97 100644 --- a/noir_stdlib/src/hash/poseidon/bn254.nr +++ b/noir_stdlib/src/hash/poseidon/bn254.nr @@ -7,6 +7,7 @@ use crate::hash::poseidon::apply_matrix; // Optimised permutation for this particular field; uses hardcoded rf and rp values, // which should agree with those in pos_conf. +#[field(bn254)] pub fn permute( pos_conf: PoseidonConfig, mut state: [Field; O]) @@ -65,6 +66,7 @@ pub fn permute( } // Corresponding absorption. +#[field(bn254)] fn absorb( pos_conf: PoseidonConfig, mut state: [Field; O], // Initial state; usually [0; O] @@ -98,6 +100,7 @@ fn absorb( } // Variable-length Poseidon-128 sponge as suggested in second bullet point of §3 of https://eprint.iacr.org/2019/458.pdf +#[field(bn254)] pub fn sponge(msg: [Field; N]) -> Field { absorb(consts::x5_5_config(), [0;5], 4, 1, msg)[1] } diff --git a/noir_stdlib/src/hash/poseidon/bn254/perm.nr b/noir_stdlib/src/hash/poseidon/bn254/perm.nr index 8b2f93c2d92..890f54fdb3f 100644 --- a/noir_stdlib/src/hash/poseidon/bn254/perm.nr +++ b/noir_stdlib/src/hash/poseidon/bn254/perm.nr @@ -3,6 +3,7 @@ use crate::hash::poseidon::bn254::consts; use crate::hash::poseidon::bn254::permute; use crate::hash::poseidon::PoseidonConfig; +#[field(bn254)] pub fn x5_2(mut state: [Field; 2]) -> [Field; 2] { state = permute( consts::x5_2_config(), @@ -11,6 +12,7 @@ pub fn x5_2(mut state: [Field; 2]) -> [Field; 2] { state } +#[field(bn254)] pub fn x5_3(mut state: [Field; 3]) -> [Field; 3] { state = permute( consts::x5_3_config(), @@ -19,6 +21,7 @@ pub fn x5_3(mut state: [Field; 3]) -> [Field; 3] { state } +#[field(bn254)] pub fn x5_4(mut state: [Field; 4]) -> [Field; 4] { state = permute( consts::x5_4_config(), @@ -27,6 +30,7 @@ pub fn x5_4(mut state: [Field; 4]) -> [Field; 4] { state } +#[field(bn254)] pub fn x5_5(mut state: [Field; 5]) -> [Field; 5] { state = permute( consts::x5_5_config(), @@ -35,6 +39,7 @@ pub fn x5_5(mut state: [Field; 5]) -> [Field; 5] { state } +#[field(bn254)] pub fn x5_6(mut state: [Field; 6]) -> [Field; 6] { state = permute( consts::x5_6_config(), @@ -43,6 +48,7 @@ pub fn x5_6(mut state: [Field; 6]) -> [Field; 6] { state } +#[field(bn254)] pub fn x5_7(mut state: [Field; 7]) -> [Field; 7] { state = permute( consts::x5_7_config(), @@ -51,6 +57,7 @@ pub fn x5_7(mut state: [Field; 7]) -> [Field; 7] { state } +#[field(bn254)] pub fn x5_8(mut state: [Field; 8]) -> [Field; 8] { state = permute( consts::x5_8_config(), @@ -59,6 +66,7 @@ pub fn x5_8(mut state: [Field; 8]) -> [Field; 8] { state } +#[field(bn254)] pub fn x5_9(mut state: [Field; 9]) -> [Field; 9] { state = permute( consts::x5_9_config(), @@ -67,6 +75,7 @@ pub fn x5_9(mut state: [Field; 9]) -> [Field; 9] { state } +#[field(bn254)] pub fn x5_10(mut state: [Field; 10]) -> [Field; 10] { state = permute( consts::x5_10_config(), @@ -75,6 +84,7 @@ pub fn x5_10(mut state: [Field; 10]) -> [Field; 10] { state } +#[field(bn254)] pub fn x5_11(mut state: [Field; 11]) -> [Field; 11] { state = permute( consts::x5_11_config(), @@ -83,6 +93,7 @@ pub fn x5_11(mut state: [Field; 11]) -> [Field; 11] { state } +#[field(bn254)] pub fn x5_12(mut state: [Field; 12]) -> [Field; 12] { state = permute( consts::x5_12_config(), @@ -91,6 +102,7 @@ pub fn x5_12(mut state: [Field; 12]) -> [Field; 12] { state } +#[field(bn254)] pub fn x5_13(mut state: [Field; 13]) -> [Field; 13] { state = permute( consts::x5_13_config(), @@ -99,6 +111,7 @@ pub fn x5_13(mut state: [Field; 13]) -> [Field; 13] { state } +#[field(bn254)] pub fn x5_14(mut state: [Field; 14]) -> [Field; 14] { state = permute( consts::x5_14_config(), @@ -107,6 +120,7 @@ pub fn x5_14(mut state: [Field; 14]) -> [Field; 14] { state } +#[field(bn254)] pub fn x5_15(mut state: [Field; 15]) -> [Field; 15] { state = permute( consts::x5_15_config(), @@ -115,6 +129,7 @@ pub fn x5_15(mut state: [Field; 15]) -> [Field; 15] { state } +#[field(bn254)] pub fn x5_16(mut state: [Field; 16]) -> [Field; 16] { state = permute( consts::x5_16_config(), @@ -123,6 +138,7 @@ pub fn x5_16(mut state: [Field; 16]) -> [Field; 16] { state } +#[field(bn254)] pub fn x5_17(mut state: [Field; 17]) -> [Field; 17] { state = permute( consts::x5_17_config(), diff --git a/noir_stdlib/src/lib.nr b/noir_stdlib/src/lib.nr index 26cf7a225ee..e6b56d29542 100644 --- a/noir_stdlib/src/lib.nr +++ b/noir_stdlib/src/lib.nr @@ -60,6 +60,7 @@ pub fn wrapping_mul(x : T, y: T) -> T { crate::from_field(crate::as_field(x) * crate::as_field(y)) } -pub fn wrapping_shift_left(x : T, y: T) -> T { - crate::from_field(crate::as_field(x) * 2.pow_32(crate::as_field(y))) -} +/// Shift-left x by y bits +/// If the result overflow the bitsize; it does not fail and returns 0 instead +#[builtin(wrapping_shift_left)] +pub fn wrapping_shift_left(_x : T, _y: T) -> T {} diff --git a/noir_stdlib/src/merkle.nr b/noir_stdlib/src/merkle.nr index 0bad55f93f4..2dc9c9814b4 100644 --- a/noir_stdlib/src/merkle.nr +++ b/noir_stdlib/src/merkle.nr @@ -14,8 +14,7 @@ pub fn compute_merkle_root(leaf: Field, index: Field, hash_path: [Field; N]) } else { (current, hash_path[i]) }; - - current = crate::hash::pedersen([hash_left, hash_right])[0]; + current = crate::hash::pedersen_hash([hash_left, hash_right]); }; current } diff --git a/noir_stdlib/src/sha256.nr b/noir_stdlib/src/sha256.nr index d2afd21db8a..0c9f9a01be0 100644 --- a/noir_stdlib/src/sha256.nr +++ b/noir_stdlib/src/sha256.nr @@ -7,7 +7,7 @@ fn rotr32(a: u32, b: u32) -> u32 // 32-bit right rotation { // None of the bits overlap between `(a >> b)` and `(a << (32 - b))` // Addition is then equivalent to OR, with fewer constraints. - (a >> b) + (a << (32 - b)) + (a >> b) + (crate::wrapping_shift_left(a, 32 - b)) } fn ch(x: u32, y: u32, z: u32) -> u32 @@ -52,7 +52,10 @@ fn sha_w(msg: [u32; 16]) -> [u32; 64] // Expanded message blocks for j in 16..64 { - w[j] = sigma1(w[j-2]) + w[j-7] + sigma0(w[j-15]) + w[j-16]; + w[j] = crate::wrapping_add( + crate::wrapping_add(sigma1(w[j-2]), w[j-7]), + crate::wrapping_add(sigma0(w[j-15]), w[j-16]), + ); }; w @@ -68,17 +71,22 @@ fn sha_c(msg: [u32; 16], hash: [u32; 8]) -> [u32; 8] let w = sha_w(msg); for j in 0..64 { - let t1 = out_h[7] + bigma1(out_h[4]) + ch(out_h[4], out_h[5], out_h[6]) - + K[j] + w[j]; - let t2 = bigma0(out_h[0]) + maj(out_h[0], out_h[1], out_h[2]); + let t1 = crate::wrapping_add( + crate::wrapping_add( + crate::wrapping_add(out_h[7], bigma1(out_h[4])), + ch(out_h[4], out_h[5], out_h[6]) + ), + crate::wrapping_add(K[j], w[j]) + ); + let t2 = crate::wrapping_add(bigma0(out_h[0]), maj(out_h[0], out_h[1], out_h[2])); out_h[7] = out_h[6]; out_h[6] = out_h[5]; out_h[5] = out_h[4]; - out_h[4] = out_h[3] + t1; + out_h[4] = crate::wrapping_add(out_h[3], t1); out_h[3] = out_h[2]; out_h[2] = out_h[1]; out_h[1] = out_h[0]; - out_h[0] = t1 + t2; + out_h[0] = crate::wrapping_add(t1, t2); }; out_h @@ -94,12 +102,13 @@ fn msg_u8_to_u32(msg: [u8; 64]) -> [u32; 16] for j in 0..4 { msg32[15 - i] = (msg32[15 - i] << 8) + msg[64 - 4*(i + 1) + j] as u32; - }; - }; - + } + } + msg32 } + // SHA-256 hash function pub fn digest(msg: [u8; N]) -> [u8; 32] { let mut msg_block: [u8; 64] = [0; 64]; @@ -115,7 +124,7 @@ pub fn digest(msg: [u8; N]) -> [u8; 32] { if i == 64 { // Enough to hash block c = sha_c(msg_u8_to_u32(msg_block), h); for j in 0..8 { - h[j] = c[j] + h[j]; + h[j] = crate::wrapping_add(c[j], h[j]); } i = 0; @@ -141,7 +150,7 @@ pub fn digest(msg: [u8; N]) -> [u8; 32] { c = h; c = sha_c(msg_u8_to_u32(msg_block), c); for j in 0..8 { - h[j] += c[j]; + h[j] = crate::wrapping_add(h[j], c[j]); } i = 0; @@ -165,7 +174,7 @@ pub fn digest(msg: [u8; N]) -> [u8; 32] { c = h; c = sha_c(msg_u8_to_u32(msg_block), c); for j in 0..8 { - h[j] += c[j]; + h[j] = crate::wrapping_add(h[j], c[j]); } // Return final hash as byte array diff --git a/noir_stdlib/src/sha512.nr b/noir_stdlib/src/sha512.nr index c565b16c098..43e817b650d 100644 --- a/noir_stdlib/src/sha512.nr +++ b/noir_stdlib/src/sha512.nr @@ -7,7 +7,7 @@ fn rotr64(a: u64, b: u64) -> u64 // 64-bit right rotation { // None of the bits overlap between `(a >> b)` and `(a << (64 - b))` // Addition is then equivalent to OR, with fewer constraints. - (a >> b) + (a << (64 - b)) + (a >> b) + (crate::wrapping_shift_left(a, 64 - b)) } fn sha_ch(x: u64, y: u64, z: u64) -> u64 @@ -52,9 +52,11 @@ fn sha_w(msg: [u64; 16]) -> [u64; 80] // Expanded message blocks for j in 16..80 { - w[j] = sha_sigma1(w[j-2]) + w[j-7] + sha_sigma0(w[j-15]) + w[j-16]; + w[j] = crate::wrapping_add( + crate::wrapping_add(sha_sigma1(w[j-2]), w[j-7]), + crate::wrapping_add(sha_sigma0(w[j-15]), w[j-16]), + ); }; - w } @@ -67,17 +69,18 @@ fn sha_c(msg: [u64; 16], hash: [u64; 8]) -> [u64; 8] let w = sha_w(msg); for j in 0..80 { - let t1 = out_h[7] + sha_bigma1(out_h[4]) + sha_ch(out_h[4], out_h[5], out_h[6]) - + K[j] + w[j]; - let t2 = sha_bigma0(out_h[0]) + sha_maj(out_h[0], out_h[1], out_h[2]); + let out1 = crate::wrapping_add(out_h[7] , sha_bigma1(out_h[4])); + let out2 = crate::wrapping_add(out1, sha_ch(out_h[4], out_h[5], out_h[6])); + let t1 = crate::wrapping_add(crate::wrapping_add(out2, K[j]), w[j]); + let t2 = crate::wrapping_add( sha_bigma0(out_h[0]) , sha_maj(out_h[0], out_h[1], out_h[2])); out_h[7] = out_h[6]; out_h[6] = out_h[5]; out_h[5] = out_h[4]; - out_h[4] = out_h[3] + t1; + out_h[4] = crate::wrapping_add(out_h[3] , t1); out_h[3] = out_h[2]; out_h[2] = out_h[1]; out_h[1] = out_h[0]; - out_h[0] = t1 + t2; + out_h[0] = crate::wrapping_add(t1, t2); }; out_h @@ -115,7 +118,7 @@ pub fn digest(msg: [u8; N]) -> [u8; 64] if i == 128 { // Enough to hash block c = sha_c(msg_u8_to_u64(msg_block), h); for j in 0..8 { - h[j] += c[j]; + h[j] = crate::wrapping_add(h[j], c[j]); } i = 0; @@ -140,7 +143,7 @@ pub fn digest(msg: [u8; N]) -> [u8; 64] } c = sha_c(msg_u8_to_u64(msg_block), h); for j in 0..8 { - h[j] += c[j]; + h[j] = crate::wrapping_add(h[j], c[j]); } i = 0; @@ -163,7 +166,7 @@ pub fn digest(msg: [u8; N]) -> [u8; 64] // Hash final padded block c = sha_c(msg_u8_to_u64(msg_block), h); for j in 0..8 { - h[j] += c[j]; + h[j] = crate::wrapping_add(h[j], c[j]); } // Return final hash as byte array diff --git a/rust-toolchain.toml b/rust-toolchain.toml index c0185fffbfb..b6f7edc4bde 100644 --- a/rust-toolchain.toml +++ b/rust-toolchain.toml @@ -1,5 +1,5 @@ [toolchain] -channel = "1.67.0" +channel = "1.71.1" components = [ "rust-src" ] targets = [ "wasm32-unknown-unknown", "wasm32-wasi", "aarch64-apple-darwin" ] profile = "default" diff --git a/tooling/backend_interface/Cargo.toml b/tooling/backend_interface/Cargo.toml index 587dcf41005..14b1609dd4a 100644 --- a/tooling/backend_interface/Cargo.toml +++ b/tooling/backend_interface/Cargo.toml @@ -32,4 +32,4 @@ test-binary = "3.0.1" [build-dependencies] build-target = "0.4.0" -const_format = "0.2.30" +const_format.workspace = true diff --git a/tooling/backend_interface/src/proof_system.rs b/tooling/backend_interface/src/proof_system.rs index c4fc6e743e5..95da1462d4e 100644 --- a/tooling/backend_interface/src/proof_system.rs +++ b/tooling/backend_interface/src/proof_system.rs @@ -23,7 +23,7 @@ impl Backend { // Create a temporary file for the circuit let circuit_path = temp_directory.join("circuit").with_extension("bytecode"); - let serialized_circuit = serialize_circuit(circuit); + let serialized_circuit = Circuit::serialize_circuit(circuit); write_to_file(&serialized_circuit, &circuit_path); GatesCommand { crs_path: self.crs_directory(), bytecode_path: circuit_path } @@ -57,7 +57,7 @@ impl Backend { // Create a temporary file for the circuit // let bytecode_path = temp_directory.join("circuit").with_extension("bytecode"); - let serialized_circuit = serialize_circuit(circuit); + let serialized_circuit = Circuit::serialize_circuit(circuit); write_to_file(&serialized_circuit, &bytecode_path); // Create proof and store it in the specified path @@ -97,7 +97,7 @@ impl Backend { // Create a temporary file for the circuit let bytecode_path = temp_directory.join("circuit").with_extension("bytecode"); - let serialized_circuit = serialize_circuit(circuit); + let serialized_circuit = Circuit::serialize_circuit(circuit); write_to_file(&serialized_circuit, &bytecode_path); // Create the verification key and write it to the specified path @@ -130,7 +130,7 @@ impl Backend { // Create a temporary file for the circuit // let bytecode_path = temp_directory.join("circuit").with_extension("bytecode"); - let serialized_circuit = serialize_circuit(circuit); + let serialized_circuit = Circuit::serialize_circuit(circuit); write_to_file(&serialized_circuit, &bytecode_path); // Create the verification key and write it to the specified path @@ -174,11 +174,3 @@ pub(super) fn write_to_file(bytes: &[u8], path: &Path) -> String { Ok(_) => display.to_string(), } } - -// TODO: See nargo/src/artifacts/mod.rs -// TODO: This method should live in ACVM and be the default method for serializing/deserializing circuits -pub(super) fn serialize_circuit(circuit: &Circuit) -> Vec { - let mut circuit_bytes: Vec = Vec::new(); - circuit.write(&mut circuit_bytes).unwrap(); - circuit_bytes -} diff --git a/tooling/backend_interface/src/smart_contract.rs b/tooling/backend_interface/src/smart_contract.rs index 08f67e7b9bc..5dac57c4072 100644 --- a/tooling/backend_interface/src/smart_contract.rs +++ b/tooling/backend_interface/src/smart_contract.rs @@ -1,4 +1,4 @@ -use super::proof_system::{serialize_circuit, write_to_file}; +use super::proof_system::write_to_file; use crate::{ cli::{ContractCommand, WriteVkCommand}, Backend, BackendError, @@ -16,7 +16,7 @@ impl Backend { // Create a temporary file for the circuit let bytecode_path = temp_directory_path.join("circuit").with_extension("bytecode"); - let serialized_circuit = serialize_circuit(circuit); + let serialized_circuit = Circuit::serialize_circuit(circuit); write_to_file(&serialized_circuit, &bytecode_path); // Create the verification key and write it to the specified path diff --git a/tooling/bb_abstraction_leaks/Cargo.toml b/tooling/bb_abstraction_leaks/Cargo.toml index 86164ba11c3..972c78831a7 100644 --- a/tooling/bb_abstraction_leaks/Cargo.toml +++ b/tooling/bb_abstraction_leaks/Cargo.toml @@ -14,4 +14,4 @@ acvm.workspace = true [build-dependencies] build-target = "0.4.0" -const_format = "0.2.30" +const_format.workspace = true diff --git a/tooling/bb_abstraction_leaks/build.rs b/tooling/bb_abstraction_leaks/build.rs index 8d490416094..fe6861a80b8 100644 --- a/tooling/bb_abstraction_leaks/build.rs +++ b/tooling/bb_abstraction_leaks/build.rs @@ -10,7 +10,7 @@ use const_format::formatcp; const USERNAME: &str = "AztecProtocol"; const REPO: &str = "aztec-packages"; -const VERSION: &str = "0.11.1"; +const VERSION: &str = "0.12.0"; const TAG: &str = formatcp!("aztec-packages-v{}", VERSION); const API_URL: &str = diff --git a/tooling/debugger/Cargo.toml b/tooling/debugger/Cargo.toml index 1f9a54b4fe8..53c71754da4 100644 --- a/tooling/debugger/Cargo.toml +++ b/tooling/debugger/Cargo.toml @@ -12,6 +12,7 @@ license.workspace = true acvm.workspace = true nargo.workspace = true noirc_printable_type.workspace = true +noirc_errors.workspace = true thiserror.workspace = true codespan-reporting.workspace = true easy-repl = "0.2.1" diff --git a/tooling/debugger/src/context.rs b/tooling/debugger/src/context.rs new file mode 100644 index 00000000000..a97bc9e8b86 --- /dev/null +++ b/tooling/debugger/src/context.rs @@ -0,0 +1,242 @@ +use acvm::acir::circuit::{Opcode, OpcodeLocation}; +use acvm::pwg::{ + ACVMStatus, BrilligSolver, BrilligSolverStatus, ForeignCallWaitInfo, StepResult, ACVM, +}; +use acvm::BlackBoxFunctionSolver; +use acvm::{acir::circuit::Circuit, acir::native_types::WitnessMap}; + +use nargo::artifacts::debug::DebugArtifact; +use nargo::errors::{ExecutionError, Location}; +use nargo::ops::ForeignCallExecutor; +use nargo::NargoError; + +use std::collections::{hash_set::Iter, HashSet}; + +#[derive(Debug)] +pub(super) enum DebugCommandResult { + Done, + Ok, + BreakpointReached(OpcodeLocation), + Error(NargoError), +} + +pub(super) struct DebugContext<'a, B: BlackBoxFunctionSolver> { + acvm: ACVM<'a, B>, + brillig_solver: Option>, + foreign_call_executor: ForeignCallExecutor, + debug_artifact: &'a DebugArtifact, + show_output: bool, + breakpoints: HashSet, +} + +impl<'a, B: BlackBoxFunctionSolver> DebugContext<'a, B> { + pub(super) fn new( + blackbox_solver: &'a B, + circuit: &'a Circuit, + debug_artifact: &'a DebugArtifact, + initial_witness: WitnessMap, + ) -> Self { + Self { + acvm: ACVM::new(blackbox_solver, &circuit.opcodes, initial_witness), + brillig_solver: None, + foreign_call_executor: ForeignCallExecutor::default(), + debug_artifact, + show_output: true, + breakpoints: HashSet::new(), + } + } + + pub(super) fn get_opcodes(&self) -> &[Opcode] { + self.acvm.opcodes() + } + + pub(super) fn get_current_opcode_location(&self) -> Option { + let ip = self.acvm.instruction_pointer(); + if ip >= self.get_opcodes().len() { + None + } else if let Some(ref solver) = self.brillig_solver { + Some(OpcodeLocation::Brillig { + acir_index: ip, + brillig_index: solver.program_counter(), + }) + } else { + Some(OpcodeLocation::Acir(ip)) + } + } + + // Returns the callstack in source code locations for the currently + // executing opcode. This can be None if the execution finished (and + // get_current_opcode_location() returns None) or if the opcode is not + // mapped to a specific source location in the debug artifact (which can + // happen for certain opcodes inserted synthetically by the compiler) + pub(super) fn get_current_source_location(&self) -> Option> { + self.get_current_opcode_location() + .as_ref() + .and_then(|location| self.debug_artifact.debug_symbols[0].opcode_location(location)) + } + + fn step_brillig_opcode(&mut self) -> DebugCommandResult { + let Some(mut solver) = self.brillig_solver.take() else { + unreachable!("Missing Brillig solver"); + }; + match solver.step() { + Ok(BrilligSolverStatus::InProgress) => { + self.brillig_solver = Some(solver); + if self.breakpoint_reached() { + DebugCommandResult::BreakpointReached( + self.get_current_opcode_location() + .expect("Breakpoint reached but we have no location"), + ) + } else { + DebugCommandResult::Ok + } + } + Ok(BrilligSolverStatus::Finished) => { + let status = self.acvm.finish_brillig_with_solver(solver); + self.handle_acvm_status(status) + } + Ok(BrilligSolverStatus::ForeignCallWait(foreign_call)) => { + self.brillig_solver = Some(solver); + self.handle_foreign_call(foreign_call) + } + Err(err) => DebugCommandResult::Error(NargoError::ExecutionError( + ExecutionError::SolvingError(err), + )), + } + } + + fn handle_foreign_call(&mut self, foreign_call: ForeignCallWaitInfo) -> DebugCommandResult { + let foreign_call_result = + self.foreign_call_executor.execute(&foreign_call, self.show_output); + match foreign_call_result { + Ok(foreign_call_result) => { + self.acvm.resolve_pending_foreign_call(foreign_call_result); + // TODO: should we retry executing the opcode somehow in this case? + DebugCommandResult::Ok + } + Err(error) => DebugCommandResult::Error(error), + } + } + + fn handle_acvm_status(&mut self, status: ACVMStatus) -> DebugCommandResult { + if let ACVMStatus::RequiresForeignCall(foreign_call) = status { + return self.handle_foreign_call(foreign_call); + } + + match status { + ACVMStatus::Solved => DebugCommandResult::Done, + ACVMStatus::InProgress => { + if self.breakpoint_reached() { + DebugCommandResult::BreakpointReached( + self.get_current_opcode_location() + .expect("Breakpoint reached but we have no location"), + ) + } else { + DebugCommandResult::Ok + } + } + ACVMStatus::Failure(error) => DebugCommandResult::Error(NargoError::ExecutionError( + ExecutionError::SolvingError(error), + )), + ACVMStatus::RequiresForeignCall(_) => { + unreachable!("Unexpected pending foreign call resolution"); + } + } + } + + pub(super) fn step_into_opcode(&mut self) -> DebugCommandResult { + if self.brillig_solver.is_some() { + return self.step_brillig_opcode(); + } + + match self.acvm.step_into_brillig_opcode() { + StepResult::IntoBrillig(solver) => { + self.brillig_solver = Some(solver); + self.step_brillig_opcode() + } + StepResult::Status(status) => self.handle_acvm_status(status), + } + } + + pub(super) fn step_acir_opcode(&mut self) -> DebugCommandResult { + let status = if let Some(solver) = self.brillig_solver.take() { + self.acvm.finish_brillig_with_solver(solver) + } else { + self.acvm.solve_opcode() + }; + self.handle_acvm_status(status) + } + + pub(super) fn next(&mut self) -> DebugCommandResult { + let start_location = self.get_current_source_location(); + loop { + let result = self.step_into_opcode(); + if !matches!(result, DebugCommandResult::Ok) { + return result; + } + let new_location = self.get_current_source_location(); + if new_location.is_some() && new_location != start_location { + return DebugCommandResult::Ok; + } + } + } + + pub(super) fn cont(&mut self) -> DebugCommandResult { + loop { + let result = self.step_into_opcode(); + if !matches!(result, DebugCommandResult::Ok) { + return result; + } + } + } + + fn breakpoint_reached(&self) -> bool { + if let Some(location) = self.get_current_opcode_location() { + self.breakpoints.contains(&location) + } else { + false + } + } + + pub(super) fn is_valid_opcode_location(&self, location: &OpcodeLocation) -> bool { + let opcodes = self.get_opcodes(); + match *location { + OpcodeLocation::Acir(acir_index) => acir_index < opcodes.len(), + OpcodeLocation::Brillig { acir_index, brillig_index } => { + acir_index < opcodes.len() + && matches!(opcodes[acir_index], Opcode::Brillig(..)) + && { + if let Opcode::Brillig(ref brillig) = opcodes[acir_index] { + brillig_index < brillig.bytecode.len() + } else { + false + } + } + } + } + } + + pub(super) fn is_breakpoint_set(&self, location: &OpcodeLocation) -> bool { + self.breakpoints.contains(location) + } + + pub(super) fn add_breakpoint(&mut self, location: OpcodeLocation) -> bool { + self.breakpoints.insert(location) + } + + pub(super) fn delete_breakpoint(&mut self, location: &OpcodeLocation) -> bool { + self.breakpoints.remove(location) + } + + pub(super) fn iterate_breakpoints(&self) -> Iter<'_, OpcodeLocation> { + self.breakpoints.iter() + } + + pub(super) fn is_solved(&self) -> bool { + matches!(self.acvm.get_status(), ACVMStatus::Solved) + } + + pub fn finalize(self) -> WitnessMap { + self.acvm.finalize() + } +} diff --git a/tooling/debugger/src/lib.rs b/tooling/debugger/src/lib.rs index 42f447ac857..7c6a9e9f618 100644 --- a/tooling/debugger/src/lib.rs +++ b/tooling/debugger/src/lib.rs @@ -1,293 +1,18 @@ -use acvm::acir::circuit::OpcodeLocation; -use acvm::pwg::{ - ACVMStatus, BrilligSolver, BrilligSolverStatus, ErrorLocation, OpcodeResolutionError, - StepResult, ACVM, -}; +mod context; +mod repl; + use acvm::BlackBoxFunctionSolver; use acvm::{acir::circuit::Circuit, acir::native_types::WitnessMap}; use nargo::artifacts::debug::DebugArtifact; -use nargo::errors::{ExecutionError, Location}; -use nargo::NargoError; - -use nargo::ops::ForeignCallExecutor; - -use easy_repl::{command, CommandStatus, Critical, Repl}; -use std::{ - cell::{Cell, RefCell}, - ops::Range, -}; - -use owo_colors::OwoColorize; - -use codespan_reporting::files::Files; - -enum SolveResult { - Done, - Ok, -} - -struct DebugContext<'backend, B: BlackBoxFunctionSolver> { - acvm: ACVM<'backend, B>, - brillig_solver: Option>, - debug_artifact: DebugArtifact, - foreign_call_executor: ForeignCallExecutor, - circuit: &'backend Circuit, - show_output: bool, -} - -impl<'backend, B: BlackBoxFunctionSolver> DebugContext<'backend, B> { - fn step_brillig_opcode(&mut self) -> Result { - let Some(mut solver) = self.brillig_solver.take() else { - unreachable!("Missing Brillig solver"); - }; - match solver.step() { - Ok(status) => { - println!("Brillig step result: {:?}", status); - println!("Brillig program counter: {:?}", solver.program_counter()); - match status { - BrilligSolverStatus::InProgress => { - self.brillig_solver = Some(solver); - Ok(SolveResult::Ok) - } - BrilligSolverStatus::Finished => { - let status = self.acvm.finish_brillig_with_solver(solver); - self.handle_acvm_status(status) - } - BrilligSolverStatus::ForeignCallWait(foreign_call) => { - let foreign_call_result = - self.foreign_call_executor.execute(&foreign_call, self.show_output)?; - solver.resolve_pending_foreign_call(foreign_call_result); - self.brillig_solver = Some(solver); - Ok(SolveResult::Ok) - } - } - } - Err(err) => self.handle_acvm_status(ACVMStatus::Failure(err)), - } - } - - fn step_opcode(&mut self) -> Result { - if matches!(self.brillig_solver, Some(_)) { - self.step_brillig_opcode() - } else { - match self.acvm.step_into_brillig_opcode() { - StepResult::IntoBrillig(solver) => { - self.brillig_solver = Some(solver); - self.step_brillig_opcode() - } - StepResult::Status(status) => self.handle_acvm_status(status), - } - } - } - - fn handle_acvm_status(&mut self, status: ACVMStatus) -> Result { - match status { - ACVMStatus::Solved => Ok(SolveResult::Done), - ACVMStatus::InProgress => Ok(SolveResult::Ok), - ACVMStatus::Failure(error) => { - let call_stack = match &error { - OpcodeResolutionError::UnsatisfiedConstrain { - opcode_location: ErrorLocation::Resolved(opcode_location), - } => Some(vec![*opcode_location]), - OpcodeResolutionError::BrilligFunctionFailed { call_stack, .. } => { - Some(call_stack.clone()) - } - _ => None, - }; - - Err(NargoError::ExecutionError(match call_stack { - Some(call_stack) => { - if let Some(assert_message) = self.circuit.get_assert_message( - *call_stack.last().expect("Call stacks should not be empty"), - ) { - ExecutionError::AssertionFailed(assert_message.to_owned(), call_stack) - } else { - ExecutionError::SolvingError(error) - } - } - None => ExecutionError::SolvingError(error), - })) - } - ACVMStatus::RequiresForeignCall(foreign_call) => { - let foreign_call_result = - self.foreign_call_executor.execute(&foreign_call, self.show_output)?; - self.acvm.resolve_pending_foreign_call(foreign_call_result); - Ok(SolveResult::Ok) - } - } - } - - fn show_current_vm_status(&self) { - let ip = self.acvm.instruction_pointer(); - let opcodes = self.acvm.opcodes(); - if ip >= opcodes.len() { - println!("Finished execution"); - } else { - println!("Stopped at opcode {}: {}", ip, opcodes[ip]); - self.show_source_code_location(&OpcodeLocation::Acir(ip), &self.debug_artifact); - } - } - - fn print_location_path(&self, loc: Location) { - let line_number = self.debug_artifact.location_line_number(loc).unwrap(); - let column_number = self.debug_artifact.location_column_number(loc).unwrap(); - - println!( - "At {}:{line_number}:{column_number}", - self.debug_artifact.name(loc.file).unwrap() - ); - } - - fn show_source_code_location(&self, location: &OpcodeLocation, debug_artifact: &DebugArtifact) { - let locations = debug_artifact.debug_symbols[0].opcode_location(location); - let Some(locations) = locations else { return }; - for loc in locations { - self.print_location_path(loc); - - let loc_line_index = debug_artifact.location_line_index(loc).unwrap(); - - // How many lines before or after the location's line we - // print - let context_lines = 5; - - let first_line_to_print = - if loc_line_index < context_lines { 0 } else { loc_line_index - context_lines }; - let last_line_index = debug_artifact.last_line_index(loc).unwrap(); - let last_line_to_print = std::cmp::min(loc_line_index + context_lines, last_line_index); - - let source = debug_artifact.location_source_code(loc).unwrap(); - for (current_line_index, line) in source.lines().enumerate() { - let current_line_number = current_line_index + 1; - - if current_line_index < first_line_to_print { - // Ignore lines before range starts - continue; - } else if current_line_index == first_line_to_print && current_line_index > 0 { - // Denote that there's more lines before but we're not showing them - print_line_of_ellipsis(current_line_index); - } - - if current_line_index > last_line_to_print { - // Denote that there's more lines after but we're not showing them, - // and stop printing - print_line_of_ellipsis(current_line_number); - break; - } - - if current_line_index == loc_line_index { - // Highlight current location - let Range { start: loc_start, end: loc_end } = - debug_artifact.location_in_line(loc).unwrap(); - println!( - "{:>3} {:2} {}{}{}", - current_line_number, - "->", - &line[0..loc_start].to_string().dimmed(), - &line[loc_start..loc_end], - &line[loc_end..].to_string().dimmed() - ); - } else { - print_dimmed_line(current_line_number, line); - } - } - } - } - - fn cont(&mut self) -> Result { - loop { - match self.step_opcode()? { - SolveResult::Done => break, - SolveResult::Ok => {} - } - } - Ok(SolveResult::Done) - } - - fn finalize(self) -> WitnessMap { - self.acvm.finalize() - } -} - -fn print_line_of_ellipsis(line_number: usize) { - println!("{}", format!("{:>3} {}", line_number, "...").dimmed()); -} - -fn print_dimmed_line(line_number: usize, line: &str) { - println!("{}", format!("{:>3} {:2} {}", line_number, "", line).dimmed()); -} - -fn map_command_status(result: SolveResult) -> CommandStatus { - match result { - SolveResult::Ok => CommandStatus::Done, - SolveResult::Done => CommandStatus::Quit, - } -} +use nargo::NargoError; pub fn debug_circuit( blackbox_solver: &B, circuit: &Circuit, debug_artifact: DebugArtifact, initial_witness: WitnessMap, - show_output: bool, ) -> Result, NargoError> { - let context = RefCell::new(DebugContext { - acvm: ACVM::new(blackbox_solver, &circuit.opcodes, initial_witness), - foreign_call_executor: ForeignCallExecutor::default(), - brillig_solver: None, - circuit, - debug_artifact, - show_output, - }); - let ref_step = &context; - let ref_cont = &context; - - let solved = Cell::new(false); - - context.borrow().show_current_vm_status(); - - let handle_result = |result| { - solved.set(matches!(result, SolveResult::Done)); - Ok(map_command_status(result)) - }; - - let mut repl = Repl::builder() - .add( - "s", - command! { - "step to the next opcode", - () => || { - let result = ref_step.borrow_mut().step_opcode().into_critical()?; - ref_step.borrow().show_current_vm_status(); - handle_result(result) - } - }, - ) - .add( - "c", - command! { - "continue execution until the end of the program", - () => || { - println!("(Continuing execution...)"); - let result = ref_cont.borrow_mut().cont().into_critical()?; - handle_result(result) - } - }, - ) - .build() - .expect("Failed to initialize debugger repl"); - - repl.run().expect("Debugger error"); - - // REPL execution has finished. - // Drop it so that we can move fields out from `context` again. - drop(repl); - - if solved.get() { - let solved_witness = context.into_inner().finalize(); - Ok(Some(solved_witness)) - } else { - Ok(None) - } + repl::run(blackbox_solver, circuit, &debug_artifact, initial_witness) } diff --git a/tooling/debugger/src/repl.rs b/tooling/debugger/src/repl.rs new file mode 100644 index 00000000000..320d8edf63a --- /dev/null +++ b/tooling/debugger/src/repl.rs @@ -0,0 +1,411 @@ +use crate::context::{DebugCommandResult, DebugContext}; + +use acvm::acir::circuit::{Opcode, OpcodeLocation}; +use acvm::BlackBoxFunctionSolver; +use acvm::{acir::circuit::Circuit, acir::native_types::WitnessMap}; + +use nargo::artifacts::debug::DebugArtifact; +use nargo::NargoError; + +use easy_repl::{command, CommandStatus, Repl}; +use std::cell::RefCell; + +use codespan_reporting::files::Files; +use noirc_errors::Location; + +use owo_colors::OwoColorize; + +use std::ops::Range; + +pub struct ReplDebugger<'a, B: BlackBoxFunctionSolver> { + context: DebugContext<'a, B>, + blackbox_solver: &'a B, + circuit: &'a Circuit, + debug_artifact: &'a DebugArtifact, + initial_witness: WitnessMap, + last_result: DebugCommandResult, +} + +impl<'a, B: BlackBoxFunctionSolver> ReplDebugger<'a, B> { + pub fn new( + blackbox_solver: &'a B, + circuit: &'a Circuit, + debug_artifact: &'a DebugArtifact, + initial_witness: WitnessMap, + ) -> Self { + let context = + DebugContext::new(blackbox_solver, circuit, debug_artifact, initial_witness.clone()); + Self { + context, + blackbox_solver, + circuit, + debug_artifact, + initial_witness, + last_result: DebugCommandResult::Ok, + } + } + + pub fn show_current_vm_status(&self) { + let location = self.context.get_current_opcode_location(); + let opcodes = self.context.get_opcodes(); + + match location { + None => println!("Finished execution"), + Some(location) => { + match location { + OpcodeLocation::Acir(ip) => { + println!("At opcode {}: {}", ip, opcodes[ip]) + } + OpcodeLocation::Brillig { acir_index, brillig_index } => { + let Opcode::Brillig(ref brillig) = opcodes[acir_index] else { + unreachable!("Brillig location does not contain a Brillig block"); + }; + println!( + "At opcode {}.{}: {:?}", + acir_index, brillig_index, brillig.bytecode[brillig_index] + ); + } + } + self.show_source_code_location(&location); + } + } + } + + fn print_location_path(&self, loc: Location) { + let line_number = self.debug_artifact.location_line_number(loc).unwrap(); + let column_number = self.debug_artifact.location_column_number(loc).unwrap(); + + println!( + "At {}:{line_number}:{column_number}", + self.debug_artifact.name(loc.file).unwrap() + ); + } + + fn show_source_code_location(&self, location: &OpcodeLocation) { + let locations = self.debug_artifact.debug_symbols[0].opcode_location(location); + let Some(locations) = locations else { return }; + for loc in locations { + self.print_location_path(loc); + + let loc_line_index = self.debug_artifact.location_line_index(loc).unwrap(); + + // How many lines before or after the location's line we + // print + let context_lines = 5; + + let first_line_to_print = + if loc_line_index < context_lines { 0 } else { loc_line_index - context_lines }; + + let last_line_index = self.debug_artifact.last_line_index(loc).unwrap(); + let last_line_to_print = std::cmp::min(loc_line_index + context_lines, last_line_index); + + let source = self.debug_artifact.location_source_code(loc).unwrap(); + for (current_line_index, line) in source.lines().enumerate() { + let current_line_number = current_line_index + 1; + + if current_line_index < first_line_to_print { + // Ignore lines before range starts + continue; + } else if current_line_index == first_line_to_print && current_line_index > 0 { + // Denote that there's more lines before but we're not showing them + print_line_of_ellipsis(current_line_index); + } + + if current_line_index > last_line_to_print { + // Denote that there's more lines after but we're not showing them, + // and stop printing + print_line_of_ellipsis(current_line_number); + break; + } + + if current_line_index == loc_line_index { + // Highlight current location + let Range { start: loc_start, end: loc_end } = + self.debug_artifact.location_in_line(loc).unwrap(); + println!( + "{:>3} {:2} {}{}{}", + current_line_number, + "->", + &line[0..loc_start].to_string().dimmed(), + &line[loc_start..loc_end], + &line[loc_end..].to_string().dimmed() + ); + } else { + print_dimmed_line(current_line_number, line); + } + } + } + } + + fn display_opcodes(&self) { + let opcodes = self.context.get_opcodes(); + let current_opcode_location = self.context.get_current_opcode_location(); + let current_acir_index = match current_opcode_location { + Some(OpcodeLocation::Acir(ip)) => Some(ip), + Some(OpcodeLocation::Brillig { acir_index, .. }) => Some(acir_index), + None => None, + }; + let current_brillig_index = match current_opcode_location { + Some(OpcodeLocation::Brillig { brillig_index, .. }) => brillig_index, + _ => 0, + }; + let outer_marker = |acir_index| { + if current_acir_index == Some(acir_index) { + "->" + } else if self.context.is_breakpoint_set(&OpcodeLocation::Acir(acir_index)) { + " *" + } else { + "" + } + }; + let brillig_marker = |acir_index, brillig_index| { + if current_acir_index == Some(acir_index) && brillig_index == current_brillig_index { + "->" + } else if self + .context + .is_breakpoint_set(&OpcodeLocation::Brillig { acir_index, brillig_index }) + { + " *" + } else { + "" + } + }; + for (acir_index, opcode) in opcodes.iter().enumerate() { + let marker = outer_marker(acir_index); + if let Opcode::Brillig(brillig) = opcode { + println!("{:>3} {:2} BRILLIG inputs={:?}", acir_index, marker, brillig.inputs); + println!(" | outputs={:?}", brillig.outputs); + for (brillig_index, brillig_opcode) in brillig.bytecode.iter().enumerate() { + println!( + "{:>3}.{:<2} |{:2} {:?}", + acir_index, + brillig_index, + brillig_marker(acir_index, brillig_index), + brillig_opcode + ); + } + } else { + println!("{:>3} {:2} {:?}", acir_index, marker, opcode); + } + } + } + + fn add_breakpoint_at(&mut self, location: OpcodeLocation) { + if !self.context.is_valid_opcode_location(&location) { + println!("Invalid opcode location {location}"); + } else if self.context.add_breakpoint(location) { + println!("Added breakpoint at opcode {location}"); + } else { + println!("Breakpoint at opcode {location} already set"); + } + } + + fn delete_breakpoint_at(&mut self, location: OpcodeLocation) { + if self.context.delete_breakpoint(&location) { + println!("Breakpoint at opcode {location} deleted"); + } else { + println!("Breakpoint at opcode {location} not set"); + } + } + + fn validate_in_progress(&self) -> bool { + match self.last_result { + DebugCommandResult::Ok | DebugCommandResult::BreakpointReached(..) => true, + DebugCommandResult::Done => { + println!("Execution finished"); + false + } + DebugCommandResult::Error(ref error) => { + println!("ERROR: {}", error); + self.show_current_vm_status(); + false + } + } + } + + fn handle_debug_command_result(&mut self, result: DebugCommandResult) { + match &result { + DebugCommandResult::BreakpointReached(location) => { + println!("Stopped at breakpoint in opcode {}", location); + } + DebugCommandResult::Error(error) => { + println!("ERROR: {}", error); + } + _ => (), + } + self.last_result = result; + self.show_current_vm_status(); + } + + fn step_acir_opcode(&mut self) { + if self.validate_in_progress() { + let result = self.context.step_acir_opcode(); + self.handle_debug_command_result(result); + } + } + + fn step_into_opcode(&mut self) { + if self.validate_in_progress() { + let result = self.context.step_into_opcode(); + self.handle_debug_command_result(result); + } + } + + fn next(&mut self) { + if self.validate_in_progress() { + let result = self.context.next(); + self.handle_debug_command_result(result); + } + } + + fn cont(&mut self) { + if self.validate_in_progress() { + println!("(Continuing execution...)"); + let result = self.context.cont(); + self.handle_debug_command_result(result); + } + } + + fn restart_session(&mut self) { + let breakpoints: Vec = + self.context.iterate_breakpoints().copied().collect(); + self.context = DebugContext::new( + self.blackbox_solver, + self.circuit, + self.debug_artifact, + self.initial_witness.clone(), + ); + for opcode_location in breakpoints { + self.context.add_breakpoint(opcode_location); + } + self.last_result = DebugCommandResult::Ok; + println!("Restarted debugging session."); + self.show_current_vm_status(); + } + + fn is_solved(&self) -> bool { + self.context.is_solved() + } + + fn finalize(self) -> WitnessMap { + self.context.finalize() + } +} + +fn print_line_of_ellipsis(line_number: usize) { + println!("{}", format!("{:>3} {}", line_number, "...").dimmed()); +} + +fn print_dimmed_line(line_number: usize, line: &str) { + println!("{}", format!("{:>3} {:2} {}", line_number, "", line).dimmed()); +} + +pub fn run( + blackbox_solver: &B, + circuit: &Circuit, + debug_artifact: &DebugArtifact, + initial_witness: WitnessMap, +) -> Result, NargoError> { + let context = + RefCell::new(ReplDebugger::new(blackbox_solver, circuit, debug_artifact, initial_witness)); + let ref_context = &context; + + ref_context.borrow().show_current_vm_status(); + + let mut repl = Repl::builder() + .add( + "step", + command! { + "step to the next ACIR opcode", + () => || { + ref_context.borrow_mut().step_acir_opcode(); + Ok(CommandStatus::Done) + } + }, + ) + .add( + "into", + command! { + "step into to the next opcode", + () => || { + ref_context.borrow_mut().step_into_opcode(); + Ok(CommandStatus::Done) + } + }, + ) + .add( + "next", + command! { + "step until a new source location is reached", + () => || { + ref_context.borrow_mut().next(); + Ok(CommandStatus::Done) + } + }, + ) + .add( + "continue", + command! { + "continue execution until the end of the program", + () => || { + ref_context.borrow_mut().cont(); + Ok(CommandStatus::Done) + } + }, + ) + .add( + "restart", + command! { + "restart the debugging session", + () => || { + ref_context.borrow_mut().restart_session(); + Ok(CommandStatus::Done) + } + }, + ) + .add( + "opcodes", + command! { + "display ACIR opcodes", + () => || { + ref_context.borrow().display_opcodes(); + Ok(CommandStatus::Done) + } + }, + ) + .add( + "break", + command! { + "add a breakpoint at an opcode location", + (LOCATION:OpcodeLocation) => |location| { + ref_context.borrow_mut().add_breakpoint_at(location); + Ok(CommandStatus::Done) + } + }, + ) + .add( + "delete", + command! { + "delete breakpoint at an opcode location", + (LOCATION:OpcodeLocation) => |location| { + ref_context.borrow_mut().delete_breakpoint_at(location); + Ok(CommandStatus::Done) + } + }, + ) + .build() + .expect("Failed to initialize debugger repl"); + + repl.run().expect("Debugger error"); + + // REPL execution has finished. + // Drop it so that we can move fields out from `context` again. + drop(repl); + + if context.borrow().is_solved() { + let solved_witness = context.into_inner().finalize(); + Ok(Some(solved_witness)) + } else { + Ok(None) + } +} diff --git a/tooling/lsp/Cargo.toml b/tooling/lsp/Cargo.toml index 8370820fe70..4f6274c908e 100644 --- a/tooling/lsp/Cargo.toml +++ b/tooling/lsp/Cargo.toml @@ -21,8 +21,8 @@ serde.workspace = true serde_json.workspace = true tower.workspace = true cfg-if.workspace = true -lsp-types = "0.94.1" -async-lsp = { version = "0.0.5", default-features = false, features = ["omni-trait"] } +lsp-types.workspace = true +async-lsp = { workspace = true, features = ["omni-trait"] } [target.'cfg(all(target_arch = "wasm32", not(target_os = "wasi")))'.dependencies] wasm-bindgen.workspace = true diff --git a/tooling/lsp/src/notifications/mod.rs b/tooling/lsp/src/notifications/mod.rs index 4a4567c01ed..a7d8bf3e2ec 100644 --- a/tooling/lsp/src/notifications/mod.rs +++ b/tooling/lsp/src/notifications/mod.rs @@ -3,7 +3,7 @@ use std::ops::ControlFlow; use async_lsp::{ErrorCode, LanguageClient, ResponseError}; use nargo::prepare_package; use nargo_toml::{find_package_manifest, resolve_workspace_from_toml, PackageSelection}; -use noirc_driver::check_crate; +use noirc_driver::{check_crate, NOIR_ARTIFACT_VERSION_STRING}; use noirc_errors::{DiagnosticKind, FileDiagnostic}; use crate::types::{ @@ -91,7 +91,11 @@ pub(super) fn on_did_save_text_document( return ControlFlow::Continue(()); } }; - let workspace = match resolve_workspace_from_toml(&toml_path, PackageSelection::All) { + let workspace = match resolve_workspace_from_toml( + &toml_path, + PackageSelection::All, + Some(NOIR_ARTIFACT_VERSION_STRING.to_string()), + ) { Ok(workspace) => workspace, Err(err) => { // If we found a manifest, but the workspace is invalid, we raise an error about it diff --git a/tooling/lsp/src/requests/code_lens_request.rs b/tooling/lsp/src/requests/code_lens_request.rs index b3a486760fb..31d8dc9fb7e 100644 --- a/tooling/lsp/src/requests/code_lens_request.rs +++ b/tooling/lsp/src/requests/code_lens_request.rs @@ -4,7 +4,7 @@ use async_lsp::{ErrorCode, LanguageClient, ResponseError}; use nargo::{package::Package, prepare_package, workspace::Workspace}; use nargo_toml::{find_package_manifest, resolve_workspace_from_toml, PackageSelection}; -use noirc_driver::check_crate; +use noirc_driver::{check_crate, NOIR_ARTIFACT_VERSION_STRING}; use noirc_frontend::hir::FunctionNameMatch; use crate::{ @@ -67,11 +67,15 @@ fn on_code_lens_request_inner( return Ok(None); } }; - let workspace = - resolve_workspace_from_toml(&toml_path, PackageSelection::All).map_err(|err| { - // If we found a manifest, but the workspace is invalid, we raise an error about it - ResponseError::new(ErrorCode::REQUEST_FAILED, err) - })?; + let workspace = resolve_workspace_from_toml( + &toml_path, + PackageSelection::All, + Some(NOIR_ARTIFACT_VERSION_STRING.to_string()), + ) + .map_err(|err| { + // If we found a manifest, but the workspace is invalid, we raise an error about it + ResponseError::new(ErrorCode::REQUEST_FAILED, err) + })?; let mut lenses: Vec = vec![]; diff --git a/tooling/lsp/src/requests/test_run.rs b/tooling/lsp/src/requests/test_run.rs index 30a3015eb75..962fe99a49b 100644 --- a/tooling/lsp/src/requests/test_run.rs +++ b/tooling/lsp/src/requests/test_run.rs @@ -6,7 +6,7 @@ use nargo::{ prepare_package, }; use nargo_toml::{find_package_manifest, resolve_workspace_from_toml, PackageSelection}; -use noirc_driver::{check_crate, CompileOptions}; +use noirc_driver::{check_crate, CompileOptions, NOIR_ARTIFACT_VERSION_STRING}; use noirc_frontend::hir::FunctionNameMatch; use crate::{ @@ -38,12 +38,15 @@ fn on_test_run_request_inner( let crate_name = params.id.crate_name(); let function_name = params.id.function_name(); - let workspace = - resolve_workspace_from_toml(&toml_path, PackageSelection::Selected(crate_name.clone())) - .map_err(|err| { - // If we found a manifest, but the workspace is invalid, we raise an error about it - ResponseError::new(ErrorCode::REQUEST_FAILED, err) - })?; + let workspace = resolve_workspace_from_toml( + &toml_path, + PackageSelection::Selected(crate_name.clone()), + Some(NOIR_ARTIFACT_VERSION_STRING.to_string()), + ) + .map_err(|err| { + // If we found a manifest, but the workspace is invalid, we raise an error about it + ResponseError::new(ErrorCode::REQUEST_FAILED, err) + })?; // Since we filtered on crate name, this should be the only item in the iterator match workspace.into_iter().next() { diff --git a/tooling/lsp/src/requests/tests.rs b/tooling/lsp/src/requests/tests.rs index a5988b54f06..6b94b921a06 100644 --- a/tooling/lsp/src/requests/tests.rs +++ b/tooling/lsp/src/requests/tests.rs @@ -4,7 +4,7 @@ use async_lsp::{ErrorCode, LanguageClient, ResponseError}; use lsp_types::{LogMessageParams, MessageType}; use nargo::prepare_package; use nargo_toml::{find_package_manifest, resolve_workspace_from_toml, PackageSelection}; -use noirc_driver::check_crate; +use noirc_driver::{check_crate, NOIR_ARTIFACT_VERSION_STRING}; use crate::{ get_non_stdlib_asset, get_package_tests_in_crate, @@ -40,11 +40,15 @@ fn on_tests_request_inner( } }; - let workspace = - resolve_workspace_from_toml(&toml_path, PackageSelection::All).map_err(|err| { - // If we found a manifest, but the workspace is invalid, we raise an error about it - ResponseError::new(ErrorCode::REQUEST_FAILED, err) - })?; + let workspace = resolve_workspace_from_toml( + &toml_path, + PackageSelection::All, + Some(NOIR_ARTIFACT_VERSION_STRING.to_string()), + ) + .map_err(|err| { + // If we found a manifest, but the workspace is invalid, we raise an error about it + ResponseError::new(ErrorCode::REQUEST_FAILED, err) + })?; let package_tests: Vec<_> = workspace .into_iter() diff --git a/tooling/nargo/Cargo.toml b/tooling/nargo/Cargo.toml index eda15ff2594..e6674c043d7 100644 --- a/tooling/nargo/Cargo.toml +++ b/tooling/nargo/Cargo.toml @@ -23,5 +23,4 @@ noirc_printable_type.workspace = true iter-extended.workspace = true serde.workspace = true thiserror.workspace = true -base64.workspace = true codespan-reporting.workspace = true diff --git a/tooling/nargo/build.rs b/tooling/nargo/build.rs index c9852cc9d80..4fa7f58892a 100644 --- a/tooling/nargo/build.rs +++ b/tooling/nargo/build.rs @@ -2,8 +2,8 @@ use rustc_version::{version, Version}; fn check_rustc_version() { assert!( - version().unwrap() >= Version::parse("1.67.0").unwrap(), - "The minimal supported rustc version is 1.67.0." + version().unwrap() >= Version::parse("1.71.1").unwrap(), + "The minimal supported rustc version is 1.71.1." ); } diff --git a/tooling/nargo/src/artifacts/contract.rs b/tooling/nargo/src/artifacts/contract.rs index 4f1ae0e10a0..f9e8d45b02e 100644 --- a/tooling/nargo/src/artifacts/contract.rs +++ b/tooling/nargo/src/artifacts/contract.rs @@ -37,8 +37,8 @@ pub struct PreprocessedContractFunction { pub abi: Abi, #[serde( - serialize_with = "super::serialize_circuit", - deserialize_with = "super::deserialize_circuit" + serialize_with = "Circuit::serialize_circuit_base64", + deserialize_with = "Circuit::deserialize_circuit_base64" )] pub bytecode: Circuit, } diff --git a/tooling/nargo/src/artifacts/debug.rs b/tooling/nargo/src/artifacts/debug.rs index d2e2eb9f311..19d8b88e641 100644 --- a/tooling/nargo/src/artifacts/debug.rs +++ b/tooling/nargo/src/artifacts/debug.rs @@ -1,6 +1,7 @@ use codespan_reporting::files::{Error, Files, SimpleFile}; use noirc_driver::DebugFile; use noirc_errors::{debug_info::DebugInfo, Location}; +use noirc_evaluator::errors::SsaReport; use serde::{Deserialize, Serialize}; use std::{ collections::{BTreeMap, BTreeSet}, @@ -15,6 +16,7 @@ use fm::{FileId, FileManager, PathString}; pub struct DebugArtifact { pub debug_symbols: Vec, pub file_map: BTreeMap, + pub warnings: Vec, } impl DebugArtifact { @@ -43,7 +45,7 @@ impl DebugArtifact { ); } - Self { debug_symbols, file_map } + Self { debug_symbols, file_map, warnings: Vec::new() } } /// Given a location, returns its file's source code diff --git a/tooling/nargo/src/artifacts/mod.rs b/tooling/nargo/src/artifacts/mod.rs index d25c65afd98..180a900fd81 100644 --- a/tooling/nargo/src/artifacts/mod.rs +++ b/tooling/nargo/src/artifacts/mod.rs @@ -3,34 +3,6 @@ //! These artifacts are intended to remain independent of any applications being built on top of Noir. //! Should any projects require/desire a different artifact format, it's expected that they will write a transformer //! to generate them using these artifacts as a starting point. -use acvm::acir::circuit::Circuit; -use base64::Engine; -use serde::{ - de::Error as DeserializationError, ser::Error as SerializationError, Deserializer, Serializer, -}; - pub mod contract; pub mod debug; pub mod program; - -// TODO: move these down into ACVM. -fn serialize_circuit(circuit: &Circuit, s: S) -> Result -where - S: Serializer, -{ - let mut circuit_bytes: Vec = Vec::new(); - circuit.write(&mut circuit_bytes).map_err(S::Error::custom)?; - let encoded_b64 = base64::engine::general_purpose::STANDARD.encode(circuit_bytes); - s.serialize_str(&encoded_b64) -} - -fn deserialize_circuit<'de, D>(deserializer: D) -> Result -where - D: Deserializer<'de>, -{ - let bytecode_b64: String = serde::Deserialize::deserialize(deserializer)?; - let circuit_bytes = - base64::engine::general_purpose::STANDARD.decode(bytecode_b64).map_err(D::Error::custom)?; - let circuit = Circuit::read(&*circuit_bytes).map_err(D::Error::custom)?; - Ok(circuit) -} diff --git a/tooling/nargo/src/artifacts/program.rs b/tooling/nargo/src/artifacts/program.rs index 5988f3f59cb..890b6c55f7d 100644 --- a/tooling/nargo/src/artifacts/program.rs +++ b/tooling/nargo/src/artifacts/program.rs @@ -21,8 +21,8 @@ pub struct PreprocessedProgram { pub abi: Abi, #[serde( - serialize_with = "super::serialize_circuit", - deserialize_with = "super::deserialize_circuit" + serialize_with = "Circuit::serialize_circuit_base64", + deserialize_with = "Circuit::deserialize_circuit_base64" )] pub bytecode: Circuit, } diff --git a/tooling/nargo/src/errors.rs b/tooling/nargo/src/errors.rs index 0c920716f2a..ba52d127e9e 100644 --- a/tooling/nargo/src/errors.rs +++ b/tooling/nargo/src/errors.rs @@ -91,7 +91,7 @@ fn extract_locations_from_error( _ => None, }?; - if let Some(OpcodeLocation::Brillig { acir_index, .. }) = opcode_locations.get(0) { + if let Some(OpcodeLocation::Brillig { acir_index, .. }) = opcode_locations.first() { opcode_locations.insert(0, OpcodeLocation::Acir(*acir_index)); } diff --git a/tooling/nargo/src/package.rs b/tooling/nargo/src/package.rs index 16f65d329ba..94c7c5b9c98 100644 --- a/tooling/nargo/src/package.rs +++ b/tooling/nargo/src/package.rs @@ -43,6 +43,8 @@ impl Dependency { #[derive(Clone)] pub struct Package { + // A semver string which specifies the compiler version required to compile this package + pub compiler_required_version: Option, pub root_dir: PathBuf, pub package_type: PackageType, pub entry_path: PathBuf, diff --git a/tooling/nargo_cli/Cargo.toml b/tooling/nargo_cli/Cargo.toml index a1440dc2ecb..1a08514dc5f 100644 --- a/tooling/nargo_cli/Cargo.toml +++ b/tooling/nargo_cli/Cargo.toml @@ -15,7 +15,7 @@ path = "src/main.rs" [build-dependencies] rustc_version = "0.4.0" -build-data = "0.1.3" +build-data.workspace = true toml.workspace = true [dependencies] @@ -40,14 +40,9 @@ prettytable-rs = "0.10" rayon = "1.8.0" thiserror.workspace = true tower.workspace = true -async-lsp = { version = "0.0.5", default-features = false, features = [ - "client-monitor", - "stdio", - "tracing", - "tokio", -] } -const_format = "0.2.30" -hex = "0.4.2" +async-lsp = { workspace = true, features = ["client-monitor", "stdio", "tracing", "tokio"] } +const_format.workspace = true +hex.workspace = true termcolor = "1.1.2" color-eyre = "0.6.2" tokio = { version = "1.0", features = ["io-std"] } diff --git a/tooling/nargo_cli/build.rs b/tooling/nargo_cli/build.rs index 39960690fe2..0d1acca6ee9 100644 --- a/tooling/nargo_cli/build.rs +++ b/tooling/nargo_cli/build.rs @@ -6,8 +6,8 @@ use std::{env, fs}; fn check_rustc_version() { assert!( - version().unwrap() >= Version::parse("1.67.0").unwrap(), - "The minimal supported rustc version is 1.67.0." + version().unwrap() >= Version::parse("1.71.1").unwrap(), + "The minimal supported rustc version is 1.71.1." ); } diff --git a/tooling/nargo_cli/src/cli/check_cmd.rs b/tooling/nargo_cli/src/cli/check_cmd.rs index 30309f88f32..79f199381fa 100644 --- a/tooling/nargo_cli/src/cli/check_cmd.rs +++ b/tooling/nargo_cli/src/cli/check_cmd.rs @@ -6,7 +6,9 @@ use iter_extended::btree_map; use nargo::{package::Package, prepare_package}; use nargo_toml::{get_package_manifest, resolve_workspace_from_toml, PackageSelection}; use noirc_abi::{AbiParameter, AbiType, MAIN_RETURN_NAME}; -use noirc_driver::{check_crate, compute_function_abi, CompileOptions}; +use noirc_driver::{ + check_crate, compute_function_abi, CompileOptions, NOIR_ARTIFACT_VERSION_STRING, +}; use noirc_frontend::{ graph::{CrateId, CrateName}, hir::Context, @@ -39,7 +41,11 @@ pub(crate) fn run( let default_selection = if args.workspace { PackageSelection::All } else { PackageSelection::DefaultOrAll }; let selection = args.package.map_or(default_selection, PackageSelection::Selected); - let workspace = resolve_workspace_from_toml(&toml_path, selection)?; + let workspace = resolve_workspace_from_toml( + &toml_path, + selection, + Some(NOIR_ARTIFACT_VERSION_STRING.to_string()), + )?; for package in &workspace { check_package(package, &args.compile_options)?; diff --git a/tooling/nargo_cli/src/cli/codegen_verifier_cmd.rs b/tooling/nargo_cli/src/cli/codegen_verifier_cmd.rs index 856970544b8..59143526b24 100644 --- a/tooling/nargo_cli/src/cli/codegen_verifier_cmd.rs +++ b/tooling/nargo_cli/src/cli/codegen_verifier_cmd.rs @@ -13,7 +13,7 @@ use clap::Args; use nargo::package::Package; use nargo::workspace::Workspace; use nargo_toml::{get_package_manifest, resolve_workspace_from_toml, PackageSelection}; -use noirc_driver::CompileOptions; +use noirc_driver::{CompileOptions, NOIR_ARTIFACT_VERSION_STRING}; use noirc_frontend::graph::CrateName; /// Generates a Solidity verifier smart contract for the program @@ -40,7 +40,11 @@ pub(crate) fn run( let default_selection = if args.workspace { PackageSelection::All } else { PackageSelection::DefaultOrAll }; let selection = args.package.map_or(default_selection, PackageSelection::Selected); - let workspace = resolve_workspace_from_toml(&toml_path, selection)?; + let workspace = resolve_workspace_from_toml( + &toml_path, + selection, + Some(NOIR_ARTIFACT_VERSION_STRING.to_string()), + )?; let (np_language, opcode_support) = backend.get_backend_info()?; for package in &workspace { diff --git a/tooling/nargo_cli/src/cli/compile_cmd.rs b/tooling/nargo_cli/src/cli/compile_cmd.rs index 039fee5dbc4..156359dab04 100644 --- a/tooling/nargo_cli/src/cli/compile_cmd.rs +++ b/tooling/nargo_cli/src/cli/compile_cmd.rs @@ -61,7 +61,12 @@ pub(crate) fn run( let default_selection = if args.workspace { PackageSelection::All } else { PackageSelection::DefaultOrAll }; let selection = args.package.map_or(default_selection, PackageSelection::Selected); - let workspace = resolve_workspace_from_toml(&toml_path, selection)?; + + let workspace = resolve_workspace_from_toml( + &toml_path, + selection, + Some(NOIR_ARTIFACT_VERSION_STRING.to_owned()), + )?; let circuit_dir = workspace.target_directory_path(); let (binary_packages, contract_packages): (Vec<_>, Vec<_>) = workspace @@ -188,6 +193,7 @@ fn compile_program( noir_version: preprocessed_program.noir_version, debug: debug_artifact.debug_symbols.remove(0), file_map: debug_artifact.file_map, + warnings: debug_artifact.warnings, }) } else { None @@ -261,8 +267,11 @@ fn save_program(program: CompiledProgram, package: &Package, circuit_dir: &Path) save_program_to_file(&preprocessed_program, &package.name, circuit_dir); - let debug_artifact = - DebugArtifact { debug_symbols: vec![program.debug], file_map: program.file_map }; + let debug_artifact = DebugArtifact { + debug_symbols: vec![program.debug], + file_map: program.file_map, + warnings: program.warnings, + }; let circuit_name: String = (&package.name).into(); save_debug_artifact_to_file(&debug_artifact, &circuit_name, circuit_dir); } @@ -275,6 +284,7 @@ fn save_contract(contract: CompiledContract, package: &Package, circuit_dir: &Pa let debug_artifact = DebugArtifact { debug_symbols: contract.functions.iter().map(|function| function.debug.clone()).collect(), file_map: contract.file_map, + warnings: contract.warnings, }; let preprocessed_functions = vecmap(contract.functions, |func| PreprocessedContractFunction { diff --git a/tooling/nargo_cli/src/cli/debug_cmd.rs b/tooling/nargo_cli/src/cli/debug_cmd.rs index 82cd3349ec4..1d344058312 100644 --- a/tooling/nargo_cli/src/cli/debug_cmd.rs +++ b/tooling/nargo_cli/src/cli/debug_cmd.rs @@ -7,7 +7,7 @@ use nargo::package::Package; use nargo_toml::{get_package_manifest, resolve_workspace_from_toml, PackageSelection}; use noirc_abi::input_parser::{Format, InputValue}; use noirc_abi::InputMap; -use noirc_driver::{CompileOptions, CompiledProgram}; +use noirc_driver::{CompileOptions, CompiledProgram, NOIR_ARTIFACT_VERSION_STRING}; use noirc_frontend::graph::CrateName; use super::compile_cmd::compile_bin_package; @@ -41,7 +41,11 @@ pub(crate) fn run( ) -> Result<(), CliError> { let toml_path = get_package_manifest(&config.program_dir)?; let selection = args.package.map_or(PackageSelection::DefaultOrAll, PackageSelection::Selected); - let workspace = resolve_workspace_from_toml(&toml_path, selection)?; + let workspace = resolve_workspace_from_toml( + &toml_path, + selection, + Some(NOIR_ARTIFACT_VERSION_STRING.to_string()), + )?; let target_dir = &workspace.target_directory_path(); let (np_language, opcode_support) = backend.get_backend_info()?; @@ -112,6 +116,7 @@ pub(crate) fn debug_program( let debug_artifact = DebugArtifact { debug_symbols: vec![compiled_program.debug.clone()], file_map: compiled_program.file_map.clone(), + warnings: compiled_program.warnings.clone(), }; noir_debugger::debug_circuit( @@ -119,7 +124,6 @@ pub(crate) fn debug_program( &compiled_program.circuit, debug_artifact, initial_witness, - true, ) .map_err(CliError::from) } diff --git a/tooling/nargo_cli/src/cli/execute_cmd.rs b/tooling/nargo_cli/src/cli/execute_cmd.rs index 1819c9a6f06..3a0da2b1134 100644 --- a/tooling/nargo_cli/src/cli/execute_cmd.rs +++ b/tooling/nargo_cli/src/cli/execute_cmd.rs @@ -8,7 +8,7 @@ use nargo::package::Package; use nargo_toml::{get_package_manifest, resolve_workspace_from_toml, PackageSelection}; use noirc_abi::input_parser::{Format, InputValue}; use noirc_abi::InputMap; -use noirc_driver::{CompileOptions, CompiledProgram}; +use noirc_driver::{CompileOptions, CompiledProgram, NOIR_ARTIFACT_VERSION_STRING}; use noirc_frontend::graph::CrateName; use super::compile_cmd::compile_bin_package; @@ -48,7 +48,11 @@ pub(crate) fn run( let default_selection = if args.workspace { PackageSelection::All } else { PackageSelection::DefaultOrAll }; let selection = args.package.map_or(default_selection, PackageSelection::Selected); - let workspace = resolve_workspace_from_toml(&toml_path, selection)?; + let workspace = resolve_workspace_from_toml( + &toml_path, + selection, + Some(NOIR_ARTIFACT_VERSION_STRING.to_string()), + )?; let target_dir = &workspace.target_directory_path(); let (np_language, opcode_support) = backend.get_backend_info()?; @@ -113,6 +117,7 @@ pub(crate) fn execute_program( let debug_artifact = DebugArtifact { debug_symbols: vec![compiled_program.debug.clone()], file_map: compiled_program.file_map.clone(), + warnings: compiled_program.warnings.clone(), }; if let Some(diagnostic) = try_to_diagnose_runtime_error(&err, &compiled_program.debug) { diff --git a/tooling/nargo_cli/src/cli/fmt_cmd.rs b/tooling/nargo_cli/src/cli/fmt_cmd.rs index 31b45cc092a..42fe5a0d362 100644 --- a/tooling/nargo_cli/src/cli/fmt_cmd.rs +++ b/tooling/nargo_cli/src/cli/fmt_cmd.rs @@ -3,6 +3,7 @@ use std::{fs::DirEntry, path::Path}; use clap::Args; use fm::FileManager; use nargo_toml::{get_package_manifest, resolve_workspace_from_toml, PackageSelection}; +use noirc_driver::NOIR_ARTIFACT_VERSION_STRING; use noirc_errors::CustomDiagnostic; use noirc_frontend::hir::def_map::parse_file; @@ -15,7 +16,11 @@ pub(crate) struct FormatCommand {} pub(crate) fn run(_args: FormatCommand, config: NargoConfig) -> Result<(), CliError> { let toml_path = get_package_manifest(&config.program_dir)?; - let workspace = resolve_workspace_from_toml(&toml_path, PackageSelection::All)?; + let workspace = resolve_workspace_from_toml( + &toml_path, + PackageSelection::All, + Some(NOIR_ARTIFACT_VERSION_STRING.to_string()), + )?; let config = nargo_fmt::Config::read(&config.program_dir) .map_err(|err| CliError::Generic(err.to_string()))?; diff --git a/tooling/nargo_cli/src/cli/info_cmd.rs b/tooling/nargo_cli/src/cli/info_cmd.rs index 50021e842c4..de0c63c3ab3 100644 --- a/tooling/nargo_cli/src/cli/info_cmd.rs +++ b/tooling/nargo_cli/src/cli/info_cmd.rs @@ -4,7 +4,9 @@ use clap::Args; use iter_extended::vecmap; use nargo::package::Package; use nargo_toml::{get_package_manifest, resolve_workspace_from_toml, PackageSelection}; -use noirc_driver::{CompileOptions, CompiledContract, CompiledProgram}; +use noirc_driver::{ + CompileOptions, CompiledContract, CompiledProgram, NOIR_ARTIFACT_VERSION_STRING, +}; use noirc_frontend::graph::CrateName; use prettytable::{row, table, Row}; use rayon::prelude::*; @@ -47,7 +49,11 @@ pub(crate) fn run( let default_selection = if args.workspace { PackageSelection::All } else { PackageSelection::DefaultOrAll }; let selection = args.package.map_or(default_selection, PackageSelection::Selected); - let workspace = resolve_workspace_from_toml(&toml_path, selection)?; + let workspace = resolve_workspace_from_toml( + &toml_path, + selection, + Some(NOIR_ARTIFACT_VERSION_STRING.to_string()), + )?; let (binary_packages, contract_packages): (Vec<_>, Vec<_>) = workspace .into_iter() diff --git a/tooling/nargo_cli/src/cli/init_cmd.rs b/tooling/nargo_cli/src/cli/init_cmd.rs index 9d7700a6598..e53c2e4cdc9 100644 --- a/tooling/nargo_cli/src/cli/init_cmd.rs +++ b/tooling/nargo_cli/src/cli/init_cmd.rs @@ -73,7 +73,7 @@ pub(crate) fn initialize_project( name = "{package_name}" type = "{package_type}" authors = [""] -compiler_version = "{NOIRC_VERSION}" +compiler_version = ">={NOIRC_VERSION}" [dependencies]"# ); diff --git a/tooling/nargo_cli/src/cli/prove_cmd.rs b/tooling/nargo_cli/src/cli/prove_cmd.rs index af300b7ebe0..3586e73ff2e 100644 --- a/tooling/nargo_cli/src/cli/prove_cmd.rs +++ b/tooling/nargo_cli/src/cli/prove_cmd.rs @@ -4,7 +4,7 @@ use nargo::package::Package; use nargo::workspace::Workspace; use nargo_toml::{get_package_manifest, resolve_workspace_from_toml, PackageSelection}; use noirc_abi::input_parser::Format; -use noirc_driver::{CompileOptions, CompiledProgram}; +use noirc_driver::{CompileOptions, CompiledProgram, NOIR_ARTIFACT_VERSION_STRING}; use noirc_frontend::graph::CrateName; use super::compile_cmd::compile_bin_package; @@ -51,7 +51,11 @@ pub(crate) fn run( let default_selection = if args.workspace { PackageSelection::All } else { PackageSelection::DefaultOrAll }; let selection = args.package.map_or(default_selection, PackageSelection::Selected); - let workspace = resolve_workspace_from_toml(&toml_path, selection)?; + let workspace = resolve_workspace_from_toml( + &toml_path, + selection, + Some(NOIR_ARTIFACT_VERSION_STRING.to_string()), + )?; let (np_language, opcode_support) = backend.get_backend_info()?; for package in &workspace { diff --git a/tooling/nargo_cli/src/cli/test_cmd.rs b/tooling/nargo_cli/src/cli/test_cmd.rs index 4ba2fc35766..e117d8555a5 100644 --- a/tooling/nargo_cli/src/cli/test_cmd.rs +++ b/tooling/nargo_cli/src/cli/test_cmd.rs @@ -8,7 +8,7 @@ use nargo::{ prepare_package, }; use nargo_toml::{get_package_manifest, resolve_workspace_from_toml, PackageSelection}; -use noirc_driver::CompileOptions; +use noirc_driver::{CompileOptions, NOIR_ARTIFACT_VERSION_STRING}; use noirc_frontend::{graph::CrateName, hir::FunctionNameMatch}; use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor}; @@ -51,7 +51,11 @@ pub(crate) fn run( let default_selection = if args.workspace { PackageSelection::All } else { PackageSelection::DefaultOrAll }; let selection = args.package.map_or(default_selection, PackageSelection::Selected); - let workspace = resolve_workspace_from_toml(&toml_path, selection)?; + let workspace = resolve_workspace_from_toml( + &toml_path, + selection, + Some(NOIR_ARTIFACT_VERSION_STRING.to_string()), + )?; let pattern = match &args.test_name { Some(name) => { diff --git a/tooling/nargo_cli/src/cli/verify_cmd.rs b/tooling/nargo_cli/src/cli/verify_cmd.rs index 6ae2b78fd0c..8c6d92b3d2f 100644 --- a/tooling/nargo_cli/src/cli/verify_cmd.rs +++ b/tooling/nargo_cli/src/cli/verify_cmd.rs @@ -11,7 +11,7 @@ use nargo::package::Package; use nargo::workspace::Workspace; use nargo_toml::{get_package_manifest, resolve_workspace_from_toml, PackageSelection}; use noirc_abi::input_parser::Format; -use noirc_driver::{CompileOptions, CompiledProgram}; +use noirc_driver::{CompileOptions, CompiledProgram, NOIR_ARTIFACT_VERSION_STRING}; use noirc_frontend::graph::CrateName; /// Given a proof and a program, verify whether the proof is valid @@ -42,7 +42,11 @@ pub(crate) fn run( let default_selection = if args.workspace { PackageSelection::All } else { PackageSelection::DefaultOrAll }; let selection = args.package.map_or(default_selection, PackageSelection::Selected); - let workspace = resolve_workspace_from_toml(&toml_path, selection)?; + let workspace = resolve_workspace_from_toml( + &toml_path, + selection, + Some(NOIR_ARTIFACT_VERSION_STRING.to_string()), + )?; let (np_language, opcode_support) = backend.get_backend_info()?; for package in &workspace { diff --git a/tooling/nargo_cli/tests/acir_artifacts/array_dynamic/target/acir.gz b/tooling/nargo_cli/tests/acir_artifacts/array_dynamic/target/acir.gz index ba3c09529b1..57701adcf3f 100644 Binary files a/tooling/nargo_cli/tests/acir_artifacts/array_dynamic/target/acir.gz and b/tooling/nargo_cli/tests/acir_artifacts/array_dynamic/target/acir.gz differ diff --git a/tooling/nargo_cli/tests/acir_artifacts/array_dynamic/target/witness.gz b/tooling/nargo_cli/tests/acir_artifacts/array_dynamic/target/witness.gz index 3cacd507613..de5a1d07227 100644 Binary files a/tooling/nargo_cli/tests/acir_artifacts/array_dynamic/target/witness.gz and b/tooling/nargo_cli/tests/acir_artifacts/array_dynamic/target/witness.gz differ diff --git a/tooling/nargo_cli/tests/acir_artifacts/brillig_unitialised_arrays/target/acir.gz b/tooling/nargo_cli/tests/acir_artifacts/brillig_unitialised_arrays/target/acir.gz index 4ab33919248..7bc3304fdaa 100644 Binary files a/tooling/nargo_cli/tests/acir_artifacts/brillig_unitialised_arrays/target/acir.gz and b/tooling/nargo_cli/tests/acir_artifacts/brillig_unitialised_arrays/target/acir.gz differ diff --git a/tooling/nargo_cli/tests/acir_artifacts/brillig_unitialised_arrays/target/witness.gz b/tooling/nargo_cli/tests/acir_artifacts/brillig_unitialised_arrays/target/witness.gz index 869536a1d98..2cbd61f9c4a 100644 Binary files a/tooling/nargo_cli/tests/acir_artifacts/brillig_unitialised_arrays/target/witness.gz and b/tooling/nargo_cli/tests/acir_artifacts/brillig_unitialised_arrays/target/witness.gz differ diff --git a/tooling/nargo_cli/tests/acir_artifacts/nested_array_dynamic/target/acir.gz b/tooling/nargo_cli/tests/acir_artifacts/nested_array_dynamic/target/acir.gz index e78bf59102d..c7559671f2a 100644 Binary files a/tooling/nargo_cli/tests/acir_artifacts/nested_array_dynamic/target/acir.gz and b/tooling/nargo_cli/tests/acir_artifacts/nested_array_dynamic/target/acir.gz differ diff --git a/tooling/nargo_cli/tests/acir_artifacts/nested_array_dynamic/target/witness.gz b/tooling/nargo_cli/tests/acir_artifacts/nested_array_dynamic/target/witness.gz index d2ff2ed1b94..7efd9b48ca4 100644 Binary files a/tooling/nargo_cli/tests/acir_artifacts/nested_array_dynamic/target/witness.gz and b/tooling/nargo_cli/tests/acir_artifacts/nested_array_dynamic/target/witness.gz differ diff --git a/tooling/nargo_cli/tests/acir_artifacts/regression_mem_op_predicate/target/acir.gz b/tooling/nargo_cli/tests/acir_artifacts/regression_mem_op_predicate/target/acir.gz index bb54dc5f548..20e8fa769a5 100644 Binary files a/tooling/nargo_cli/tests/acir_artifacts/regression_mem_op_predicate/target/acir.gz and b/tooling/nargo_cli/tests/acir_artifacts/regression_mem_op_predicate/target/acir.gz differ diff --git a/tooling/nargo_cli/tests/acir_artifacts/regression_mem_op_predicate/target/witness.gz b/tooling/nargo_cli/tests/acir_artifacts/regression_mem_op_predicate/target/witness.gz index e8653567d5f..000b4483daf 100644 Binary files a/tooling/nargo_cli/tests/acir_artifacts/regression_mem_op_predicate/target/witness.gz and b/tooling/nargo_cli/tests/acir_artifacts/regression_mem_op_predicate/target/witness.gz differ diff --git a/tooling/nargo_cli/tests/acir_artifacts/simple_shield/target/acir.gz b/tooling/nargo_cli/tests/acir_artifacts/simple_shield/target/acir.gz index 9a9f3a76992..0600c1dfc78 100644 Binary files a/tooling/nargo_cli/tests/acir_artifacts/simple_shield/target/acir.gz and b/tooling/nargo_cli/tests/acir_artifacts/simple_shield/target/acir.gz differ diff --git a/tooling/nargo_cli/tests/acir_artifacts/slice_dynamic_index/target/acir.gz b/tooling/nargo_cli/tests/acir_artifacts/slice_dynamic_index/target/acir.gz index 30b5d36a2e3..08d3fa2de40 100644 Binary files a/tooling/nargo_cli/tests/acir_artifacts/slice_dynamic_index/target/acir.gz and b/tooling/nargo_cli/tests/acir_artifacts/slice_dynamic_index/target/acir.gz differ diff --git a/tooling/nargo_cli/tests/acir_artifacts/slice_dynamic_index/target/witness.gz b/tooling/nargo_cli/tests/acir_artifacts/slice_dynamic_index/target/witness.gz index 1cbd7129bb0..a077aaf9e56 100644 Binary files a/tooling/nargo_cli/tests/acir_artifacts/slice_dynamic_index/target/witness.gz and b/tooling/nargo_cli/tests/acir_artifacts/slice_dynamic_index/target/witness.gz differ diff --git a/tooling/nargo_cli/tests/acir_artifacts/slices/target/acir.gz b/tooling/nargo_cli/tests/acir_artifacts/slices/target/acir.gz index 70a32bccf6f..70a3700cbaf 100644 Binary files a/tooling/nargo_cli/tests/acir_artifacts/slices/target/acir.gz and b/tooling/nargo_cli/tests/acir_artifacts/slices/target/acir.gz differ diff --git a/tooling/nargo_cli/tests/acir_artifacts/slices/target/witness.gz b/tooling/nargo_cli/tests/acir_artifacts/slices/target/witness.gz index ac4ffe17323..07ac75fe038 100644 Binary files a/tooling/nargo_cli/tests/acir_artifacts/slices/target/witness.gz and b/tooling/nargo_cli/tests/acir_artifacts/slices/target/witness.gz differ diff --git a/tooling/nargo_cli/tests/compile_failure/assert_constant_fail/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/assert_constant_fail/Nargo.toml index a8c9b4ad344..2eaf67246e1 100644 --- a/tooling/nargo_cli/tests/compile_failure/assert_constant_fail/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/assert_constant_fail/Nargo.toml @@ -2,6 +2,4 @@ name = "assert_constant_fail" type = "bin" authors = [""] -compiler_version = "0.9.0" - [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_failure/assert_eq_struct/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/assert_eq_struct/Nargo.toml index 055c23234ce..9fcdcc10bb7 100644 --- a/tooling/nargo_cli/tests/compile_failure/assert_eq_struct/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/assert_eq_struct/Nargo.toml @@ -2,6 +2,4 @@ name = "assert_eq_struct" type = "bin" authors = [""] -compiler_version = "0.1" - [dependencies] diff --git a/tooling/nargo_cli/tests/compile_failure/brillig_assert_fail/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/brillig_assert_fail/Nargo.toml index 181af302d8f..7ce776e5ce6 100644 --- a/tooling/nargo_cli/tests/compile_failure/brillig_assert_fail/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/brillig_assert_fail/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_assert_fail" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_failure/brillig_assert_fail/src/main.nr b/tooling/nargo_cli/tests/compile_failure/brillig_assert_fail/src/main.nr index 801a818c816..e9379a29876 100644 --- a/tooling/nargo_cli/tests/compile_failure/brillig_assert_fail/src/main.nr +++ b/tooling/nargo_cli/tests/compile_failure/brillig_assert_fail/src/main.nr @@ -1,7 +1,7 @@ // Tests a very simple program. // // The features being tested is using assert on brillig -fn main(x: Field) { +fn main(x: Field) { assert(1 == conditional(x as bool)); } diff --git a/tooling/nargo_cli/tests/compile_failure/constrain_typo/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/constrain_typo/Nargo.toml index db1c3480387..191121e59b7 100644 --- a/tooling/nargo_cli/tests/compile_failure/constrain_typo/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/constrain_typo/Nargo.toml @@ -2,6 +2,5 @@ name = "constrain_typo" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_failure/custom_entry_not_found/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/custom_entry_not_found/Nargo.toml index 0ccb94aff1a..a32696d3370 100644 --- a/tooling/nargo_cli/tests/compile_failure/custom_entry_not_found/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/custom_entry_not_found/Nargo.toml @@ -4,6 +4,5 @@ type = "bin" # Testing that this file is missing and doesn't fallback to default `main.nr` file entry = "src/foobarbaz.nr" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_failure/dep_impl_primitive/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/dep_impl_primitive/Nargo.toml index 6a49afec2c4..afe5a5134ca 100644 --- a/tooling/nargo_cli/tests/compile_failure/dep_impl_primitive/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/dep_impl_primitive/Nargo.toml @@ -2,7 +2,5 @@ name = "dep_impl_primitive" type = "bin" authors = [""] -compiler_version = "0.8.0" - [dependencies] bad_impl = { path = "../../test_libraries/bad_impl" } diff --git a/tooling/nargo_cli/tests/compile_failure/depend_on_bin/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/depend_on_bin/Nargo.toml index 2404e68e180..8334a38eb4b 100644 --- a/tooling/nargo_cli/tests/compile_failure/depend_on_bin/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/depend_on_bin/Nargo.toml @@ -2,7 +2,5 @@ name = "depend_on_bin" type = "bin" authors = [""] -compiler_version = "0.8.0" - [dependencies] bin_dep = { path = "../../test_libraries/bin_dep" } diff --git a/tooling/nargo_cli/tests/compile_failure/div_by_zero_constants/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/div_by_zero_constants/Nargo.toml index 55e36368845..aad13c7d97f 100644 --- a/tooling/nargo_cli/tests/compile_failure/div_by_zero_constants/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/div_by_zero_constants/Nargo.toml @@ -2,6 +2,5 @@ name = "divide_by_zero" type = "bin" authors = [""] -compiler_version = "0.10.3" [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_failure/div_by_zero_constants/src/main.nr b/tooling/nargo_cli/tests/compile_failure/div_by_zero_constants/src/main.nr index 2259d51e6de..58adc5444b1 100644 --- a/tooling/nargo_cli/tests/compile_failure/div_by_zero_constants/src/main.nr +++ b/tooling/nargo_cli/tests/compile_failure/div_by_zero_constants/src/main.nr @@ -3,4 +3,4 @@ use dep::std; fn main() { let a: Field = 3 / 0; std::println(a); -} \ No newline at end of file +} diff --git a/tooling/nargo_cli/tests/compile_failure/div_by_zero_modulo/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/div_by_zero_modulo/Nargo.toml index d3b69d8c41b..22ff18075cd 100644 --- a/tooling/nargo_cli/tests/compile_failure/div_by_zero_modulo/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/div_by_zero_modulo/Nargo.toml @@ -2,6 +2,5 @@ name = "div_by_zero_modulo" type = "bin" authors = [""] -compiler_version = "0.10.5" [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_failure/div_by_zero_modulo/src/main.nr b/tooling/nargo_cli/tests/compile_failure/div_by_zero_modulo/src/main.nr index f20c39486e0..d938ab7fca8 100644 --- a/tooling/nargo_cli/tests/compile_failure/div_by_zero_modulo/src/main.nr +++ b/tooling/nargo_cli/tests/compile_failure/div_by_zero_modulo/src/main.nr @@ -1,7 +1,7 @@ fn main() { let a: u32 = 6; - let b = 3; - let c = 0; - let res = (a*b) % c; - assert(res != 5); -} \ No newline at end of file + let b = 3; + let c = 0; + let res = (a * b) % c; + assert(res != 5); +} diff --git a/tooling/nargo_cli/tests/compile_failure/div_by_zero_numerator_witness/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/div_by_zero_numerator_witness/Nargo.toml index 58a60a38a0c..30a7eb62645 100644 --- a/tooling/nargo_cli/tests/compile_failure/div_by_zero_numerator_witness/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/div_by_zero_numerator_witness/Nargo.toml @@ -2,6 +2,5 @@ name = "div_by_zero_numerator_witness" type = "bin" authors = [""] -compiler_version = "0.10.3" [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_failure/div_by_zero_witness/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/div_by_zero_witness/Nargo.toml index 08dbe74f018..e4968f6182d 100644 --- a/tooling/nargo_cli/tests/compile_failure/div_by_zero_witness/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/div_by_zero_witness/Nargo.toml @@ -2,6 +2,5 @@ name = "div_by_zero_witness" type = "bin" authors = [""] -compiler_version = "0.10.3" [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_failure/dup_trait_implementation_4/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/dup_trait_implementation_4/Nargo.toml index 7c2c50884fe..18352cb34b5 100644 --- a/tooling/nargo_cli/tests/compile_failure/dup_trait_implementation_4/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/dup_trait_implementation_4/Nargo.toml @@ -2,6 +2,5 @@ name = "dup_trait_implementation_4" type = "bin" authors = [""] -compiler_version = "0.11.1" [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_failure/dup_trait_implementation_4/src/main.nr b/tooling/nargo_cli/tests/compile_failure/dup_trait_implementation_4/src/main.nr index b9f712ceff0..e03fe8b3eeb 100644 --- a/tooling/nargo_cli/tests/compile_failure/dup_trait_implementation_4/src/main.nr +++ b/tooling/nargo_cli/tests/compile_failure/dup_trait_implementation_4/src/main.nr @@ -2,5 +2,4 @@ mod module1; mod module2; mod module3; -fn main() { -} +fn main() {} diff --git a/tooling/nargo_cli/tests/compile_failure/dup_trait_implementation_5/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/dup_trait_implementation_5/Nargo.toml index b5bacc433f3..40b7c3d0269 100644 --- a/tooling/nargo_cli/tests/compile_failure/dup_trait_implementation_5/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/dup_trait_implementation_5/Nargo.toml @@ -2,6 +2,5 @@ name = "dup_trait_implementation_5" type = "bin" authors = [""] -compiler_version = "0.11.1" [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_failure/dup_trait_implementation_5/src/main.nr b/tooling/nargo_cli/tests/compile_failure/dup_trait_implementation_5/src/main.nr index 78e3867e4a1..b5719009898 100644 --- a/tooling/nargo_cli/tests/compile_failure/dup_trait_implementation_5/src/main.nr +++ b/tooling/nargo_cli/tests/compile_failure/dup_trait_implementation_5/src/main.nr @@ -3,5 +3,4 @@ mod module2; mod module3; mod module4; -fn main() { -} +fn main() {} diff --git a/tooling/nargo_cli/tests/compile_failure/dup_trait_items_1/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/dup_trait_items_1/Nargo.toml index d8b44af47c2..078a336c282 100644 --- a/tooling/nargo_cli/tests/compile_failure/dup_trait_items_1/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/dup_trait_items_1/Nargo.toml @@ -2,6 +2,4 @@ name = "dup_trait_items_1" type = "bin" authors = [""] -compiler_version = "0.15.0" - [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_failure/dup_trait_items_2/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/dup_trait_items_2/Nargo.toml index b37256a1292..41e1a3b3fd9 100644 --- a/tooling/nargo_cli/tests/compile_failure/dup_trait_items_2/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/dup_trait_items_2/Nargo.toml @@ -2,6 +2,4 @@ name = "dup_trait_items_2" type = "bin" authors = [""] -compiler_version = "0.15.0" - [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_failure/dup_trait_items_3/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/dup_trait_items_3/Nargo.toml index c9a0de11174..1388f3c83ee 100644 --- a/tooling/nargo_cli/tests/compile_failure/dup_trait_items_3/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/dup_trait_items_3/Nargo.toml @@ -2,6 +2,4 @@ name = "dup_trait_items_3" type = "bin" authors = [""] -compiler_version = "0.15.0" - [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_failure/dup_trait_items_4/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/dup_trait_items_4/Nargo.toml index 5e4af3a29ae..43e8096548b 100644 --- a/tooling/nargo_cli/tests/compile_failure/dup_trait_items_4/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/dup_trait_items_4/Nargo.toml @@ -2,6 +2,4 @@ name = "dup_trait_items_4" type = "bin" authors = [""] -compiler_version = "0.15.0" - [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_failure/dup_trait_items_5/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/dup_trait_items_5/Nargo.toml index 2d8c9aad7ec..0af8ef88cea 100644 --- a/tooling/nargo_cli/tests/compile_failure/dup_trait_items_5/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/dup_trait_items_5/Nargo.toml @@ -2,6 +2,4 @@ name = "dup_trait_items_5" type = "bin" authors = [""] -compiler_version = "0.15.0" - [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_failure/dup_trait_items_6/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/dup_trait_items_6/Nargo.toml index 5107c10b41d..dd5f13438ec 100644 --- a/tooling/nargo_cli/tests/compile_failure/dup_trait_items_6/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/dup_trait_items_6/Nargo.toml @@ -2,6 +2,4 @@ name = "dup_trait_items_6" type = "bin" authors = [""] -compiler_version = "0.15.0" - [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_failure/duplicate_declaration/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/duplicate_declaration/Nargo.toml index 56f65941b52..a4c82c70642 100644 --- a/tooling/nargo_cli/tests/compile_failure/duplicate_declaration/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/duplicate_declaration/Nargo.toml @@ -2,6 +2,5 @@ name = "duplicate_declaration" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_failure/duplicate_declaration/src/main.nr b/tooling/nargo_cli/tests/compile_failure/duplicate_declaration/src/main.nr index 09337e51c93..4803f2005c9 100644 --- a/tooling/nargo_cli/tests/compile_failure/duplicate_declaration/src/main.nr +++ b/tooling/nargo_cli/tests/compile_failure/duplicate_declaration/src/main.nr @@ -5,4 +5,4 @@ fn hello(x : Field) -> Field { fn hello(x : Field) -> Field { x -} \ No newline at end of file +} diff --git a/tooling/nargo_cli/tests/compile_failure/dyn_index_fail_nested_array/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/dyn_index_fail_nested_array/Nargo.toml index 52a547e8d7b..7f1c2c097a4 100644 --- a/tooling/nargo_cli/tests/compile_failure/dyn_index_fail_nested_array/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/dyn_index_fail_nested_array/Nargo.toml @@ -2,6 +2,5 @@ name = "dyn_index_fail_nested_array" type = "bin" authors = [""] -compiler_version = "0.11.1" [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_failure/dyn_index_fail_nested_array/src/main.nr b/tooling/nargo_cli/tests/compile_failure/dyn_index_fail_nested_array/src/main.nr index e26625457d9..9f2ae3a0618 100644 --- a/tooling/nargo_cli/tests/compile_failure/dyn_index_fail_nested_array/src/main.nr +++ b/tooling/nargo_cli/tests/compile_failure/dyn_index_fail_nested_array/src/main.nr @@ -5,4 +5,4 @@ struct Foo { fn main(mut x : [Foo; 3], y : pub Field) { assert(x[y + 2].a == 5); -} \ No newline at end of file +} diff --git a/tooling/nargo_cli/tests/compile_failure/dynamic_index_failure/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/dynamic_index_failure/Nargo.toml index c68615052c1..2c44a5356c3 100644 --- a/tooling/nargo_cli/tests/compile_failure/dynamic_index_failure/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/dynamic_index_failure/Nargo.toml @@ -2,6 +2,5 @@ name = "dynamic_index_failure" type = "bin" authors = [""] -compiler_version = "0.10.3" [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_failure/dynamic_index_failure/src/main.nr b/tooling/nargo_cli/tests/compile_failure/dynamic_index_failure/src/main.nr index 2665356ccd6..10d4d1f02d1 100644 --- a/tooling/nargo_cli/tests/compile_failure/dynamic_index_failure/src/main.nr +++ b/tooling/nargo_cli/tests/compile_failure/dynamic_index_failure/src/main.nr @@ -20,4 +20,4 @@ fn main(mut x: [u32; 5], z: Field) { // } // } // assert(x[idx] != 0); -} \ No newline at end of file +} diff --git a/tooling/nargo_cli/tests/compile_failure/field_modulo/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/field_modulo/Nargo.toml index f6bc2dd70e2..94934f13e56 100644 --- a/tooling/nargo_cli/tests/compile_failure/field_modulo/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/field_modulo/Nargo.toml @@ -2,6 +2,4 @@ name = "field_modulo" type = "bin" authors = [""] -compiler_version = "0.9.0" - [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_failure/field_modulo/src/main.nr b/tooling/nargo_cli/tests/compile_failure/field_modulo/src/main.nr index b27ba0892b3..a482b68806b 100644 --- a/tooling/nargo_cli/tests/compile_failure/field_modulo/src/main.nr +++ b/tooling/nargo_cli/tests/compile_failure/field_modulo/src/main.nr @@ -1,4 +1,3 @@ - fn main(x: Field) -> pub Field { x % 2 } diff --git a/tooling/nargo_cli/tests/compile_failure/integer_literal_overflow/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/integer_literal_overflow/Nargo.toml index f29ec0408ea..ed607023878 100644 --- a/tooling/nargo_cli/tests/compile_failure/integer_literal_overflow/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/integer_literal_overflow/Nargo.toml @@ -2,6 +2,4 @@ name = "integer_literal_overflow" type = "bin" authors = [""] -compiler_version = "0.16.0" - [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_failure/invalid_dependency_name/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/invalid_dependency_name/Nargo.toml index 69b56a2e7d0..99d184acdcf 100644 --- a/tooling/nargo_cli/tests/compile_failure/invalid_dependency_name/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/invalid_dependency_name/Nargo.toml @@ -2,7 +2,5 @@ name = "invalid_dependency_name" type = "bin" authors = [""] -compiler_version = "0.9.0" - [dependencies] bad_name = { path = "../../test_libraries/bad_name" } diff --git a/tooling/nargo_cli/tests/compile_failure/multiple_contracts/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/multiple_contracts/Nargo.toml index c71c86c664b..d6e4e632f95 100644 --- a/tooling/nargo_cli/tests/compile_failure/multiple_contracts/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/multiple_contracts/Nargo.toml @@ -2,6 +2,4 @@ name = "multiple_contracts" type = "contract" authors = [""] -compiler_version = "0.9.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/compile_failure/multiple_primary_attributes_fail/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/multiple_primary_attributes_fail/Nargo.toml index 7e699d4bbe0..9aa843d16dc 100644 --- a/tooling/nargo_cli/tests/compile_failure/multiple_primary_attributes_fail/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/multiple_primary_attributes_fail/Nargo.toml @@ -2,6 +2,4 @@ name = "multiple_primary_attributes_fail" type = "bin" authors = [""] -compiler_version = "0.9.0" - [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_failure/mutability_regression_2911/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/mutability_regression_2911/Nargo.toml index 5136fad35ce..05db8252f3b 100644 --- a/tooling/nargo_cli/tests/compile_failure/mutability_regression_2911/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/mutability_regression_2911/Nargo.toml @@ -2,6 +2,4 @@ name = "mutability_regression_2911" type = "bin" authors = [""] -compiler_version = "0.9.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/compile_failure/orphaned_trait_impl/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/orphaned_trait_impl/Nargo.toml index 47df960cc33..89f30bb1ba5 100644 --- a/tooling/nargo_cli/tests/compile_failure/orphaned_trait_impl/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/orphaned_trait_impl/Nargo.toml @@ -2,8 +2,6 @@ name = "orphaned_trait_impl" type = "bin" authors = [""] -compiler_version = "0.12.0" - [dependencies] crate1 = { path = "crate1" } crate2 = { path = "crate2" } diff --git a/tooling/nargo_cli/tests/compile_failure/orphaned_trait_impl/crate1/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/orphaned_trait_impl/crate1/Nargo.toml index b28e0e840c4..de1eddf2cf0 100644 --- a/tooling/nargo_cli/tests/compile_failure/orphaned_trait_impl/crate1/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/orphaned_trait_impl/crate1/Nargo.toml @@ -2,6 +2,4 @@ name = "crate1" type = "lib" authors = [""] -compiler_version = "0.12.0" - [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_failure/orphaned_trait_impl/crate2/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/orphaned_trait_impl/crate2/Nargo.toml index a90a5dcceea..c86c5edf51a 100644 --- a/tooling/nargo_cli/tests/compile_failure/orphaned_trait_impl/crate2/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/orphaned_trait_impl/crate2/Nargo.toml @@ -2,6 +2,4 @@ name = "crate2" type = "lib" authors = [""] -compiler_version = "0.12.0" - [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_failure/overflowing_assignment/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/overflowing_assignment/Nargo.toml index 25bdea70129..612e3e7aaf6 100644 --- a/tooling/nargo_cli/tests/compile_failure/overflowing_assignment/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/overflowing_assignment/Nargo.toml @@ -2,6 +2,4 @@ name = "overflowing_assignment" type = "bin" authors = [""] -compiler_version = "0.9.0" - [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_failure/overflowing_assignment/src/main.nr b/tooling/nargo_cli/tests/compile_failure/overflowing_assignment/src/main.nr index 78535a853a6..6b529103ca3 100644 --- a/tooling/nargo_cli/tests/compile_failure/overflowing_assignment/src/main.nr +++ b/tooling/nargo_cli/tests/compile_failure/overflowing_assignment/src/main.nr @@ -1,5 +1,5 @@ fn main() { let x:u8 = -1; let y:u8 = 300; - assert(x!=y); + assert(x != y); } diff --git a/tooling/nargo_cli/tests/compile_failure/overlapping_generic_impls/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/overlapping_generic_impls/Nargo.toml new file mode 100644 index 00000000000..a279bfb053a --- /dev/null +++ b/tooling/nargo_cli/tests/compile_failure/overlapping_generic_impls/Nargo.toml @@ -0,0 +1,5 @@ +[package] +name = "overlapping_generic_impls" +type = "bin" +authors = [""] +[dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_failure/overlapping_generic_impls/src/main.nr b/tooling/nargo_cli/tests/compile_failure/overlapping_generic_impls/src/main.nr new file mode 100644 index 00000000000..abf905ad71b --- /dev/null +++ b/tooling/nargo_cli/tests/compile_failure/overlapping_generic_impls/src/main.nr @@ -0,0 +1,7 @@ + +trait Trait { fn t(self); } + +impl Trait for T { fn t(self){} } +impl Trait for u32 { fn t(self){} } + +fn main() {} diff --git a/tooling/nargo_cli/tests/compile_failure/package_name_empty/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/package_name_empty/Nargo.toml index 7c4dbd0c994..88382674780 100644 --- a/tooling/nargo_cli/tests/compile_failure/package_name_empty/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/package_name_empty/Nargo.toml @@ -2,6 +2,4 @@ name = "" type = "bin" authors = [""] -compiler_version = "0.9.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/compile_failure/package_name_hyphen/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/package_name_hyphen/Nargo.toml index f8d0a85db4a..4882b83b8bf 100644 --- a/tooling/nargo_cli/tests/compile_failure/package_name_hyphen/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/package_name_hyphen/Nargo.toml @@ -2,6 +2,4 @@ name = "hyphenated-name" type = "bin" authors = [""] -compiler_version = "0.9.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/compile_failure/primary_attribute_struct/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/primary_attribute_struct/Nargo.toml index 872c8f2030d..7c5e7f70774 100644 --- a/tooling/nargo_cli/tests/compile_failure/primary_attribute_struct/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/primary_attribute_struct/Nargo.toml @@ -3,6 +3,5 @@ name = "primary_attribute_struct" type = "bin" authors = [""] -compiler_version = "0.11.1" [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_failure/radix_non_constant_length/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/radix_non_constant_length/Nargo.toml index b8b1a2417dc..349698cc32d 100644 --- a/tooling/nargo_cli/tests/compile_failure/radix_non_constant_length/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/radix_non_constant_length/Nargo.toml @@ -2,6 +2,5 @@ name = "radix_non_constant_length" type = "bin" authors = [""] -compiler_version = "0.10.2" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_failure/slice_access_failure/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/slice_access_failure/Nargo.toml index fee471dffd7..fc159b7efc1 100644 --- a/tooling/nargo_cli/tests/compile_failure/slice_access_failure/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/slice_access_failure/Nargo.toml @@ -2,6 +2,5 @@ name = "slice_access_failure" type = "bin" authors = [""] -compiler_version = "0.10.2" [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_failure/slice_insert_failure/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/slice_insert_failure/Nargo.toml index fc7eb87be49..5134032264c 100644 --- a/tooling/nargo_cli/tests/compile_failure/slice_insert_failure/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/slice_insert_failure/Nargo.toml @@ -2,6 +2,4 @@ name = "slice_insert_failure" type = "bin" authors = [""] -compiler_version = "0.12.0" - [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_failure/slice_insert_failure/src/main.nr b/tooling/nargo_cli/tests/compile_failure/slice_insert_failure/src/main.nr index dad80bff7ab..72918037c16 100644 --- a/tooling/nargo_cli/tests/compile_failure/slice_insert_failure/src/main.nr +++ b/tooling/nargo_cli/tests/compile_failure/slice_insert_failure/src/main.nr @@ -8,4 +8,4 @@ fn main(x : Field, y : pub Field) { } slice = slice.insert(10, 100); -} \ No newline at end of file +} diff --git a/tooling/nargo_cli/tests/compile_failure/slice_remove_failure/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/slice_remove_failure/Nargo.toml index 795a4d863cb..1e13dfe6483 100644 --- a/tooling/nargo_cli/tests/compile_failure/slice_remove_failure/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/slice_remove_failure/Nargo.toml @@ -2,6 +2,4 @@ name = "slice_remove_failure" type = "bin" authors = [""] -compiler_version = "0.12.0" - [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_failure/slice_remove_failure/src/main.nr b/tooling/nargo_cli/tests/compile_failure/slice_remove_failure/src/main.nr index 7c308488ae8..1cd335f4b34 100644 --- a/tooling/nargo_cli/tests/compile_failure/slice_remove_failure/src/main.nr +++ b/tooling/nargo_cli/tests/compile_failure/slice_remove_failure/src/main.nr @@ -8,4 +8,4 @@ fn main(x : Field, y : pub Field) { } let (removed_slice, removed_elem) = slice.remove(10); -} \ No newline at end of file +} diff --git a/tooling/nargo_cli/tests/compile_failure/trait_incorrect_generic_count/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/trait_incorrect_generic_count/Nargo.toml new file mode 100644 index 00000000000..379e964d70a --- /dev/null +++ b/tooling/nargo_cli/tests/compile_failure/trait_incorrect_generic_count/Nargo.toml @@ -0,0 +1,7 @@ +[package] +name = "trait_incorrect_generic_count" +type = "bin" +authors = [""] +compiler_version = ">=0.18.0" + +[dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_failure/trait_incorrect_generic_count/src/main.nr b/tooling/nargo_cli/tests/compile_failure/trait_incorrect_generic_count/src/main.nr new file mode 100644 index 00000000000..702c3153717 --- /dev/null +++ b/tooling/nargo_cli/tests/compile_failure/trait_incorrect_generic_count/src/main.nr @@ -0,0 +1,13 @@ + +fn main(){ + let x: u32 = 0; + x.trait_fn(); +} + +trait Trait { + fn trait_fn(x: T) -> T {} +} + +impl Trait for u32 { + fn trait_fn(x: A) -> A { x } +} diff --git a/tooling/nargo_cli/tests/compile_failure/workspace_fail/crates/a/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/workspace_fail/crates/a/Nargo.toml index 411f048a93b..8d0e1aca4a9 100644 --- a/tooling/nargo_cli/tests/compile_failure/workspace_fail/crates/a/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/workspace_fail/crates/a/Nargo.toml @@ -2,6 +2,4 @@ name = "a" type = "bin" authors = [""] -compiler_version = "0.8.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/compile_failure/workspace_fail/crates/b/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/workspace_fail/crates/b/Nargo.toml index 1af8ef961cc..f316511340f 100644 --- a/tooling/nargo_cli/tests/compile_failure/workspace_fail/crates/b/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/workspace_fail/crates/b/Nargo.toml @@ -2,6 +2,4 @@ name = "b" type = "bin" authors = [""] -compiler_version = "0.8.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/compile_failure/workspace_missing_toml/crates/b/Nargo.toml b/tooling/nargo_cli/tests/compile_failure/workspace_missing_toml/crates/b/Nargo.toml index 1af8ef961cc..f316511340f 100644 --- a/tooling/nargo_cli/tests/compile_failure/workspace_missing_toml/crates/b/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_failure/workspace_missing_toml/crates/b/Nargo.toml @@ -2,6 +2,4 @@ name = "b" type = "bin" authors = [""] -compiler_version = "0.8.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_contract/contract_with_impl/Nargo.toml b/tooling/nargo_cli/tests/compile_success_contract/contract_with_impl/Nargo.toml index 99340cf80b5..ed5e9ec0910 100644 --- a/tooling/nargo_cli/tests/compile_success_contract/contract_with_impl/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_contract/contract_with_impl/Nargo.toml @@ -2,7 +2,6 @@ name = "simple_contract" type = "contract" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_contract/non_entry_point_method/Nargo.toml b/tooling/nargo_cli/tests/compile_success_contract/non_entry_point_method/Nargo.toml index c17e430c703..fb1969acc43 100644 --- a/tooling/nargo_cli/tests/compile_success_contract/non_entry_point_method/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_contract/non_entry_point_method/Nargo.toml @@ -2,6 +2,5 @@ name = "no_entry_points" type = "contract" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_contract/non_entry_point_method/src/main.nr b/tooling/nargo_cli/tests/compile_success_contract/non_entry_point_method/src/main.nr index 5c7152029c9..f1b739e4b88 100644 --- a/tooling/nargo_cli/tests/compile_success_contract/non_entry_point_method/src/main.nr +++ b/tooling/nargo_cli/tests/compile_success_contract/non_entry_point_method/src/main.nr @@ -3,4 +3,4 @@ contract Foo { #[contract_library_method] fn has_mut(_context : &mut PlaceholderStruct) {} -} \ No newline at end of file +} diff --git a/tooling/nargo_cli/tests/compile_success_contract/simple_contract/Nargo.toml b/tooling/nargo_cli/tests/compile_success_contract/simple_contract/Nargo.toml index 99340cf80b5..ed5e9ec0910 100644 --- a/tooling/nargo_cli/tests/compile_success_contract/simple_contract/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_contract/simple_contract/Nargo.toml @@ -2,7 +2,6 @@ name = "simple_contract" type = "contract" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/attributes_multiple/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/attributes_multiple/Nargo.toml index 96b221d6c9b..78b0e5b7b18 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/attributes_multiple/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/attributes_multiple/Nargo.toml @@ -2,6 +2,5 @@ name = "attributes_multiple" type = "bin" authors = [""] -compiler_version = "0.10.5" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/attributes_multiple/src/main.nr b/tooling/nargo_cli/tests/compile_success_empty/attributes_multiple/src/main.nr index 46b761065ff..581fb989b4c 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/attributes_multiple/src/main.nr +++ b/tooling/nargo_cli/tests/compile_success_empty/attributes_multiple/src/main.nr @@ -1,8 +1,7 @@ - fn main() { another_func() } #[aztec(private)] #[internal] -fn another_func() {} \ No newline at end of file +fn another_func() {} diff --git a/tooling/nargo_cli/tests/compile_success_empty/attributes_struct/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/attributes_struct/Nargo.toml index 0f00e7d9c73..e05ccb8d925 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/attributes_struct/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/attributes_struct/Nargo.toml @@ -2,6 +2,5 @@ name = "attributes_struct" type = "bin" authors = [""] -compiler_version = "0.11.1" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/auto_deref/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/auto_deref/Nargo.toml index cc1c9a8d8f7..ed2a51c0fb0 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/auto_deref/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/auto_deref/Nargo.toml @@ -2,6 +2,4 @@ name = "auto_deref" type = "bin" authors = [""] -compiler_version = "0.16.0" - [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_success_empty/auto_deref/src/main.nr b/tooling/nargo_cli/tests/compile_success_empty/auto_deref/src/main.nr index e0b4a447fd0..d69aff7e0d4 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/auto_deref/src/main.nr +++ b/tooling/nargo_cli/tests/compile_success_empty/auto_deref/src/main.nr @@ -1,4 +1,3 @@ - fn main() { let a = &mut &mut &mut [1, 2, 3]; assert(a[0] == 1); diff --git a/tooling/nargo_cli/tests/compile_success_empty/brillig_cast/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/brillig_cast/Nargo.toml index 7c5aebabb95..cb5a7f3f2bd 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/brillig_cast/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/brillig_cast/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_cast" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/brillig_field_binary_operations/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/brillig_field_binary_operations/Nargo.toml index a8e7cd167d2..fb17e881f4c 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/brillig_field_binary_operations/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/brillig_field_binary_operations/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_field_binary_operations" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/brillig_field_binary_operations/src/main.nr b/tooling/nargo_cli/tests/compile_success_empty/brillig_field_binary_operations/src/main.nr index e7b0afccc3e..85002cef01d 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/brillig_field_binary_operations/src/main.nr +++ b/tooling/nargo_cli/tests/compile_success_empty/brillig_field_binary_operations/src/main.nr @@ -1,5 +1,5 @@ // Tests arithmetic operations on fields -fn main() { +fn main() { let x = 4; let y = 2; assert((x + y) == add(x, y)); @@ -22,4 +22,4 @@ unconstrained fn mul(x : Field, y : Field) -> Field { unconstrained fn div(x : Field, y : Field) -> Field { x / y -} \ No newline at end of file +} diff --git a/tooling/nargo_cli/tests/compile_success_empty/brillig_integer_binary_operations/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/brillig_integer_binary_operations/Nargo.toml index 09b851e7c5c..cd550ce0252 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/brillig_integer_binary_operations/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/brillig_integer_binary_operations/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_integer_binary_operations" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/brillig_modulo/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/brillig_modulo/Nargo.toml index b27417dba8f..7bac4a06607 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/brillig_modulo/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/brillig_modulo/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_modulo" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/brillig_modulo/src/main.nr b/tooling/nargo_cli/tests/compile_success_empty/brillig_modulo/src/main.nr index c2c15f88b91..57dc516bd97 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/brillig_modulo/src/main.nr +++ b/tooling/nargo_cli/tests/compile_success_empty/brillig_modulo/src/main.nr @@ -7,18 +7,16 @@ fn main() { assert(signed_modulo(5, 3) == 2); assert(signed_modulo(2, 3) == 2); - // See #3275. - // Commented out for now since the previous values which would overflow an i4 are now a compiler error. - // let minus_two: i4 = -2; // 14 - // let minus_three: i4 = -3; // 13 - // let minus_five: i4 = -5; // 11 + let minus_two: i4 = -2; // 14 + let minus_three: i4 = -3; // 13 + let minus_five: i4 = -5; // 11 - // // (5 / -3) * -3 + 2 = -1 * -3 + 2 = 3 + 2 = 5 - // assert(signed_modulo(5, minus_three) == 2); - // // (-5 / 3) * 3 - 2 = -1 * 3 - 2 = -3 - 2 = -5 - // assert(signed_modulo(minus_five, 3) == minus_two); - // // (-5 / -3) * -3 - 2 = 1 * -3 - 2 = -3 - 2 = -5 - // assert(signed_modulo(minus_five, minus_three) == minus_two); + // (5 / -3) * -3 + 2 = -1 * -3 + 2 = 3 + 2 = 5 + assert(signed_modulo(5, minus_three) == 2); + // (-5 / 3) * 3 - 2 = -1 * 3 - 2 = -3 - 2 = -5 + assert(signed_modulo(minus_five, 3) == minus_two); + // (-5 / -3) * -3 - 2 = 1 * -3 - 2 = -3 - 2 = -5 + assert(signed_modulo(minus_five, minus_three) == minus_two); } unconstrained fn modulo(x: u32, y: u32) -> u32 { diff --git a/tooling/nargo_cli/tests/compile_success_empty/brillig_to_bits/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/brillig_to_bits/Nargo.toml index 6c62900468a..a18b769550d 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/brillig_to_bits/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/brillig_to_bits/Nargo.toml @@ -2,6 +2,4 @@ name = "brillig_to_bits" type = "bin" authors = [""] -compiler_version = "0.7.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/brillig_to_bits/src/main.nr b/tooling/nargo_cli/tests/compile_success_empty/brillig_to_bits/src/main.nr index a2ab0d4bc5a..294da58f68a 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/brillig_to_bits/src/main.nr +++ b/tooling/nargo_cli/tests/compile_success_empty/brillig_to_bits/src/main.nr @@ -20,5 +20,4 @@ unconstrained fn main() { let le_bit = le_bits_x[3-i]; assert(be_bit == le_bit); } - } diff --git a/tooling/nargo_cli/tests/compile_success_empty/closure_explicit_types/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/closure_explicit_types/Nargo.toml index 0ff85ab80bb..86ddff27910 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/closure_explicit_types/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/closure_explicit_types/Nargo.toml @@ -2,6 +2,5 @@ name = "closure_explicit_types" type = "bin" authors = [""] -compiler_version = "0.10.3" [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_success_empty/closure_explicit_types/src/main.nr b/tooling/nargo_cli/tests/compile_success_empty/closure_explicit_types/src/main.nr index 133bc1b4206..b5008c5d6dd 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/closure_explicit_types/src/main.nr +++ b/tooling/nargo_cli/tests/compile_success_empty/closure_explicit_types/src/main.nr @@ -1,4 +1,3 @@ - fn ret_normal_lambda1() -> fn() -> Field { || 10 } @@ -70,10 +69,10 @@ fn main() { assert(accepts_closure3(|| y as u64 + z) == 70); let w = 50; - assert(add_results(|| 100, || x ) == 150); - assert(add_results(|| x + 100, || w + x ) == 250); + assert(add_results(|| 100, || x) == 150); + assert(add_results(|| x + 100, || w + x) == 250); - let arr = [1,2,3,4]; + let arr = [1, 2, 3, 4]; assert(map(arr, |n| n + 1) == [2, 3, 4, 5]); assert(map(arr, |n| n + x) == [51, 52, 53, 54]); diff --git a/tooling/nargo_cli/tests/compile_success_empty/comptime_recursion_regression/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/comptime_recursion_regression/Nargo.toml index 6ded8f92d55..74710a6ac2a 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/comptime_recursion_regression/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/comptime_recursion_regression/Nargo.toml @@ -2,6 +2,5 @@ name = "comptime_recursion_regression" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/comptime_sort/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/comptime_sort/Nargo.toml index 15221af78c8..7d215a22496 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/comptime_sort/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/comptime_sort/Nargo.toml @@ -2,6 +2,4 @@ name = "comptime_sort" type = "bin" authors = [""] -compiler_version = "0.6.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/comptime_sort/src/main.nr b/tooling/nargo_cli/tests/compile_success_empty/comptime_sort/src/main.nr index f8bd38654c0..a24a6ebaba6 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/comptime_sort/src/main.nr +++ b/tooling/nargo_cli/tests/compile_success_empty/comptime_sort/src/main.nr @@ -1,6 +1,5 @@ - fn main() { - let unsorted: [u8; 3] = [3,1,2]; + let unsorted: [u8; 3] = [3, 1, 2]; let sorted = unsorted.sort(); assert(sorted[0] == 1); assert(sorted[1] == 2); diff --git a/tooling/nargo_cli/tests/compile_success_empty/conditional_regression_547/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/conditional_regression_547/Nargo.toml index 2729aca911c..1a62c5af20c 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/conditional_regression_547/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/conditional_regression_547/Nargo.toml @@ -2,6 +2,5 @@ name = "conditional_regression_547" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/conditional_regression_547/src/main.nr b/tooling/nargo_cli/tests/compile_success_empty/conditional_regression_547/src/main.nr index 41ccbb00a2a..f97199288a4 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/conditional_regression_547/src/main.nr +++ b/tooling/nargo_cli/tests/compile_success_empty/conditional_regression_547/src/main.nr @@ -13,10 +13,5 @@ fn main(x: Field) -> pub Field { } fn safe_inverse(n: Field) -> Field { - if n == 0 { - 0 - } - else { - 1 / n - } + if n == 0 { 0 } else { 1 / n } } diff --git a/tooling/nargo_cli/tests/compile_success_empty/conditional_regression_579/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/conditional_regression_579/Nargo.toml index fab92005fba..b440cb26e46 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/conditional_regression_579/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/conditional_regression_579/Nargo.toml @@ -2,6 +2,5 @@ name = "conditional_regression_579" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/conditional_regression_to_bits/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/conditional_regression_to_bits/Nargo.toml index e886f083a6c..f2b13c4d547 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/conditional_regression_to_bits/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/conditional_regression_to_bits/Nargo.toml @@ -2,6 +2,5 @@ name = "conditional_regression_to_bits" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/ec_baby_jubjub/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/ec_baby_jubjub/Nargo.toml index 178be37f780..fdb0df17112 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/ec_baby_jubjub/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/ec_baby_jubjub/Nargo.toml @@ -3,6 +3,5 @@ name = "ec_baby_jubjub" description = "Baby Jubjub sanity checks" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/ec_baby_jubjub/src/main.nr b/tooling/nargo_cli/tests/compile_success_empty/ec_baby_jubjub/src/main.nr index 3372e969d4b..2060ac57e31 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/ec_baby_jubjub/src/main.nr +++ b/tooling/nargo_cli/tests/compile_success_empty/ec_baby_jubjub/src/main.nr @@ -13,39 +13,39 @@ use dep::std::ec::montcurve::curvegroup::Point as MG; fn main() { // This test only makes sense if Field is the right prime field. - if 21888242871839275222246405745257275088548364400416034343698204186575808495617 == 0 - { + if 21888242871839275222246405745257275088548364400416034343698204186575808495617 == 0 { // Define Baby Jubjub (ERC-2494) parameters in affine representation - let bjj_affine = AffineCurve::new(168700, 168696, Gaffine::new(995203441582195749578291179787384436505546430278305826713579947235728471134,5472060717959818805561601436314318772137091100104008585924551046643952123905)); + let bjj_affine = AffineCurve::new(168700, 168696, Gaffine::new( + 995203441582195749578291179787384436505546430278305826713579947235728471134, 5472060717959818805561601436314318772137091100104008585924551046643952123905 + )); // Test addition - let p1_affine = Gaffine::new(17777552123799933955779906779655732241715742912184938656739573121738514868268, 2626589144620713026669568689430873010625803728049924121243784502389097019475); - let p2_affine = Gaffine::new(16540640123574156134436876038791482806971768689494387082833631921987005038935, 20819045374670962167435360035096875258406992893633759881276124905556507972311); - - let p3_affine = bjj_affine.add(p1_affine, p2_affine); - assert( - p3_affine.eq(Gaffine::new( - 7916061937171219682591368294088513039687205273691143098332585753343424131937, - 14035240266687799601661095864649209771790948434046947201833777492504781204499 - )) + let p1_affine = Gaffine::new( + 17777552123799933955779906779655732241715742912184938656739573121738514868268, 2626589144620713026669568689430873010625803728049924121243784502389097019475 ); + let p2_affine = Gaffine::new( + 16540640123574156134436876038791482806971768689494387082833631921987005038935, 20819045374670962167435360035096875258406992893633759881276124905556507972311 + ); + + let p3_affine = bjj_affine.add(p1_affine, p2_affine); + assert(p3_affine.eq(Gaffine::new( + 7916061937171219682591368294088513039687205273691143098332585753343424131937, 14035240266687799601661095864649209771790948434046947201833777492504781204499 + ))); // Test scalar multiplication let p4_affine = bjj_affine.mul(2, p1_affine); - assert( - p4_affine.eq(Gaffine::new( - 6890855772600357754907169075114257697580319025794532037257385534741338397365, - 4338620300185947561074059802482547481416142213883829469920100239455078257889 - )) - ); - assert(p4_affine.eq(bjj_affine.bit_mul([0,1], p1_affine))); + assert(p4_affine.eq(Gaffine::new( + 6890855772600357754907169075114257697580319025794532037257385534741338397365, + 4338620300185947561074059802482547481416142213883829469920100239455078257889, + ))); + assert(p4_affine.eq(bjj_affine.bit_mul([0, 1], p1_affine))); // Test subtraction let p5_affine = bjj_affine.subtract(p3_affine, p3_affine); assert(p5_affine.eq(Gaffine::zero())); // Check that these points are on the curve - assert( + assert( bjj_affine.contains(bjj_affine.gen) & bjj_affine.contains(p1_affine) & bjj_affine.contains(p2_affine) & @@ -56,7 +56,6 @@ fn main() { // Test CurveGroup equivalents let bjj = bjj_affine.into_group(); // Baby Jubjub - let p1 = p1_affine.into_group(); let p2 = p2_affine.into_group(); let p3 = p3_affine.into_group(); @@ -68,21 +67,14 @@ fn main() { // Test scalar multiplication assert(p4.eq(bjj.mul(2, p1))); - assert(p4.eq(bjj.bit_mul([0,1], p1))); + assert(p4.eq(bjj.bit_mul([0, 1], p1))); // Test subtraction assert(G::zero().eq(bjj.subtract(p3, p3))); assert(p5.eq(G::zero())); // Check that these points are on the curve - assert( - bjj.contains(bjj.gen) & - bjj.contains(p1) & - bjj.contains(p2) & - bjj.contains(p3) & - bjj.contains(p4) & - bjj.contains(p5) - ); + assert(bjj.contains(bjj.gen) & bjj.contains(p1) & bjj.contains(p2) & bjj.contains(p3) & bjj.contains(p4) & bjj.contains(p5)); // Test SWCurve equivalents of the above // First the affine representation @@ -95,32 +87,18 @@ fn main() { let p5_swcurve_affine = bjj_affine.map_into_swcurve(p5_affine); // Addition - assert( - p3_swcurve_affine.eq( - bjj_swcurve_affine.add( - p1_swcurve_affine, - p2_swcurve_affine - ) - ) - ); + assert(p3_swcurve_affine.eq(bjj_swcurve_affine.add(p1_swcurve_affine, p2_swcurve_affine))); // Doubling assert(p4_swcurve_affine.eq(bjj_swcurve_affine.mul(2, p1_swcurve_affine))); - assert(p4_swcurve_affine.eq(bjj_swcurve_affine.bit_mul([0,1], p1_swcurve_affine))); + assert(p4_swcurve_affine.eq(bjj_swcurve_affine.bit_mul([0, 1], p1_swcurve_affine))); // Subtraction assert(SWGaffine::zero().eq(bjj_swcurve_affine.subtract(p3_swcurve_affine, p3_swcurve_affine))); assert(p5_swcurve_affine.eq(SWGaffine::zero())); // Check that these points are on the curve - assert( - bjj_swcurve_affine.contains(bjj_swcurve_affine.gen) & - bjj_swcurve_affine.contains(p1_swcurve_affine) & - bjj_swcurve_affine.contains(p2_swcurve_affine) & - bjj_swcurve_affine.contains(p3_swcurve_affine) & - bjj_swcurve_affine.contains(p4_swcurve_affine) & - bjj_swcurve_affine.contains(p5_swcurve_affine) - ); + assert(bjj_swcurve_affine.contains(bjj_swcurve_affine.gen) & bjj_swcurve_affine.contains(p1_swcurve_affine) & bjj_swcurve_affine.contains(p2_swcurve_affine) & bjj_swcurve_affine.contains(p3_swcurve_affine) & bjj_swcurve_affine.contains(p4_swcurve_affine) & bjj_swcurve_affine.contains(p5_swcurve_affine)); // Then the CurveGroup representation let bjj_swcurve = bjj.into_swcurve(); @@ -132,25 +110,18 @@ fn main() { let p5_swcurve = bjj.map_into_swcurve(p5); // Addition - assert(p3_swcurve.eq(bjj_swcurve.add(p1_swcurve,p2_swcurve))); + assert(p3_swcurve.eq(bjj_swcurve.add(p1_swcurve, p2_swcurve))); // Doubling assert(p4_swcurve.eq(bjj_swcurve.mul(2, p1_swcurve))); - assert(p4_swcurve.eq(bjj_swcurve.bit_mul([0,1], p1_swcurve))); + assert(p4_swcurve.eq(bjj_swcurve.bit_mul([0, 1], p1_swcurve))); // Subtraction assert(SWG::zero().eq(bjj_swcurve.subtract(p3_swcurve, p3_swcurve))); assert(p5_swcurve.eq(SWG::zero())); // Check that these points are on the curve - assert( - bjj_swcurve.contains(bjj_swcurve.gen) & - bjj_swcurve.contains(p1_swcurve) & - bjj_swcurve.contains(p2_swcurve) & - bjj_swcurve.contains(p3_swcurve) & - bjj_swcurve.contains(p4_swcurve) & - bjj_swcurve.contains(p5_swcurve) - ); + assert(bjj_swcurve.contains(bjj_swcurve.gen) & bjj_swcurve.contains(p1_swcurve) & bjj_swcurve.contains(p2_swcurve) & bjj_swcurve.contains(p3_swcurve) & bjj_swcurve.contains(p4_swcurve) & bjj_swcurve.contains(p5_swcurve)); // Test MontCurve conversions // First the affine representation @@ -167,21 +138,14 @@ fn main() { // Doubling assert(p4_montcurve_affine.eq(bjj_montcurve_affine.mul(2, p1_montcurve_affine))); - assert(p4_montcurve_affine.eq(bjj_montcurve_affine.bit_mul([0,1], p1_montcurve_affine))); + assert(p4_montcurve_affine.eq(bjj_montcurve_affine.bit_mul([0, 1], p1_montcurve_affine))); // Subtraction assert(MGaffine::zero().eq(bjj_montcurve_affine.subtract(p3_montcurve_affine, p3_montcurve_affine))); assert(p5_montcurve_affine.eq(MGaffine::zero())); // Check that these points are on the curve - assert( - bjj_montcurve_affine.contains(bjj_montcurve_affine.gen) & - bjj_montcurve_affine.contains(p1_montcurve_affine) & - bjj_montcurve_affine.contains(p2_montcurve_affine) & - bjj_montcurve_affine.contains(p3_montcurve_affine) & - bjj_montcurve_affine.contains(p4_montcurve_affine) & - bjj_montcurve_affine.contains(p5_montcurve_affine) - ); + assert(bjj_montcurve_affine.contains(bjj_montcurve_affine.gen) & bjj_montcurve_affine.contains(p1_montcurve_affine) & bjj_montcurve_affine.contains(p2_montcurve_affine) & bjj_montcurve_affine.contains(p3_montcurve_affine) & bjj_montcurve_affine.contains(p4_montcurve_affine) & bjj_montcurve_affine.contains(p5_montcurve_affine)); // Then the CurveGroup representation let bjj_montcurve = bjj.into_montcurve(); @@ -197,30 +161,27 @@ fn main() { // Doubling assert(p4_montcurve.eq(bjj_montcurve.mul(2, p1_montcurve))); - assert(p4_montcurve.eq(bjj_montcurve.bit_mul([0,1], p1_montcurve))); + assert(p4_montcurve.eq(bjj_montcurve.bit_mul([0, 1], p1_montcurve))); // Subtraction assert(MG::zero().eq(bjj_montcurve.subtract(p3_montcurve, p3_montcurve))); assert(p5_montcurve.eq(MG::zero())); // Check that these points are on the curve - assert( - bjj_montcurve.contains(bjj_montcurve.gen) & - bjj_montcurve.contains(p1_montcurve) & - bjj_montcurve.contains(p2_montcurve) & - bjj_montcurve.contains(p3_montcurve) & - bjj_montcurve.contains(p4_montcurve) & - bjj_montcurve.contains(p5_montcurve) - ); + assert(bjj_montcurve.contains(bjj_montcurve.gen) & bjj_montcurve.contains(p1_montcurve) & bjj_montcurve.contains(p2_montcurve) & bjj_montcurve.contains(p3_montcurve) & bjj_montcurve.contains(p4_montcurve) & bjj_montcurve.contains(p5_montcurve)); // Elligator 2 map-to-curve let ell2_pt_map = bjj_affine.elligator2_map(27); - assert(ell2_pt_map.eq(MGaffine::new(7972459279704486422145701269802978968072470631857513331988813812334797879121, 8142420778878030219043334189293412482212146646099536952861607542822144507872).into_tecurve())); + assert(ell2_pt_map.eq(MGaffine::new( + 7972459279704486422145701269802978968072470631857513331988813812334797879121, 8142420778878030219043334189293412482212146646099536952861607542822144507872 + ).into_tecurve())); // SWU map-to-curve - let swu_pt_map = bjj_affine.swu_map(5,27); - - assert(swu_pt_map.eq(bjj_affine.map_from_swcurve(SWGaffine::new(2162719247815120009132293839392097468339661471129795280520343931405114293888, 5341392251743377373758788728206293080122949448990104760111875914082289313973)))); - } + let swu_pt_map = bjj_affine.swu_map(5, 27); + + assert(swu_pt_map.eq(bjj_affine.map_from_swcurve(SWGaffine::new( + 2162719247815120009132293839392097468339661471129795280520343931405114293888, 5341392251743377373758788728206293080122949448990104760111875914082289313973 + )))); + } } diff --git a/tooling/nargo_cli/tests/compile_success_empty/generators/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/generators/Nargo.toml index 0f05b6e5759..58d8a993e16 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/generators/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/generators/Nargo.toml @@ -2,6 +2,5 @@ name = "generators" type = "bin" authors = [""] -compiler_version = "0.10.3" [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_success_empty/generators/src/main.nr b/tooling/nargo_cli/tests/compile_success_empty/generators/src/main.nr index 2f6f90a8c57..9a65c5fd3d2 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/generators/src/main.nr +++ b/tooling/nargo_cli/tests/compile_success_empty/generators/src/main.nr @@ -28,7 +28,7 @@ fn fibonacci_generator() -> fn[(&mut Field, &mut Field)]() -> Field { // we'll be able to un-hardcode the array length if we have the ::<> syntax proposed in https://github.com/noir-lang/noir/issues/2458 fn get_some(generator: fn[Env]() -> Field) -> [Field; 5] { - [0,0,0,0,0].map(|_| generator()) + [0, 0, 0, 0, 0].map(|_| generator()) } fn test_fib() { @@ -44,9 +44,9 @@ fn test_fib() { fn test_counter() { let counter = make_counter(); - assert(counter() == 1); - assert(counter() == 2); - assert(counter() == 3); + assert(counter() == 1); + assert(counter() == 2); + assert(counter() == 3); assert(get_some(counter) == [4, 5, 6, 7, 8]); } diff --git a/tooling/nargo_cli/tests/compile_success_empty/higher_order_fn_selector/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/higher_order_fn_selector/Nargo.toml index 09a0e342a71..968fc5300e6 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/higher_order_fn_selector/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/higher_order_fn_selector/Nargo.toml @@ -2,6 +2,4 @@ name = "higher_order_fn_selector" type = "bin" authors = [""] -compiler_version = "0.8.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/higher_order_fn_selector/src/main.nr b/tooling/nargo_cli/tests/compile_success_empty/higher_order_fn_selector/src/main.nr index e1a13919f4c..d3fd4d5f94a 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/higher_order_fn_selector/src/main.nr +++ b/tooling/nargo_cli/tests/compile_success_empty/higher_order_fn_selector/src/main.nr @@ -1,4 +1,3 @@ - fn g(x: &mut Field) -> () { *x *= 2; } @@ -8,11 +7,7 @@ fn h(x: &mut Field) -> () { } fn selector(flag: &mut bool) -> fn(&mut Field) -> () { - let my_func = if *flag { - g - } else { - h - }; + let my_func = if *flag { g } else { h }; // Flip the flag for the next function call *flag = !(*flag); @@ -20,7 +15,6 @@ fn selector(flag: &mut bool) -> fn(&mut Field) -> () { } fn main() { - let mut flag: bool = true; let mut x: Field = 100; @@ -34,5 +28,4 @@ fn main() { returned_func2(&mut y); assert(y == 300); - } diff --git a/tooling/nargo_cli/tests/execution_success/sha2_blocks/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/impl_with_where_clause/Nargo.toml similarity index 54% rename from tooling/nargo_cli/tests/execution_success/sha2_blocks/Nargo.toml rename to tooling/nargo_cli/tests/compile_success_empty/impl_with_where_clause/Nargo.toml index 9aa46c465e9..ef9bdce2640 100644 --- a/tooling/nargo_cli/tests/execution_success/sha2_blocks/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/impl_with_where_clause/Nargo.toml @@ -1,7 +1,6 @@ [package] -name = "sha2_blocks" +name = "impl_with_where_clause" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/impl_with_where_clause/src/main.nr b/tooling/nargo_cli/tests/compile_success_empty/impl_with_where_clause/src/main.nr new file mode 100644 index 00000000000..be9fe0b110d --- /dev/null +++ b/tooling/nargo_cli/tests/compile_success_empty/impl_with_where_clause/src/main.nr @@ -0,0 +1,29 @@ + +fn main() { + let array: [Field; 3] = [1, 2, 3]; + assert(array.eq(array)); + + // Ensure this still works if we have to infer the type of the integer literals + let array = [1, 2, 3]; + assert(array.eq(array)); +} + +trait Eq { + fn eq(self, other: Self) -> bool; +} + +impl Eq for [T; N] where T: Eq { + fn eq(self, other: Self) -> bool { + let mut ret = true; + for i in 0 .. self.len() { + ret &= self[i].eq(other[i]); + } + ret + } +} + +impl Eq for Field { + fn eq(self, other: Field) -> bool { + self == other + } +} diff --git a/tooling/nargo_cli/tests/compile_success_empty/inner_outer_cl/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/inner_outer_cl/Nargo.toml index 25722866d9b..073456fa7f6 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/inner_outer_cl/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/inner_outer_cl/Nargo.toml @@ -2,6 +2,5 @@ name = "inner_outer_cl" type = "bin" authors = [""] -compiler_version = "0.7.1" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/instruction_deduplication/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/instruction_deduplication/Nargo.toml index 615bc6254e2..4786a87ff65 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/instruction_deduplication/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/instruction_deduplication/Nargo.toml @@ -2,6 +2,4 @@ name = "instruction_deduplication" type = "bin" authors = [""] -compiler_version = "0.8.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/intrinsic_die/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/intrinsic_die/Nargo.toml index 60e0310eab2..539c536b944 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/intrinsic_die/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/intrinsic_die/Nargo.toml @@ -2,6 +2,4 @@ name = "intrinsic_die" type = "bin" authors = [""] -compiler_version = "0.6.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/intrinsic_die/src/main.nr b/tooling/nargo_cli/tests/compile_success_empty/intrinsic_die/src/main.nr index 08c5cce4034..c07c35d521a 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/intrinsic_die/src/main.nr +++ b/tooling/nargo_cli/tests/compile_success_empty/intrinsic_die/src/main.nr @@ -1,11 +1,9 @@ use dep::std; // This test checks that we perform dead-instruction-elimination on intrinsic functions. - fn main(x: Field) { let bytes = x.to_be_bytes(32); - - let hash = std::hash::pedersen([x]); - let _p1 = std::scalar_mul::fixed_base_embedded_curve(x, 0); + let hash = std::hash::pedersen_commitment([x]); + let _p1 = std::scalar_mul::fixed_base_embedded_curve(x, 0); } diff --git a/tooling/nargo_cli/tests/compile_success_empty/let_stmt/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/let_stmt/Nargo.toml index 45f9a53edeb..def6e33b39a 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/let_stmt/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/let_stmt/Nargo.toml @@ -2,6 +2,4 @@ name = "let_stmt" type = "bin" authors = [""] -compiler_version = "0.8.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/main_return/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/main_return/Nargo.toml index c4224b7e23c..793ae612730 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/main_return/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/main_return/Nargo.toml @@ -2,6 +2,5 @@ name = "main_return" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/numeric_generics/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/numeric_generics/Nargo.toml index c8a3ce73a5e..835c945c3b8 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/numeric_generics/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/numeric_generics/Nargo.toml @@ -2,6 +2,5 @@ name = "numeric_generics" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/option/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/option/Nargo.toml index 553efccd746..d9bec3c3096 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/option/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/option/Nargo.toml @@ -2,6 +2,4 @@ name = "option" type = "bin" authors = [""] -compiler_version = "0.7.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/option/src/main.nr b/tooling/nargo_cli/tests/compile_success_empty/option/src/main.nr index 22229014eef..1f879bd375f 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/option/src/main.nr +++ b/tooling/nargo_cli/tests/compile_success_empty/option/src/main.nr @@ -2,7 +2,6 @@ use dep::std::option::Option; fn main() { let ten = 10; // giving this a name, to ensure that the Option functions work with closures - let none = Option::none(); let some = Option::some(3); diff --git a/tooling/nargo_cli/tests/compile_success_empty/references_aliasing/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/references_aliasing/Nargo.toml index b95c3998483..0310e55ed7e 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/references_aliasing/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/references_aliasing/Nargo.toml @@ -2,6 +2,5 @@ name = "references_aliasing" type = "bin" authors = [""] -compiler_version = "0.5.1" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/regression_2099/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/regression_2099/Nargo.toml index 3e995a0acd6..6b9f9a24038 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/regression_2099/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/regression_2099/Nargo.toml @@ -2,6 +2,4 @@ name = "regression_2099" type = "bin" authors = [""] -compiler_version = "0.9.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/regression_2099/src/main.nr b/tooling/nargo_cli/tests/compile_success_empty/regression_2099/src/main.nr index b96e664dedf..ab74bd2c826 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/regression_2099/src/main.nr +++ b/tooling/nargo_cli/tests/compile_success_empty/regression_2099/src/main.nr @@ -11,11 +11,19 @@ use dep::std::ec::montcurve::curvegroup::Point as MG; fn main() { // Define Baby Jubjub (ERC-2494) parameters in affine representation - let bjj_affine = AffineCurve::new(168700, 168696, Gaffine::new(995203441582195749578291179787384436505546430278305826713579947235728471134,5472060717959818805561601436314318772137091100104008585924551046643952123905)); + let bjj_affine = AffineCurve::new(168700, 168696, Gaffine::new( + 995203441582195749578291179787384436505546430278305826713579947235728471134, 5472060717959818805561601436314318772137091100104008585924551046643952123905 + )); // Test addition - let p1_affine = Gaffine::new(17777552123799933955779906779655732241715742912184938656739573121738514868268, 2626589144620713026669568689430873010625803728049924121243784502389097019475); - let p2_affine = Gaffine::new(16540640123574156134436876038791482806971768689494387082833631921987005038935, 20819045374670962167435360035096875258406992893633759881276124905556507972311); + let p1_affine = Gaffine::new( + 17777552123799933955779906779655732241715742912184938656739573121738514868268, + 2626589144620713026669568689430873010625803728049924121243784502389097019475 + ); + let p2_affine = Gaffine::new( + 16540640123574156134436876038791482806971768689494387082833631921987005038935, + 20819045374670962167435360035096875258406992893633759881276124905556507972311 + ); let _p3_affine = bjj_affine.add(p1_affine, p2_affine); // Test SWCurve equivalents of the above @@ -25,13 +33,8 @@ fn main() { let p1_swcurve_affine = bjj_affine.map_into_swcurve(p1_affine); let p2_swcurve_affine = bjj_affine.map_into_swcurve(p2_affine); - let _p3_swcurve_affine_from_add = bjj_swcurve_affine.add( - p1_swcurve_affine, - p2_swcurve_affine - ); + let _p3_swcurve_affine_from_add = bjj_swcurve_affine.add(p1_swcurve_affine, p2_swcurve_affine); // Check that these points are on the curve - assert( - bjj_swcurve_affine.contains(p1_swcurve_affine) - ); + assert(bjj_swcurve_affine.contains(p1_swcurve_affine)); } diff --git a/tooling/nargo_cli/tests/compile_success_empty/ret_fn_ret_cl/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/ret_fn_ret_cl/Nargo.toml index 4e1b06d927f..4f778574417 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/ret_fn_ret_cl/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/ret_fn_ret_cl/Nargo.toml @@ -2,6 +2,5 @@ name = "ret_fn_ret_cl" type = "bin" authors = [""] -compiler_version = "0.7.1" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/ret_fn_ret_cl/src/main.nr b/tooling/nargo_cli/tests/compile_success_empty/ret_fn_ret_cl/src/main.nr index a368dc58529..13ac6c8d764 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/ret_fn_ret_cl/src/main.nr +++ b/tooling/nargo_cli/tests/compile_success_empty/ret_fn_ret_cl/src/main.nr @@ -17,7 +17,6 @@ fn ret_fn() -> fn(Field) -> Field { // }; // inner_closure // } - fn ret_lambda() -> fn(Field) -> Field { let cl = |z: Field| -> Field { z + 1 @@ -31,7 +30,6 @@ fn main(x : Field) { // let result_closure = ret_closure(); // assert(result_closure(x) == x + 1); - let result_lambda = ret_lambda(); assert(result_lambda(x) == x + 1); } diff --git a/tooling/nargo_cli/tests/compile_success_empty/simple_array_param/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/simple_array_param/Nargo.toml index 9874c8cb6a8..4f1811cc669 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/simple_array_param/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/simple_array_param/Nargo.toml @@ -2,6 +2,4 @@ name = "simple_array_param" type = "bin" authors = [""] -compiler_version = "0.6.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/simple_program_no_body/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/simple_program_no_body/Nargo.toml index f35a196ab59..13178336eea 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/simple_program_no_body/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/simple_program_no_body/Nargo.toml @@ -2,6 +2,5 @@ name = "simple_program_no_body" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/simple_program_no_body/src/main.nr b/tooling/nargo_cli/tests/compile_success_empty/simple_program_no_body/src/main.nr index b87f216b461..1c66955e126 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/simple_program_no_body/src/main.nr +++ b/tooling/nargo_cli/tests/compile_success_empty/simple_program_no_body/src/main.nr @@ -6,4 +6,4 @@ // // This program will never fail since there are // no assertions being applied. -fn main(_x : Field, _y : pub Field) {} \ No newline at end of file +fn main(_x : Field, _y : pub Field) {} diff --git a/tooling/nargo_cli/tests/compile_success_empty/simple_range/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/simple_range/Nargo.toml index 864cd03beb3..1db9099be7e 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/simple_range/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/simple_range/Nargo.toml @@ -2,6 +2,5 @@ name = "simple_range" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/simple_range/src/main.nr b/tooling/nargo_cli/tests/compile_success_empty/simple_range/src/main.nr index 9a4b9033493..38f95d99f9b 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/simple_range/src/main.nr +++ b/tooling/nargo_cli/tests/compile_success_empty/simple_range/src/main.nr @@ -1,6 +1,6 @@ // Tests a very simple program. // // The features being tested is casting to an integer -fn main(x : Field) { +fn main(x : Field) { let _z = x as u32; -} \ No newline at end of file +} diff --git a/tooling/nargo_cli/tests/compile_success_empty/specialization/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/specialization/Nargo.toml index df379491dc9..aaccd85a444 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/specialization/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/specialization/Nargo.toml @@ -2,6 +2,4 @@ name = "specialization" type = "bin" authors = [""] -compiler_version = "0.16.0" - [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_success_empty/specialization/src/main.nr b/tooling/nargo_cli/tests/compile_success_empty/specialization/src/main.nr index 32102ad1437..9cd32e0f1eb 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/specialization/src/main.nr +++ b/tooling/nargo_cli/tests/compile_success_empty/specialization/src/main.nr @@ -9,7 +9,7 @@ impl Foo { } fn main() { - let f1: Foo = Foo{}; - let f2: Foo = Foo{}; + let f1: Foo = Foo {}; + let f2: Foo = Foo {}; assert(f1.foo() + f2.foo() == 3); } diff --git a/tooling/nargo_cli/tests/compile_success_empty/str_as_bytes/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/str_as_bytes/Nargo.toml index 31f7ab5d9b4..6b9bbd9b65f 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/str_as_bytes/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/str_as_bytes/Nargo.toml @@ -2,6 +2,4 @@ name = "str_as_bytes" type = "bin" authors = [""] -compiler_version = "0.9.0" - [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_success_empty/str_as_bytes/src/main.nr b/tooling/nargo_cli/tests/compile_success_empty/str_as_bytes/src/main.nr index 6890b156b15..6fdd926ce7f 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/str_as_bytes/src/main.nr +++ b/tooling/nargo_cli/tests/compile_success_empty/str_as_bytes/src/main.nr @@ -2,17 +2,17 @@ use dep::std; fn main() { let a = "hello"; let b = a.as_bytes(); - assert(b[0]==104); - assert(b[1]==101); - assert(b[2]==108); - assert(b[3]==108); - assert(b[4]==111); - assert(b.len()==5); + assert(b[0] == 104); + assert(b[1] == 101); + assert(b[2] == 108); + assert(b[3] == 108); + assert(b[4] == 111); + assert(b.len() == 5); let mut c = a.as_bytes_vec(); - assert(c.get(0)==104); - assert(c.get(1)==101); - assert(c.get(2)==108); - assert(c.get(3)==108); - assert(c.get(4)==111); - assert(c.len()==5); + assert(c.get(0) == 104); + assert(c.get(1) == 101); + assert(c.get(2) == 108); + assert(c.get(3) == 108); + assert(c.get(4) == 111); + assert(c.len() == 5); } diff --git a/tooling/nargo_cli/tests/compile_success_empty/to_bits/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/to_bits/Nargo.toml index 9fe822eca93..ef47f3b4ba1 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/to_bits/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/to_bits/Nargo.toml @@ -2,6 +2,4 @@ name = "to_bits" type = "bin" authors = [""] -compiler_version = "0.7.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/to_bits/src/main.nr b/tooling/nargo_cli/tests/compile_success_empty/to_bits/src/main.nr index 65ff9dcac01..5da3ca9e060 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/to_bits/src/main.nr +++ b/tooling/nargo_cli/tests/compile_success_empty/to_bits/src/main.nr @@ -1,4 +1,3 @@ - fn main() { let field = 1000; let be_bits = field.to_be_bits(16); @@ -19,5 +18,4 @@ fn main() { let le_bit = le_bits_x[3-i]; assert(be_bit == le_bit); } - } diff --git a/tooling/nargo_cli/tests/compile_success_empty/trait_allowed_item_name_matches/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/trait_allowed_item_name_matches/Nargo.toml index 459cf96bab7..bd31596297a 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/trait_allowed_item_name_matches/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/trait_allowed_item_name_matches/Nargo.toml @@ -2,6 +2,4 @@ name = "trait_allowed_item_name_matches" type = "bin" authors = [""] -compiler_version = "0.15.0" - [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_success_empty/trait_associated_member_names_clashes/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/trait_associated_member_names_clashes/Nargo.toml index 585dcde7351..79d78c1aa51 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/trait_associated_member_names_clashes/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/trait_associated_member_names_clashes/Nargo.toml @@ -2,6 +2,4 @@ name = "trait_associated_member_names_clashes" type = "bin" authors = [""] -compiler_version = "0.16.0" - [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_success_empty/trait_default_implementation/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/trait_default_implementation/Nargo.toml index 7fcb4d0281e..938e224ec02 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/trait_default_implementation/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/trait_default_implementation/Nargo.toml @@ -2,6 +2,5 @@ name = "trait_default_implementation" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/trait_function_calls/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/trait_function_calls/Nargo.toml index 74be9decefc..1bb7522d6e1 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/trait_function_calls/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/trait_function_calls/Nargo.toml @@ -2,6 +2,4 @@ name = "trait_function_calls" type = "bin" authors = [""] -compiler_version = "0.15.0" - [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_success_empty/trait_generics/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/trait_generics/Nargo.toml new file mode 100644 index 00000000000..c1b5d0aaa6c --- /dev/null +++ b/tooling/nargo_cli/tests/compile_success_empty/trait_generics/Nargo.toml @@ -0,0 +1,6 @@ +[package] +name = "trait_generics" +type = "bin" +authors = [""] + +[dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/trait_generics/src/main.nr b/tooling/nargo_cli/tests/compile_success_empty/trait_generics/src/main.nr new file mode 100644 index 00000000000..504132eea8d --- /dev/null +++ b/tooling/nargo_cli/tests/compile_success_empty/trait_generics/src/main.nr @@ -0,0 +1,62 @@ + +struct Empty {} + +trait Foo { + fn foo(self) -> u32; +} + +impl Foo for Empty { + fn foo(_self: Self) -> u32 { 32 } +} + +impl Foo for Empty { + fn foo(_self: Self) -> u32 { 64 } +} + +fn main() { + let x: Empty = Empty {}; + let y: Empty = Empty {}; + let z = Empty {}; + + assert(x.foo() == 32); + assert(y.foo() == 64); + + // Types matching multiple impls will currently choose + // the first matching one instead of erroring + assert(z.foo() == 32); + + call_impl_with_generic_struct(); + call_impl_with_generic_function(); +} + +// Ensure we can call a generic impl +fn call_impl_with_generic_struct() { + let x: u8 = 7; + let y: i8 = 8; + let s2_u8 = S2 { x }; + let s2_i8 = S2 { x: y }; + assert(s2_u8.t2().x == 7); + assert(s2_i8.t2().x == 8); +} + +trait T2 { + fn t2(self) -> Self; +} + +struct S2 { x: T } + +impl T2 for S2 { + fn t2(self) -> Self { self } +} + +fn call_impl_with_generic_function() { + assert(3.t3(7) == 7); +} + +trait T3 { + fn t3(self, x: T) -> T; +} + +impl T3 for u32 { + fn t3(self, y: U) -> U { y } +} diff --git a/tooling/nargo_cli/tests/compile_success_empty/trait_multi_module_test/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/trait_multi_module_test/Nargo.toml index 89d83e18f66..efa176099cf 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/trait_multi_module_test/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/trait_multi_module_test/Nargo.toml @@ -2,6 +2,5 @@ name = "trait_multi_module_test" type = "bin" authors = [""] -compiler_version = "0.11.1" [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_success_empty/trait_override_implementation/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/trait_override_implementation/Nargo.toml index 7ab5a62b5ba..1ccf15adc14 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/trait_override_implementation/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/trait_override_implementation/Nargo.toml @@ -2,6 +2,5 @@ name = "trait_override_implementation" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/trait_override_implementation/src/main.nr b/tooling/nargo_cli/tests/compile_success_empty/trait_override_implementation/src/main.nr index f5f01c79ad6..763784f64e8 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/trait_override_implementation/src/main.nr +++ b/tooling/nargo_cli/tests/compile_success_empty/trait_override_implementation/src/main.nr @@ -4,9 +4,8 @@ trait Default { fn default(x: Field, y: Field) -> Self; fn method2(x: Field) -> Field { - x + x } - } struct Foo { @@ -20,7 +19,7 @@ impl Default for Foo { } fn method2(x: Field) -> Field { - x * 3 + x * 3 } } @@ -40,32 +39,39 @@ impl F for Bar { fn f3(self) -> Field { 30 } } -impl F for &mut Bar { - fn f1(self) -> Field { 101 } - fn f5(self) -> Field { 505 } -} + +// Impls on mutable references are temporarily disabled +// impl F for &mut Bar { +// fn f1(self) -> Field { 101 } +// fn f5(self) -> Field { 505 } +// } + fn main(x: Field) { let first = Foo::method2(x); assert(first == 3 * x); let bar = Bar{}; - assert(bar.f1() == 10); - assert(bar.f2() == 2); - assert(bar.f3() == 30); - assert(bar.f4() == 4); - assert(bar.f5() == 50); + + assert(bar.f1() == 10, "1"); + assert(bar.f2() == 2, "2"); + assert(bar.f3() == 30, "3"); + assert(bar.f4() == 4, "4"); + assert(bar.f5() == 50, "5"); let mut bar_mut = Bar{}; - assert((&mut bar_mut).f1() == 101); - assert((&mut bar_mut).f2() == 2); - assert((&mut bar_mut).f3() == 3); - assert((&mut bar_mut).f4() == 4); - assert((&mut bar_mut).f5() == 505); - - assert(bar_mut.f1() == 10); - assert(bar_mut.f2() == 2); - assert(bar_mut.f3() == 30); - assert(bar_mut.f4() == 4); - assert(bar_mut.f5() == 50); -} \ No newline at end of file + + // Impls on mutable references are temporarily disabled + // assert_eq((&mut bar_mut).f1(), 101); + // assert((&mut bar_mut).f2() == 2, "7"); + // assert((&mut bar_mut).f3() == 3, "8"); + // assert((&mut bar_mut).f4() == 4, "9"); + // assert((&mut bar_mut).f5() == 505, "10"); + + assert(bar_mut.f1() == 10, "10"); + assert(bar_mut.f2() == 2, "12"); + assert(bar_mut.f3() == 30, "13"); + assert(bar_mut.f4() == 4, "14"); + assert(bar_mut.f5() == 50, "15"); +} + diff --git a/tooling/nargo_cli/tests/compile_success_empty/trait_self/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/trait_self/Nargo.toml index 0dfaea44862..71c541ccd4f 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/trait_self/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/trait_self/Nargo.toml @@ -2,6 +2,5 @@ name = "trait_self" type = "bin" authors = [""] -compiler_version = "0.10.5" [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_success_empty/trait_self/trait_self/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/trait_self/trait_self/Nargo.toml index 0dfaea44862..71c541ccd4f 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/trait_self/trait_self/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/trait_self/trait_self/Nargo.toml @@ -2,6 +2,5 @@ name = "trait_self" type = "bin" authors = [""] -compiler_version = "0.10.5" [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_success_empty/trait_where_clause/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/trait_where_clause/Nargo.toml index 9f17579976b..1bbde8bfd79 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/trait_where_clause/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/trait_where_clause/Nargo.toml @@ -2,6 +2,5 @@ name = "trait_where_clause" type = "bin" authors = [""] -compiler_version = "0.11.1" [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_success_empty/traits/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/traits/Nargo.toml index 75fb80c4bfa..a33e8681807 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/traits/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/traits/Nargo.toml @@ -2,6 +2,5 @@ name = "traits" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/unary_operators/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/unary_operators/Nargo.toml index 65ad7c1c70c..8ab6f708b8a 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/unary_operators/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/unary_operators/Nargo.toml @@ -2,6 +2,5 @@ name = "unary_operators" type = "bin" authors = [""] -compiler_version = "0.10.3" [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/compile_success_empty/unconstrained_empty/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/unconstrained_empty/Nargo.toml index a42660e8bb7..48d0f5938d8 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/unconstrained_empty/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/unconstrained_empty/Nargo.toml @@ -2,6 +2,4 @@ name = "unconstrained_empty" type = "bin" authors = [""] -compiler_version = "0.6.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/unconstrained_empty/src/main.nr b/tooling/nargo_cli/tests/compile_success_empty/unconstrained_empty/src/main.nr index 6a3e59c5fed..5e5fb297236 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/unconstrained_empty/src/main.nr +++ b/tooling/nargo_cli/tests/compile_success_empty/unconstrained_empty/src/main.nr @@ -1,2 +1 @@ -unconstrained fn main() { -} +unconstrained fn main() {} diff --git a/tooling/nargo_cli/tests/compile_success_empty/unit/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/unit/Nargo.toml index 35fcd4bf339..7a15bd803c0 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/unit/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/unit/Nargo.toml @@ -2,6 +2,5 @@ name = "unit" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/unit/src/main.nr b/tooling/nargo_cli/tests/compile_success_empty/unit/src/main.nr index 2cb1f7d7c66..603829ec6db 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/unit/src/main.nr +++ b/tooling/nargo_cli/tests/compile_success_empty/unit/src/main.nr @@ -9,6 +9,10 @@ fn main() { } fn f1() {} -fn f2() { () } +fn f2() { + () +} fn f3() -> () {} -fn f4() -> () { () } +fn f4() -> () { + () +} diff --git a/tooling/nargo_cli/tests/compile_success_empty/unused_variables/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/unused_variables/Nargo.toml index 61456b3a320..1447f07d81d 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/unused_variables/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/unused_variables/Nargo.toml @@ -2,6 +2,5 @@ name = "unused_variables" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/compile_success_empty/unused_variables/src/main.nr b/tooling/nargo_cli/tests/compile_success_empty/unused_variables/src/main.nr index d0ffa8a0d91..5c27340caca 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/unused_variables/src/main.nr +++ b/tooling/nargo_cli/tests/compile_success_empty/unused_variables/src/main.nr @@ -1,3 +1 @@ -fn main(x : Field, y : pub Field) { - -} \ No newline at end of file +fn main(x : Field, y : pub Field) {} diff --git a/tooling/nargo_cli/tests/compile_success_empty/vectors/Nargo.toml b/tooling/nargo_cli/tests/compile_success_empty/vectors/Nargo.toml index f628d5e27e1..e4c3889c685 100644 --- a/tooling/nargo_cli/tests/compile_success_empty/vectors/Nargo.toml +++ b/tooling/nargo_cli/tests/compile_success_empty/vectors/Nargo.toml @@ -2,6 +2,5 @@ name = "vectors" type = "bin" authors = [""] -compiler_version = "0.7.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/1327_concrete_in_generic/Nargo.toml b/tooling/nargo_cli/tests/execution_success/1327_concrete_in_generic/Nargo.toml index 0ccf7ff8c9c..3adf969538c 100644 --- a/tooling/nargo_cli/tests/execution_success/1327_concrete_in_generic/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/1327_concrete_in_generic/Nargo.toml @@ -2,6 +2,4 @@ name = "1327_concrete_in_generic" type = "bin" authors = [""] -compiler_version = "0.6.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/1327_concrete_in_generic/src/main.nr b/tooling/nargo_cli/tests/execution_success/1327_concrete_in_generic/src/main.nr index 368d4811e45..5d139111c53 100644 --- a/tooling/nargo_cli/tests/execution_success/1327_concrete_in_generic/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/1327_concrete_in_generic/src/main.nr @@ -58,9 +58,7 @@ fn d_method(input: D) -> Field { } fn get_d_method_interface() -> MethodInterface { - MethodInterface { - some_method_on_t_d: d_method, - } + MethodInterface { some_method_on_t_d: d_method } } // --- diff --git a/tooling/nargo_cli/tests/execution_success/1_mul/Nargo.toml b/tooling/nargo_cli/tests/execution_success/1_mul/Nargo.toml index 29053e36f7c..a0fd8d98027 100644 --- a/tooling/nargo_cli/tests/execution_success/1_mul/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/1_mul/Nargo.toml @@ -2,6 +2,5 @@ name = "1_mul" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/2_div/Nargo.toml b/tooling/nargo_cli/tests/execution_success/2_div/Nargo.toml index 6b28c58bea2..f689c97f760 100644 --- a/tooling/nargo_cli/tests/execution_success/2_div/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/2_div/Nargo.toml @@ -2,6 +2,5 @@ name = "2_div" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/2_div/src/main.nr b/tooling/nargo_cli/tests/execution_success/2_div/src/main.nr index ff0dee755cc..e16cc5be229 100644 --- a/tooling/nargo_cli/tests/execution_success/2_div/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/2_div/src/main.nr @@ -2,6 +2,6 @@ fn main(mut x: u32, y: u32, z: u32) { let a = x % y; assert(x / y == z); - assert(a == x - z*y); + assert(a == x - z * y); assert((50 as u64) % (9 as u64) == 5); } diff --git a/tooling/nargo_cli/tests/execution_success/3_add/Nargo.toml b/tooling/nargo_cli/tests/execution_success/3_add/Nargo.toml index dca0a0d9931..0bd2caef024 100644 --- a/tooling/nargo_cli/tests/execution_success/3_add/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/3_add/Nargo.toml @@ -2,6 +2,5 @@ name = "3_add" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/3_add/src/main.nr b/tooling/nargo_cli/tests/execution_success/3_add/src/main.nr index 2884415b81a..480348dc1cf 100644 --- a/tooling/nargo_cli/tests/execution_success/3_add/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/3_add/src/main.nr @@ -4,5 +4,5 @@ fn main(mut x: u32, y: u32, z: u32) { assert(x == z); x *= 8; - assert(x>9); + assert(x > 9); } diff --git a/tooling/nargo_cli/tests/execution_success/4_sub/Nargo.toml b/tooling/nargo_cli/tests/execution_success/4_sub/Nargo.toml index 149c3a6f7e5..b282bfe6287 100644 --- a/tooling/nargo_cli/tests/execution_success/4_sub/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/4_sub/Nargo.toml @@ -2,6 +2,5 @@ name = "4_sub" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/5_over/Nargo.toml b/tooling/nargo_cli/tests/execution_success/5_over/Nargo.toml index a59347066c9..dd9a21b44bf 100644 --- a/tooling/nargo_cli/tests/execution_success/5_over/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/5_over/Nargo.toml @@ -2,6 +2,5 @@ name = "5_over" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/6/Nargo.toml b/tooling/nargo_cli/tests/execution_success/6/Nargo.toml index b0353fb6ae5..9774a5d8c47 100644 --- a/tooling/nargo_cli/tests/execution_success/6/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/6/Nargo.toml @@ -2,6 +2,5 @@ name = "6" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/6/src/main.nr b/tooling/nargo_cli/tests/execution_success/6/src/main.nr index 8b350de16c1..4cc8886df04 100644 --- a/tooling/nargo_cli/tests/execution_success/6/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/6/src/main.nr @@ -14,7 +14,7 @@ fn main(x: [u8; 5], result: pub [u8; 32]) { digest = std::hash::sha256(x); assert(digest == result); - let y = [12,45,78,41]; - let h = std::hash::mimc_bn254(y); - assert(h == 18226366069841799622585958305961373004333097209608110160936134895615261821931); + let y = [12, 45, 78, 41]; + let h = std::hash::mimc::mimc_bn254(y); + assert(h == 18226366069841799622585958305961373004333097209608110160936134895615261821931); } diff --git a/tooling/nargo_cli/tests/execution_success/6_array/Nargo.toml b/tooling/nargo_cli/tests/execution_success/6_array/Nargo.toml index 4a6d8e1f401..c75df3e468e 100644 --- a/tooling/nargo_cli/tests/execution_success/6_array/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/6_array/Nargo.toml @@ -2,6 +2,5 @@ name = "6_array" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/7/Nargo.toml b/tooling/nargo_cli/tests/execution_success/7/Nargo.toml index 9321253ec03..f69f89468d7 100644 --- a/tooling/nargo_cli/tests/execution_success/7/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/7/Nargo.toml @@ -2,6 +2,5 @@ name = "7" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/7_function/Nargo.toml b/tooling/nargo_cli/tests/execution_success/7_function/Nargo.toml index ea899378643..cec14ff7d6a 100644 --- a/tooling/nargo_cli/tests/execution_success/7_function/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/7_function/Nargo.toml @@ -2,6 +2,5 @@ name = "7_function" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/7_function/src/main.nr b/tooling/nargo_cli/tests/execution_success/7_function/src/main.nr index 8fd85fa31cf..32926171098 100644 --- a/tooling/nargo_cli/tests/execution_success/7_function/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/7_function/src/main.nr @@ -49,7 +49,7 @@ fn test3(x: [u8; 3]) -> [u8; 3] { } fn test_multiple(x: u32, y: u32) -> (u32, u32) { - (y,x) + (y, x) } fn test_multiple2() -> my_struct { @@ -71,11 +71,11 @@ struct my2 { } fn test_multiple4(s: my_struct) { - assert(s.a == s.b+2); + assert(s.a == s.b + 2); } fn test_multiple5(a: (u32, u32)) { - assert(a.0 == a.1+2); + assert(a.0 == a.1 + 2); } fn test_multiple6(a: my2, b: my_struct, c: (my2, my_struct)) { @@ -93,20 +93,17 @@ fn bar() -> [Field; 1] { } fn main(x: u32 , y: u32 , a: Field, arr1: [u32; 9], arr2: [u32; 9]) { - let mut ss: my_struct = my_struct { b: x, a: x+2, }; + let mut ss: my_struct = my_struct { b: x, a: x + 2 }; test_multiple4(ss); - test_multiple5((ss.a,ss.b)); - let my = my2 { - aa: ss, - bb: ss, - }; + test_multiple5((ss.a, ss.b)); + let my = my2 { aa: ss, bb: ss }; ss.a = 61; - test_multiple6(my, ss, (my,ss)); + test_multiple6(my, ss, (my, ss)); let my_block = { let mut ab = f2(a); ab = ab + a; - (x,ab) + (x, ab) }; assert(my_block.1 == 4); diff --git a/tooling/nargo_cli/tests/execution_success/arithmetic_binary_operations/Nargo.toml b/tooling/nargo_cli/tests/execution_success/arithmetic_binary_operations/Nargo.toml index 7bacc45d7d1..c9160aa2592 100644 --- a/tooling/nargo_cli/tests/execution_success/arithmetic_binary_operations/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/arithmetic_binary_operations/Nargo.toml @@ -2,6 +2,5 @@ name = "arithmetic_binary_operations" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/array_dynamic/Nargo.toml b/tooling/nargo_cli/tests/execution_success/array_dynamic/Nargo.toml index 17b38706704..25684b00377 100644 --- a/tooling/nargo_cli/tests/execution_success/array_dynamic/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/array_dynamic/Nargo.toml @@ -2,6 +2,5 @@ name = "array_dynamic" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/array_dynamic/src/main.nr b/tooling/nargo_cli/tests/execution_success/array_dynamic/src/main.nr index 14b6f7d3b85..dd732f37e9b 100644 --- a/tooling/nargo_cli/tests/execution_success/array_dynamic/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/array_dynamic/src/main.nr @@ -1,18 +1,18 @@ fn main(x: [u32; 5], mut z: u32, t: u32, index: [Field;5], index2: [Field;5], offset: Field, sublen: Field) { - let idx = (z - 5*t - 5) as Field; + let idx = (z - 5 * t - 5) as Field; //dynamic array test dyn_array(x, idx, idx - 3); //regression for issue 1283 let mut s = 0; - let x3 = [246,159,32,176,8]; + let x3 = [246, 159, 32, 176, 8]; for i in 0..5 { s += x3[index[i]]; } - assert(s!=0); + assert(s != 0); if 3 < (sublen as u32) { - assert(index[offset + 3] == index2[3]); + assert(index[offset + 3] == index2[3]); } } diff --git a/tooling/nargo_cli/tests/execution_success/array_eq/Nargo.toml b/tooling/nargo_cli/tests/execution_success/array_eq/Nargo.toml index 4a9bd6293c0..1020d4905b1 100644 --- a/tooling/nargo_cli/tests/execution_success/array_eq/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/array_eq/Nargo.toml @@ -2,6 +2,5 @@ name = "array_eq" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/array_eq/src/main.nr b/tooling/nargo_cli/tests/execution_success/array_eq/src/main.nr index d1771ed91a6..5bbd595898c 100644 --- a/tooling/nargo_cli/tests/execution_success/array_eq/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/array_eq/src/main.nr @@ -1,4 +1,4 @@ // Simple example of checking where two arrays are equal fn main(a: [Field; 32], b: [Field; 32]) { - assert(a == b); + assert(a == b); } diff --git a/tooling/nargo_cli/tests/execution_success/array_len/Nargo.toml b/tooling/nargo_cli/tests/execution_success/array_len/Nargo.toml index b54cea7cc17..24ac6ff7f13 100644 --- a/tooling/nargo_cli/tests/execution_success/array_len/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/array_len/Nargo.toml @@ -2,6 +2,5 @@ name = "array_len" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/array_neq/Nargo.toml b/tooling/nargo_cli/tests/execution_success/array_neq/Nargo.toml index 0539cceb542..2e4bbdf97ee 100644 --- a/tooling/nargo_cli/tests/execution_success/array_neq/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/array_neq/Nargo.toml @@ -2,6 +2,5 @@ name = "array_neq" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/array_neq/src/main.nr b/tooling/nargo_cli/tests/execution_success/array_neq/src/main.nr index be734dea368..a3e51dc5066 100644 --- a/tooling/nargo_cli/tests/execution_success/array_neq/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/array_neq/src/main.nr @@ -1,4 +1,4 @@ // Simple example of checking where two arrays are different fn main(a: [Field; 32], b: [Field; 32]) { - assert(a != b); + assert(a != b); } diff --git a/tooling/nargo_cli/tests/execution_success/array_sort/Nargo.toml b/tooling/nargo_cli/tests/execution_success/array_sort/Nargo.toml index f5f469c5a5f..28e9c65a0dc 100644 --- a/tooling/nargo_cli/tests/execution_success/array_sort/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/array_sort/Nargo.toml @@ -2,6 +2,4 @@ name = "array_sort" type = "bin" authors = [""] -compiler_version = "0.6.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/assert/Nargo.toml b/tooling/nargo_cli/tests/execution_success/assert/Nargo.toml index 17ed9362bef..7780d53459e 100644 --- a/tooling/nargo_cli/tests/execution_success/assert/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/assert/Nargo.toml @@ -2,6 +2,5 @@ name = "assert" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/assert_statement/Nargo.toml b/tooling/nargo_cli/tests/execution_success/assert_statement/Nargo.toml index 641cb1b00e0..c6a1daaed19 100644 --- a/tooling/nargo_cli/tests/execution_success/assert_statement/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/assert_statement/Nargo.toml @@ -2,6 +2,5 @@ name = "assert_statement" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/assign_ex/Nargo.toml b/tooling/nargo_cli/tests/execution_success/assign_ex/Nargo.toml index 2ca969eeb93..4ef7b3aa5a6 100644 --- a/tooling/nargo_cli/tests/execution_success/assign_ex/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/assign_ex/Nargo.toml @@ -2,6 +2,5 @@ name = "assign_ex" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/bit_and/Nargo.toml b/tooling/nargo_cli/tests/execution_success/bit_and/Nargo.toml index 71a98db6635..e9a28577079 100644 --- a/tooling/nargo_cli/tests/execution_success/bit_and/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/bit_and/Nargo.toml @@ -2,6 +2,5 @@ name = "bit_and" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/bit_and/src/main.nr b/tooling/nargo_cli/tests/execution_success/bit_and/src/main.nr index 35671abea63..8b5074d5a24 100644 --- a/tooling/nargo_cli/tests/execution_success/bit_and/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/bit_and/src/main.nr @@ -3,7 +3,7 @@ fn main(x : Field, y : Field) { let x_as_u8 = x as u8; let y_as_u8 = y as u8; - + assert((x_as_u8 & y_as_u8) == x_as_u8); //bitwise and with 1 bit: diff --git a/tooling/nargo_cli/tests/execution_success/bit_shifts_comptime/Nargo.toml b/tooling/nargo_cli/tests/execution_success/bit_shifts_comptime/Nargo.toml index 9b7aa319406..81272be4e98 100644 --- a/tooling/nargo_cli/tests/execution_success/bit_shifts_comptime/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/bit_shifts_comptime/Nargo.toml @@ -2,6 +2,5 @@ name = "bit_shifts_comptime" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/bit_shifts_comptime/src/main.nr b/tooling/nargo_cli/tests/execution_success/bit_shifts_comptime/src/main.nr index 209861e74fa..f46c7ea1ea8 100644 --- a/tooling/nargo_cli/tests/execution_success/bit_shifts_comptime/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/bit_shifts_comptime/src/main.nr @@ -3,21 +3,21 @@ fn main(x: u64) { let three: u64 = 3; // shifts on constant values - assert(two << 2 == 8); - assert((two << 3) / 8 == two); - assert((three >> 1) == 1); + assert(two << 2 == 8); + assert((two << 3) / 8 == two); + assert((three >> 1) == 1); // shifts on runtime values - assert(x << 1 == 128); - assert(x >> 2 == 16); + assert(x << 1 == 128); + assert(x >> 2 == 16); regression_2250(); } fn regression_2250() { let a: u1 = 1 >> 1; - assert(a == 0); + assert(a == 0); let b: u32 = 1 >> 32; - assert(b == 0); + assert(b == 0); } diff --git a/tooling/nargo_cli/tests/execution_success/bit_shifts_runtime/Nargo.toml b/tooling/nargo_cli/tests/execution_success/bit_shifts_runtime/Nargo.toml index 3f9058f1946..f60c7dbe658 100644 --- a/tooling/nargo_cli/tests/execution_success/bit_shifts_runtime/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/bit_shifts_runtime/Nargo.toml @@ -2,6 +2,5 @@ name = "bit_shifts_runtime" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/bit_shifts_runtime/src/main.nr b/tooling/nargo_cli/tests/execution_success/bit_shifts_runtime/src/main.nr index f4d9c3916a6..b415a573ad5 100644 --- a/tooling/nargo_cli/tests/execution_success/bit_shifts_runtime/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/bit_shifts_runtime/src/main.nr @@ -1,9 +1,9 @@ fn main(x: u64, y: u64) { // runtime shifts on compile-time known values - assert(64 << y == 128); - assert(64 >> y == 32); + assert(64 << y == 128); + assert(64 >> y == 32); // runtime shifts on runtime values - assert(x << y == 128); - assert(x >> y == 32); + assert(x << y == 128); + assert(x >> y == 32); } diff --git a/tooling/nargo_cli/tests/execution_success/bool_not/Nargo.toml b/tooling/nargo_cli/tests/execution_success/bool_not/Nargo.toml index c2521450344..fe42e1efa11 100644 --- a/tooling/nargo_cli/tests/execution_success/bool_not/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/bool_not/Nargo.toml @@ -2,6 +2,5 @@ name = "bool_not" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/bool_or/Nargo.toml b/tooling/nargo_cli/tests/execution_success/bool_or/Nargo.toml index a878c1acb38..e139a7a2947 100644 --- a/tooling/nargo_cli/tests/execution_success/bool_or/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/bool_or/Nargo.toml @@ -2,6 +2,5 @@ name = "bool_or" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/brillig_acir_as_brillig/Nargo.toml b/tooling/nargo_cli/tests/execution_success/brillig_acir_as_brillig/Nargo.toml index 42b3c71aad3..aef4fd56d4f 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_acir_as_brillig/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/brillig_acir_as_brillig/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_acir_as_brillig" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/brillig_arrays/Nargo.toml b/tooling/nargo_cli/tests/execution_success/brillig_arrays/Nargo.toml index abaa6680f84..a4433e380a9 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_arrays/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/brillig_arrays/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_arrays" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/brillig_assert/Nargo.toml b/tooling/nargo_cli/tests/execution_success/brillig_assert/Nargo.toml index c6a27b47e79..b7d9231ab75 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_assert/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/brillig_assert/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_assert" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/brillig_blake2s/Nargo.toml b/tooling/nargo_cli/tests/execution_success/brillig_blake2s/Nargo.toml index 8fc7df96fc3..a497b6f48cc 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_blake2s/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/brillig_blake2s/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_blake2s" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/brillig_calls/Nargo.toml b/tooling/nargo_cli/tests/execution_success/brillig_calls/Nargo.toml index 9b6b4bd357b..7cc53a33a8a 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_calls/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/brillig_calls/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_calls" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/brillig_calls_array/Nargo.toml b/tooling/nargo_cli/tests/execution_success/brillig_calls_array/Nargo.toml index 0c60f6218eb..e360f2d6338 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_calls_array/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/brillig_calls_array/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_calls_array" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/brillig_calls_conditionals/Nargo.toml b/tooling/nargo_cli/tests/execution_success/brillig_calls_conditionals/Nargo.toml index f99445381d3..1553cd525ff 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_calls_conditionals/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/brillig_calls_conditionals/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_calls_conditionals" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/brillig_conditional/Nargo.toml b/tooling/nargo_cli/tests/execution_success/brillig_conditional/Nargo.toml index 7432f303349..6a8be620fee 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_conditional/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/brillig_conditional/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_conditional" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/brillig_conditional/src/main.nr b/tooling/nargo_cli/tests/execution_success/brillig_conditional/src/main.nr index a3d92ab58e9..e77d4d9479e 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_conditional/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/brillig_conditional/src/main.nr @@ -6,9 +6,5 @@ fn main(x: Field) { } unconstrained fn conditional(x : bool) -> Field { - if x { - 4 - }else { - 5 - } + if x { 4 } else { 5 } } diff --git a/tooling/nargo_cli/tests/execution_success/brillig_ecdsa/Nargo.toml b/tooling/nargo_cli/tests/execution_success/brillig_ecdsa/Nargo.toml index 96ffe8f1c92..972dd9ce93b 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_ecdsa/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/brillig_ecdsa/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_ecdsa" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/brillig_fns_as_values/Nargo.toml b/tooling/nargo_cli/tests/execution_success/brillig_fns_as_values/Nargo.toml index fd94bfb3a60..decd9a9412a 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_fns_as_values/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/brillig_fns_as_values/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_fns_as_values" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/brillig_fns_as_values/src/main.nr b/tooling/nargo_cli/tests/execution_success/brillig_fns_as_values/src/main.nr index 5f8435825f6..d22959853b3 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_fns_as_values/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/brillig_fns_as_values/src/main.nr @@ -1,3 +1,5 @@ +use dep::std; + struct MyStruct { operation: fn (u32) -> u32, } @@ -5,9 +7,9 @@ struct MyStruct { fn main(x: u32) { assert(wrapper(increment, x) == x + 1); assert(wrapper(increment_acir, x) == x + 1); - assert(wrapper(decrement, x) == x - 1); + assert(wrapper(decrement, x) == std::wrapping_sub(x, 1)); assert(wrapper_with_struct(MyStruct { operation: increment }, x) == x + 1); - assert(wrapper_with_struct(MyStruct { operation: decrement }, x) == x - 1); + assert(wrapper_with_struct(MyStruct { operation: decrement }, x) == std::wrapping_sub(x, 1)); // https://github.com/noir-lang/noir/issues/1975 assert(increment(x) == x + 1); } diff --git a/tooling/nargo_cli/tests/execution_success/brillig_hash_to_field/Nargo.toml b/tooling/nargo_cli/tests/execution_success/brillig_hash_to_field/Nargo.toml index a7d75459f7e..7cfcc745f0d 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_hash_to_field/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/brillig_hash_to_field/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_hash_to_field" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/brillig_identity_function/Nargo.toml b/tooling/nargo_cli/tests/execution_success/brillig_identity_function/Nargo.toml index 1c7603a5660..8196884fe2b 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_identity_function/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/brillig_identity_function/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_identity_function" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/brillig_keccak/Nargo.toml b/tooling/nargo_cli/tests/execution_success/brillig_keccak/Nargo.toml index 358c7c63a60..8cacf2186b8 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_keccak/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/brillig_keccak/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_keccak" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/brillig_keccak/src/main.nr b/tooling/nargo_cli/tests/execution_success/brillig_keccak/src/main.nr index 46c2a59f6b6..38258af0adf 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_keccak/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/brillig_keccak/src/main.nr @@ -11,13 +11,13 @@ fn main(x: Field, result: [u8; 32]) { //#1399: variable meesage size let message_size = 4; - let hash_a = keccak256([1,2,3,4], message_size); - let hash_b = keccak256([1,2,3,4,0,0,0,0], message_size); + let hash_a = keccak256([1, 2, 3, 4], message_size); + let hash_b = keccak256([1, 2, 3, 4, 0, 0, 0, 0], message_size); assert(hash_a == hash_b); let message_size_big = 8; - let hash_c = keccak256([1,2,3,4,0,0,0,0], message_size_big); + let hash_c = keccak256([1, 2, 3, 4, 0, 0, 0, 0], message_size_big); assert(hash_a != hash_c); } diff --git a/tooling/nargo_cli/tests/execution_success/brillig_loop/Nargo.toml b/tooling/nargo_cli/tests/execution_success/brillig_loop/Nargo.toml index c43a806784a..1212397c4db 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_loop/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/brillig_loop/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_loop" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/brillig_nested_arrays/Nargo.toml b/tooling/nargo_cli/tests/execution_success/brillig_nested_arrays/Nargo.toml index 4ce5518efb5..c36c8a0a2bd 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_nested_arrays/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/brillig_nested_arrays/Nargo.toml @@ -2,6 +2,4 @@ name = "brillig_nested_arrays" type = "bin" authors = [""] -compiler_version = "0.6.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/brillig_nested_arrays/src/main.nr b/tooling/nargo_cli/tests/execution_success/brillig_nested_arrays/src/main.nr index e182585f5e5..d0a60ac0a58 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_nested_arrays/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/brillig_nested_arrays/src/main.nr @@ -13,16 +13,16 @@ unconstrained fn access_nested(notes: [MyNote; 2], x: Field, y: Field) -> Field } unconstrained fn create_inside_brillig(x: Field, y: Field) { - let header = Header { params: [1, 2, 3]}; - let note0 = MyNote { array: [1, 2], plain : 3, header }; - let note1 = MyNote { array: [4, 5], plain : 6, header }; + let header = Header { params: [1, 2, 3] }; + let note0 = MyNote { array: [1, 2], plain: 3, header }; + let note1 = MyNote { array: [4, 5], plain: 6, header }; assert(access_nested([note0, note1], x, y) == (2 + 4 + 3 + 1)); } fn main(x: Field, y: Field) { - let header = Header { params: [1, 2, 3]}; - let note0 = MyNote { array: [1, 2], plain : 3, header }; - let note1 = MyNote { array: [4, 5], plain : 6, header }; + let header = Header { params: [1, 2, 3] }; + let note0 = MyNote { array: [1, 2], plain: 3, header }; + let note1 = MyNote { array: [4, 5], plain: 6, header }; create_inside_brillig(x, y); assert(access_nested([note0, note1], x, y) == (2 + 4 + 3 + 1)); diff --git a/tooling/nargo_cli/tests/execution_success/brillig_nested_slices/Nargo.toml b/tooling/nargo_cli/tests/execution_success/brillig_nested_slices/Nargo.toml index 3a558b737d8..d84338cdbb4 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_nested_slices/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/brillig_nested_slices/Nargo.toml @@ -2,6 +2,4 @@ name = "brillig_nested_slices" type = "bin" authors = [""] -compiler_version = "0.6.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/brillig_not/Nargo.toml b/tooling/nargo_cli/tests/execution_success/brillig_not/Nargo.toml index 38a0872adfb..ef882ea8da0 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_not/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/brillig_not/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_not" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/brillig_oracle/Nargo.toml b/tooling/nargo_cli/tests/execution_success/brillig_oracle/Nargo.toml index 0b03be79ef8..13bd913cef7 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_oracle/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/brillig_oracle/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_oracle" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/brillig_pedersen/Nargo.toml b/tooling/nargo_cli/tests/execution_success/brillig_pedersen/Nargo.toml index f6f34dcc650..6327caa0a09 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_pedersen/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/brillig_pedersen/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_pedersen" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/brillig_pedersen/src/main.nr b/tooling/nargo_cli/tests/execution_success/brillig_pedersen/src/main.nr index dfa10c96663..1a793dd3f05 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_pedersen/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/brillig_pedersen/src/main.nr @@ -1,21 +1,24 @@ use dep::std; unconstrained fn main(x: Field, y: Field, salt: Field, out_x: Field, out_y: Field, out_hash: Field) { - let res = std::hash::pedersen_with_separator([x, y], 0); - assert(res[0] == out_x); - assert(res[1] == out_y); + let res = std::hash::pedersen_commitment_with_separator([x, y], 0); + assert(res.x == out_x); + assert(res.y == out_y); + + let res_hash = std::hash::pedersen_hash_with_separator([x, y], 0); assert_eq(res_hash, out_hash); - assert(res_hash != res[0]); + assert(res_hash != res.x); + - let raw_data = [x,y]; + let raw_data = [x, y]; let mut state = 0; for i in 0..(2 as u32) { state = state * 8 + raw_data[i]; } state += salt; - let hash = std::hash::pedersen_with_separator([state], 0); - assert(std::hash::pedersen_with_separator([43], 0)[0] == hash[0]); + let hash = std::hash::pedersen_commitment_with_separator([state], 0); + assert(std::hash::pedersen_commitment_with_separator([43], 0).x == hash.x); } diff --git a/tooling/nargo_cli/tests/execution_success/brillig_recursion/Nargo.toml b/tooling/nargo_cli/tests/execution_success/brillig_recursion/Nargo.toml index 32dd1a6c858..087eeefd5ac 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_recursion/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/brillig_recursion/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_recursion" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/brillig_recursion/src/main.nr b/tooling/nargo_cli/tests/execution_success/brillig_recursion/src/main.nr index 43d1034fbbf..ebfc48c9198 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_recursion/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/brillig_recursion/src/main.nr @@ -6,9 +6,5 @@ fn main(x: u32) { } unconstrained fn fibonacci(x : u32) -> u32 { - if x <= 1 { - x - } else { - fibonacci(x - 1) + fibonacci(x - 2) - } + if x <= 1 { x } else { fibonacci(x - 1) + fibonacci(x - 2) } } diff --git a/tooling/nargo_cli/tests/execution_success/brillig_references/Nargo.toml b/tooling/nargo_cli/tests/execution_success/brillig_references/Nargo.toml index 7f47fab9d9a..0f64b862ba0 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_references/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/brillig_references/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_references" type = "bin" authors = [""] -compiler_version = "0.5.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/brillig_references/src/main.nr b/tooling/nargo_cli/tests/execution_success/brillig_references/src/main.nr index 46372940bc8..4118e4216a1 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_references/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/brillig_references/src/main.nr @@ -18,12 +18,7 @@ unconstrained fn main(mut x: Field) { assert(**nested_allocations.y == 1); // Test nested struct allocations with a mutable reference to an array. - let mut c = C { - foo: 0, - bar: &mut C2 { - array: &mut [1, 2], - }, - }; + let mut c = C { foo: 0, bar: &mut C2 { array: &mut [1, 2] } }; *c.bar.array = [3, 4]; let arr: [Field; 2] = *c.bar.array; assert(arr[0] == 3); diff --git a/tooling/nargo_cli/tests/execution_success/brillig_scalar_mul/Nargo.toml b/tooling/nargo_cli/tests/execution_success/brillig_scalar_mul/Nargo.toml index a580584f7f9..eefd041b899 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_scalar_mul/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/brillig_scalar_mul/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_scalar_mul" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/brillig_scalar_mul/src/main.nr b/tooling/nargo_cli/tests/execution_success/brillig_scalar_mul/src/main.nr index b95a8d4ef4a..c85bc433a76 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_scalar_mul/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/brillig_scalar_mul/src/main.nr @@ -15,8 +15,8 @@ unconstrained fn main( priv_key = b; pub_x = b_pub_x; pub_y = b_pub_y; - } + } let res = std::scalar_mul::fixed_base_embedded_curve(priv_key, 0); - assert(res[0] == pub_x); - assert(res[1] == pub_y); + assert(res[0] == pub_x); + assert(res[1] == pub_y); } diff --git a/tooling/nargo_cli/tests/execution_success/brillig_schnorr/Nargo.toml b/tooling/nargo_cli/tests/execution_success/brillig_schnorr/Nargo.toml index 3defa68f561..1b598abbf74 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_schnorr/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/brillig_schnorr/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_schnorr" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/brillig_schnorr/src/main.nr b/tooling/nargo_cli/tests/execution_success/brillig_schnorr/src/main.nr index 4212839601f..f30299b8a7b 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_schnorr/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/brillig_schnorr/src/main.nr @@ -12,10 +12,10 @@ unconstrained fn main(message: [u8; 10], message_field: Field, pub_key_x: Field, // Is there ever a situation where someone would want // to ensure that a signature was invalid? // Check that passing a slice as the message is valid - let valid_signature = std::schnorr::verify_signature(pub_key_x,pub_key_y,signature, message_field_bytes); + let valid_signature = std::schnorr::verify_signature(pub_key_x, pub_key_y, signature, message_field_bytes); assert(valid_signature); // Check that passing an array as the message is valid - let valid_signature = std::schnorr::verify_signature(pub_key_x,pub_key_y,signature, message); + let valid_signature = std::schnorr::verify_signature(pub_key_x, pub_key_y, signature, message); assert(valid_signature); } diff --git a/tooling/nargo_cli/tests/execution_success/brillig_sha256/Nargo.toml b/tooling/nargo_cli/tests/execution_success/brillig_sha256/Nargo.toml index 6aebe1ed5ad..7140fa0fd0b 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_sha256/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/brillig_sha256/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_sha256" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/brillig_slices/Nargo.toml b/tooling/nargo_cli/tests/execution_success/brillig_slices/Nargo.toml index 51d81efb6ae..5f6caad088a 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_slices/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/brillig_slices/Nargo.toml @@ -2,6 +2,4 @@ name = "brillig_slices" type = "bin" authors = [""] -compiler_version = "0.6.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/brillig_to_be_bytes/Nargo.toml b/tooling/nargo_cli/tests/execution_success/brillig_to_be_bytes/Nargo.toml index 21c5104e6a8..df6c818c90f 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_to_be_bytes/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/brillig_to_be_bytes/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_to_be_bytes" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/brillig_to_bytes_integration/Nargo.toml b/tooling/nargo_cli/tests/execution_success/brillig_to_bytes_integration/Nargo.toml index 10c2abeee29..991f3d1e46c 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_to_bytes_integration/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/brillig_to_bytes_integration/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_to_bytes_integration" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/brillig_to_bytes_integration/src/main.nr b/tooling/nargo_cli/tests/execution_success/brillig_to_bytes_integration/src/main.nr index 775d1e512d9..bc1b96a40b5 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_to_bytes_integration/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/brillig_to_bytes_integration/src/main.nr @@ -6,7 +6,7 @@ unconstrained fn main(x : Field, _y: Field) { let be_byte_array = y.to_be_bytes(31); // The result of this byte array will be little-endian let le_byte_array = x.to_le_bytes(31); - + assert(le_byte_array[0] == 60); assert(le_byte_array[0] == be_byte_array[30]); assert(le_byte_array[1] == be_byte_array[29]); diff --git a/tooling/nargo_cli/tests/execution_success/brillig_to_le_bytes/Nargo.toml b/tooling/nargo_cli/tests/execution_success/brillig_to_le_bytes/Nargo.toml index e1ba633bff1..c2ce8ad01b5 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_to_le_bytes/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/brillig_to_le_bytes/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_to_le_bytes" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/brillig_top_level/Nargo.toml b/tooling/nargo_cli/tests/execution_success/brillig_top_level/Nargo.toml index 79686cab2ea..f74a2a82964 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_top_level/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/brillig_top_level/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_top_level" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/brillig_unitialised_arrays/Nargo.toml b/tooling/nargo_cli/tests/execution_success/brillig_unitialised_arrays/Nargo.toml index c7045d0b816..f23ecc787d0 100644 --- a/tooling/nargo_cli/tests/execution_success/brillig_unitialised_arrays/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/brillig_unitialised_arrays/Nargo.toml @@ -2,6 +2,5 @@ name = "brillig_unitialised_arrays" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/cast_bool/Nargo.toml b/tooling/nargo_cli/tests/execution_success/cast_bool/Nargo.toml index 65a878d776a..6571019494e 100644 --- a/tooling/nargo_cli/tests/execution_success/cast_bool/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/cast_bool/Nargo.toml @@ -2,6 +2,5 @@ name = "cast_bool" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/closures_mut_ref/Nargo.toml b/tooling/nargo_cli/tests/execution_success/closures_mut_ref/Nargo.toml index f70cde6f878..01936c7be65 100644 --- a/tooling/nargo_cli/tests/execution_success/closures_mut_ref/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/closures_mut_ref/Nargo.toml @@ -2,6 +2,4 @@ name = "closures_mut_ref" type = "bin" authors = [""] -compiler_version = "0.8.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/conditional_1/Nargo.toml b/tooling/nargo_cli/tests/execution_success/conditional_1/Nargo.toml index af1efa03e82..28ca01332df 100644 --- a/tooling/nargo_cli/tests/execution_success/conditional_1/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/conditional_1/Nargo.toml @@ -2,6 +2,5 @@ name = "conditional_1" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/conditional_1/src/main.nr b/tooling/nargo_cli/tests/execution_success/conditional_1/src/main.nr index 176106ba890..bd29f135082 100644 --- a/tooling/nargo_cli/tests/execution_success/conditional_1/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/conditional_1/src/main.nr @@ -40,7 +40,7 @@ fn main(a: u32, mut c: [u32; 4], x: [u8; 5], result: pub [u8; 32]) { //Test case for conditional with arrays from function parameters - let b = sort([1,2,3,4]); + let b = sort([1, 2, 3, 4]); assert(b[0] == 1); if a == 0 { @@ -51,7 +51,7 @@ fn main(a: u32, mut c: [u32; 4], x: [u8; 5], result: pub [u8; 32]) { c[0] = 1; c[1] = c[2] / a + 11 % a; let f1 = a as Field; - assert(10/f1 != 0); + assert(10 / f1 != 0); } assert(c[0] == 3); diff --git a/tooling/nargo_cli/tests/execution_success/conditional_2/Nargo.toml b/tooling/nargo_cli/tests/execution_success/conditional_2/Nargo.toml index 1401a715eef..153c5d38b99 100644 --- a/tooling/nargo_cli/tests/execution_success/conditional_2/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/conditional_2/Nargo.toml @@ -2,6 +2,5 @@ name = "conditional_2" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/conditional_2/src/main.nr b/tooling/nargo_cli/tests/execution_success/conditional_2/src/main.nr index 70237d4b638..c4d60d8b999 100644 --- a/tooling/nargo_cli/tests/execution_success/conditional_2/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/conditional_2/src/main.nr @@ -11,7 +11,7 @@ fn test3 (x: u8) { } fn test4() -> [u32; 4] { - let b: [u32; 4] = [1,2,3,4]; + let b: [u32; 4] = [1, 2, 3, 4]; b } diff --git a/tooling/nargo_cli/tests/execution_success/conditional_regression_421/Nargo.toml b/tooling/nargo_cli/tests/execution_success/conditional_regression_421/Nargo.toml index 9fddef0e86f..987b51ae126 100644 --- a/tooling/nargo_cli/tests/execution_success/conditional_regression_421/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/conditional_regression_421/Nargo.toml @@ -2,6 +2,5 @@ name = "conditional_regression_421" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/conditional_regression_421/src/main.nr b/tooling/nargo_cli/tests/execution_success/conditional_regression_421/src/main.nr index 60052c20610..5789afb76db 100644 --- a/tooling/nargo_cli/tests/execution_success/conditional_regression_421/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/conditional_regression_421/src/main.nr @@ -2,13 +2,9 @@ fn main(a: u32, mut c: [u32; 4]) { //Issue reported in #421 if a == c[0] { assert(c[0] == 0); - } else { - if a == c[1] { - assert(c[1] == 0); - } else { - if a == c[2] { - assert(c[2] == 0); - } - } + } else if a == c[1] { + assert(c[1] == 0); + } else if a == c[2] { + assert(c[2] == 0); } } diff --git a/tooling/nargo_cli/tests/execution_success/conditional_regression_661/Nargo.toml b/tooling/nargo_cli/tests/execution_success/conditional_regression_661/Nargo.toml index 902408f5d56..ed11341c5b0 100644 --- a/tooling/nargo_cli/tests/execution_success/conditional_regression_661/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/conditional_regression_661/Nargo.toml @@ -2,6 +2,5 @@ name = "conditional_regression_661" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/conditional_regression_661/src/main.nr b/tooling/nargo_cli/tests/execution_success/conditional_regression_661/src/main.nr index efdc1ddbce4..5d8734897d7 100644 --- a/tooling/nargo_cli/tests/execution_success/conditional_regression_661/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/conditional_regression_661/src/main.nr @@ -21,7 +21,7 @@ fn issue_661_foo(array: [u32;4], b:u32) ->[u32;1] { } fn issue_661_bar(a : [u32;4]) ->[u32;4] { - let mut b: [u32; 4] = [0;4]; + let mut b: [u32; 4] = [0; 4]; b[0]=a[0]+1; b } diff --git a/tooling/nargo_cli/tests/execution_success/conditional_regression_short_circuit/Nargo.toml b/tooling/nargo_cli/tests/execution_success/conditional_regression_short_circuit/Nargo.toml index 24c16982cc4..92f5a869bc4 100644 --- a/tooling/nargo_cli/tests/execution_success/conditional_regression_short_circuit/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/conditional_regression_short_circuit/Nargo.toml @@ -2,6 +2,5 @@ name = "conditional_regression_short_circuit" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/conditional_regression_short_circuit/src/main.nr b/tooling/nargo_cli/tests/execution_success/conditional_regression_short_circuit/src/main.nr index 57387ed5052..b119619990e 100644 --- a/tooling/nargo_cli/tests/execution_success/conditional_regression_short_circuit/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/conditional_regression_short_circuit/src/main.nr @@ -33,6 +33,6 @@ fn call_intrinsic(x: [u8; 5], result: [u8; 32]) { } fn test4() -> [u32; 4] { - let b: [u32; 4] = [1,2,3,4]; + let b: [u32; 4] = [1, 2, 3, 4]; b } diff --git a/tooling/nargo_cli/tests/execution_success/custom_entry/Nargo.toml b/tooling/nargo_cli/tests/execution_success/custom_entry/Nargo.toml index a8cc75072b1..35cf2e080c1 100644 --- a/tooling/nargo_cli/tests/execution_success/custom_entry/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/custom_entry/Nargo.toml @@ -3,6 +3,5 @@ name = "custom_entry" type = "bin" entry = "src/foobarbaz.nr" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/debug_logs/Nargo.toml b/tooling/nargo_cli/tests/execution_success/debug_logs/Nargo.toml index edc03c152cf..9550d50cf15 100644 --- a/tooling/nargo_cli/tests/execution_success/debug_logs/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/debug_logs/Nargo.toml @@ -2,6 +2,4 @@ name = "debug_logs" type = "bin" authors = [""] -compiler_version = "0.8.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/diamond_deps_0/Nargo.toml b/tooling/nargo_cli/tests/execution_success/diamond_deps_0/Nargo.toml index 6b1dd65ba32..8b75d71ae12 100644 --- a/tooling/nargo_cli/tests/execution_success/diamond_deps_0/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/diamond_deps_0/Nargo.toml @@ -2,7 +2,6 @@ name = "diamond_deps_0" type = "bin" authors = [""] -compiler_version = "0.7.1" [dependencies] dep1 = { path = "../../test_libraries/diamond_deps_1" } diff --git a/tooling/nargo_cli/tests/execution_success/distinct_keyword/Nargo.toml b/tooling/nargo_cli/tests/execution_success/distinct_keyword/Nargo.toml index b7de54ea5cc..3f1b1386ba7 100644 --- a/tooling/nargo_cli/tests/execution_success/distinct_keyword/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/distinct_keyword/Nargo.toml @@ -2,6 +2,5 @@ name = "distinct_keyword" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/double_verify_proof/Nargo.toml b/tooling/nargo_cli/tests/execution_success/double_verify_proof/Nargo.toml index 61aaabfcf5b..a4edd2e4288 100644 --- a/tooling/nargo_cli/tests/execution_success/double_verify_proof/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/double_verify_proof/Nargo.toml @@ -2,6 +2,4 @@ name = "double_verify_proof" type = "bin" authors = [""] -compiler_version = "0.6.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/double_verify_proof/src/main.nr b/tooling/nargo_cli/tests/execution_success/double_verify_proof/src/main.nr index c679730e3c0..92e8326a895 100644 --- a/tooling/nargo_cli/tests/execution_success/double_verify_proof/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/double_verify_proof/src/main.nr @@ -9,19 +9,11 @@ fn main( proof_b : [Field; 94], ) -> pub [Field; 16] { let output_aggregation_object_a = std::verify_proof( - verification_key.as_slice(), - proof.as_slice(), - public_inputs.as_slice(), - key_hash, - input_aggregation_object + verification_key.as_slice(), proof.as_slice(), public_inputs.as_slice(), key_hash, input_aggregation_object ); let output_aggregation_object = std::verify_proof( - verification_key.as_slice(), - proof_b.as_slice(), - public_inputs.as_slice(), - key_hash, - output_aggregation_object_a + verification_key.as_slice(), proof_b.as_slice(), public_inputs.as_slice(), key_hash, output_aggregation_object_a ); let mut output = [0; 16]; diff --git a/tooling/nargo_cli/tests/execution_success/ecdsa_secp256k1/Nargo.toml b/tooling/nargo_cli/tests/execution_success/ecdsa_secp256k1/Nargo.toml index 0f8111dc9f6..58fdf96f0e3 100644 --- a/tooling/nargo_cli/tests/execution_success/ecdsa_secp256k1/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/ecdsa_secp256k1/Nargo.toml @@ -3,6 +3,5 @@ name = "ecdsa_secp256k1" description = "ECDSA secp256k1 verification" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/ecdsa_secp256k1/src/main.nr b/tooling/nargo_cli/tests/execution_success/ecdsa_secp256k1/src/main.nr index 5af8008f291..38a6ebd13e5 100644 --- a/tooling/nargo_cli/tests/execution_success/ecdsa_secp256k1/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/ecdsa_secp256k1/src/main.nr @@ -3,8 +3,8 @@ use dep::std; fn main(message : [u8;38],hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { // Hash the message, since secp256k1 expects a hashed_message let expected = std::hash::sha256(message); - assert(hashed_message == expected); + assert(hashed_message == expected); let valid_signature = std::ecdsa_secp256k1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); + assert(valid_signature); } diff --git a/tooling/nargo_cli/tests/execution_success/ecdsa_secp256r1/Nargo.toml b/tooling/nargo_cli/tests/execution_success/ecdsa_secp256r1/Nargo.toml index 738b049060a..87e8d529566 100644 --- a/tooling/nargo_cli/tests/execution_success/ecdsa_secp256r1/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/ecdsa_secp256r1/Nargo.toml @@ -3,6 +3,5 @@ name = "ecdsa_secp256r1" description = "ECDSA secp256r1 verification" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/ecdsa_secp256r1/src/main.nr b/tooling/nargo_cli/tests/execution_success/ecdsa_secp256r1/src/main.nr index eda78cd81a6..840a401f109 100644 --- a/tooling/nargo_cli/tests/execution_success/ecdsa_secp256r1/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/ecdsa_secp256r1/src/main.nr @@ -2,5 +2,5 @@ use dep::std; fn main(hashed_message : [u8;32], pub_key_x : [u8;32], pub_key_y : [u8;32], signature : [u8;64]) { let valid_signature = std::ecdsa_secp256r1::verify_signature(pub_key_x, pub_key_y, signature, hashed_message); - assert(valid_signature); + assert(valid_signature); } diff --git a/tooling/nargo_cli/tests/execution_success/eddsa/Nargo.toml b/tooling/nargo_cli/tests/execution_success/eddsa/Nargo.toml index 039da3a7074..0f545c2febc 100644 --- a/tooling/nargo_cli/tests/execution_success/eddsa/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/eddsa/Nargo.toml @@ -3,6 +3,5 @@ name = "eddsa" description = "Eddsa verification" type = "bin" authors = [""] -compiler_version = "0.3.2" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/eddsa/src/main.nr b/tooling/nargo_cli/tests/execution_success/eddsa/src/main.nr index 870a20fe01a..724ff1a640c 100644 --- a/tooling/nargo_cli/tests/execution_success/eddsa/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/eddsa/src/main.nr @@ -12,9 +12,9 @@ fn main(msg: pub Field, _priv_key_a: Field, _priv_key_b: Field) { // Manually computed as fields can't use modulo. Importantantly the commitment is within // the subgroup order. Note that choice of hash is flexible for this step. - // let r_a = hash::pedersen([_priv_key_a, msg])[0] % bjj.suborder; // modulus computed manually + // let r_a = hash::pedersen_commitment([_priv_key_a, msg])[0] % bjj.suborder; // modulus computed manually let r_a = 1414770703199880747815475415092878800081323795074043628810774576767372531818; - // let r_b = hash::pedersen([_priv_key_b, msg])[0] % bjj.suborder; // modulus computed manually + // let r_b = hash::pedersen_commitment([_priv_key_b, msg])[0] % bjj.suborder; // modulus computed manually let r_b = 571799555715456644614141527517766533395606396271089506978608487688924659618; let r8_a = bjj.curve.mul(r_a, bjj.base8); @@ -37,7 +37,7 @@ fn main(msg: pub Field, _priv_key_a: Field, _priv_key_b: Field) { // ]); // let s_a = (r_a + _priv_key_a * h_a) % bjj.suborder; // modulus computed manually - let s_a = 30333430637424319196043722294837632681219980330991241982145549329256671548; + let s_a = 30333430637424319196043722294837632681219980330991241982145549329256671548; // let s_b = (r_b + _priv_key_b * h_b) % bjj.suborder; // modulus computed manually let s_b = 1646085314320208098241070054368798527940102577261034947654839408482102287019; diff --git a/tooling/nargo_cli/tests/execution_success/field_attribute/Nargo.toml b/tooling/nargo_cli/tests/execution_success/field_attribute/Nargo.toml index f625d7e41f2..37487d0043c 100644 --- a/tooling/nargo_cli/tests/execution_success/field_attribute/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/field_attribute/Nargo.toml @@ -2,6 +2,5 @@ name = "field_attribute" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/field_attribute/src/main.nr b/tooling/nargo_cli/tests/execution_success/field_attribute/src/main.nr index d6d71781899..dda83db40de 100644 --- a/tooling/nargo_cli/tests/execution_success/field_attribute/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/field_attribute/src/main.nr @@ -16,4 +16,4 @@ fn foo() -> u32 { #[field(bls12_381)] fn foo() -> u32 { 3 -} \ No newline at end of file +} diff --git a/tooling/nargo_cli/tests/execution_success/generics/Nargo.toml b/tooling/nargo_cli/tests/execution_success/generics/Nargo.toml index 18bdae1ab08..19c8ff28ec7 100644 --- a/tooling/nargo_cli/tests/execution_success/generics/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/generics/Nargo.toml @@ -2,6 +2,5 @@ name = "generics" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/global_consts/Nargo.toml b/tooling/nargo_cli/tests/execution_success/global_consts/Nargo.toml index 2452ad8edb3..3b4d6be2353 100644 --- a/tooling/nargo_cli/tests/execution_success/global_consts/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/global_consts/Nargo.toml @@ -2,6 +2,5 @@ name = "global_consts" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/global_consts/src/main.nr b/tooling/nargo_cli/tests/execution_success/global_consts/src/main.nr index 0c3a4fcd771..07d88cb2049 100644 --- a/tooling/nargo_cli/tests/execution_success/global_consts/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/global_consts/src/main.nr @@ -27,10 +27,10 @@ fn main(a: [Field; M + N - N], b: [Field; 30 + N / 2], c : pub [Field; foo::MAGI assert(test_struct.y[i] != NESTED[1][0].v); } - assert(N != M); + assert(N != M); let expected: u32 = 42; - assert(foo::TYPE_INFERRED == expected); + assert(foo::TYPE_INFERRED == expected); let mut y = 5; let mut x = M; @@ -40,30 +40,30 @@ fn main(a: [Field; M + N - N], b: [Field; 30 + N / 2], c : pub [Field; foo::MAGI y = i; } - assert(y == 24); - assert(x == 10); + assert(y == 24); + assert(x == 10); let q = multiplyByM(3); - assert(q == 96); + assert(q == 96); arrays_neq(a, b); let t: [Field; T_LEN] = [N, M]; - assert(t[1] == 32); + assert(t[1] == 32); - assert(15 == mysubmodule::my_helper()); + assert(15 == mysubmodule::my_helper()); let add_submodules_N = mysubmodule::N + foo::bar::N; - assert(15 == add_submodules_N); + assert(15 == add_submodules_N); let add_from_bar_N = mysubmodule::N + foo::bar::from_bar(1); - assert(15 == add_from_bar_N); + assert(15 == add_from_bar_N); // Example showing an array filled with (mysubmodule::N + 2) 0's let sugared = [0; mysubmodule::N + 2]; - assert(sugared[mysubmodule::N + 1] == 0); + assert(sugared[mysubmodule::N + 1] == 0); let arr: [Field; mysubmodule::N] = [N; 10]; - assert((arr[0] == 5) & (arr[9] == 5)); + assert((arr[0] == 5) & (arr[9] == 5)); foo::from_foo(d); baz::from_baz(c); @@ -74,7 +74,7 @@ fn multiplyByM(x: Field) -> Field { } fn arrays_neq(a: [Field; M], b: [Field; M]) { - assert(a != b); + assert(a != b); } mod mysubmodule { diff --git a/tooling/nargo_cli/tests/execution_success/hash_to_field/Nargo.toml b/tooling/nargo_cli/tests/execution_success/hash_to_field/Nargo.toml index d78b59118f9..a00a7bdc050 100644 --- a/tooling/nargo_cli/tests/execution_success/hash_to_field/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/hash_to_field/Nargo.toml @@ -2,6 +2,5 @@ name = "hash_to_field" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/hash_to_field/src/main.nr b/tooling/nargo_cli/tests/execution_success/hash_to_field/src/main.nr index ffc334179ee..2b7d59cd8b6 100644 --- a/tooling/nargo_cli/tests/execution_success/hash_to_field/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/hash_to_field/src/main.nr @@ -2,4 +2,4 @@ use dep::std; fn main(input : Field) -> pub Field { std::hash::hash_to_field([input]) -} +} \ No newline at end of file diff --git a/tooling/nargo_cli/tests/execution_success/higher_order_functions/Nargo.toml b/tooling/nargo_cli/tests/execution_success/higher_order_functions/Nargo.toml index 9dc419d1678..8f8a79e7e83 100644 --- a/tooling/nargo_cli/tests/execution_success/higher_order_functions/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/higher_order_functions/Nargo.toml @@ -2,6 +2,5 @@ name = "higher_order_functions" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/if_else_chain/Nargo.toml b/tooling/nargo_cli/tests/execution_success/if_else_chain/Nargo.toml index fc5fffa2185..2f0dc93d120 100644 --- a/tooling/nargo_cli/tests/execution_success/if_else_chain/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/if_else_chain/Nargo.toml @@ -2,6 +2,5 @@ name = "if_else_chain" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/if_else_chain/src/main.nr b/tooling/nargo_cli/tests/execution_success/if_else_chain/src/main.nr index 9fd5fbfd3d3..2705d5b3111 100644 --- a/tooling/nargo_cli/tests/execution_success/if_else_chain/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/if_else_chain/src/main.nr @@ -9,7 +9,7 @@ fn main(a: u32, mut c: [u32; 4]) { // expect to match this case assert(c[3] == 0); } else { - assert(c[0] == 10); + assert(c[0] == 10); } } diff --git a/tooling/nargo_cli/tests/execution_success/import/Nargo.toml b/tooling/nargo_cli/tests/execution_success/import/Nargo.toml index 858c2a29840..c92328f106c 100644 --- a/tooling/nargo_cli/tests/execution_success/import/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/import/Nargo.toml @@ -2,6 +2,5 @@ name = "import" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/import/src/main.nr b/tooling/nargo_cli/tests/execution_success/import/src/main.nr index cb6476480d8..b85ee74ff69 100644 --- a/tooling/nargo_cli/tests/execution_success/import/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/import/src/main.nr @@ -2,7 +2,7 @@ mod import; use crate::import::hello; fn main(x : Field, y : Field) { - let _k = dep::std::hash::pedersen([x]); + let _k = dep::std::hash::pedersen_commitment([x]); let _l = hello(x); assert(x != import::hello(y)); diff --git a/tooling/nargo_cli/tests/execution_success/integer_array_indexing/Nargo.toml b/tooling/nargo_cli/tests/execution_success/integer_array_indexing/Nargo.toml index 3cec63d465b..6e639b64f58 100644 --- a/tooling/nargo_cli/tests/execution_success/integer_array_indexing/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/integer_array_indexing/Nargo.toml @@ -2,6 +2,5 @@ name = "integer_array_indexing" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/keccak256/Nargo.toml b/tooling/nargo_cli/tests/execution_success/keccak256/Nargo.toml index ab1a04b7c07..7e48c3b342c 100644 --- a/tooling/nargo_cli/tests/execution_success/keccak256/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/keccak256/Nargo.toml @@ -2,6 +2,5 @@ name = "keccak256" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/keccak256/src/main.nr b/tooling/nargo_cli/tests/execution_success/keccak256/src/main.nr index 9bca6a7c1bf..511d668bc3d 100644 --- a/tooling/nargo_cli/tests/execution_success/keccak256/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/keccak256/src/main.nr @@ -10,13 +10,13 @@ fn main(x: Field, result: [u8; 32]) { //#1399: variable meesage size let message_size = 4; - let hash_a = std::hash::keccak256([1,2,3,4], message_size); - let hash_b = std::hash::keccak256([1,2,3,4,0,0,0,0], message_size); + let hash_a = std::hash::keccak256([1, 2, 3, 4], message_size); + let hash_b = std::hash::keccak256([1, 2, 3, 4, 0, 0, 0, 0], message_size); assert(hash_a == hash_b); let message_size_big = 8; - let hash_c = std::hash::keccak256([1,2,3,4,0,0,0,0], message_size_big); + let hash_c = std::hash::keccak256([1, 2, 3, 4, 0, 0, 0, 0], message_size_big); assert(hash_a != hash_c); } diff --git a/tooling/nargo_cli/tests/execution_success/main_bool_arg/Nargo.toml b/tooling/nargo_cli/tests/execution_success/main_bool_arg/Nargo.toml index 1a4e3657464..c1cedb6c657 100644 --- a/tooling/nargo_cli/tests/execution_success/main_bool_arg/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/main_bool_arg/Nargo.toml @@ -2,6 +2,5 @@ name = "main_bool_arg" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/merkle_insert/Nargo.toml b/tooling/nargo_cli/tests/execution_success/merkle_insert/Nargo.toml index 3eb97c30cac..f09458411d8 100644 --- a/tooling/nargo_cli/tests/execution_success/merkle_insert/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/merkle_insert/Nargo.toml @@ -2,6 +2,5 @@ name = "merkle_insert" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/merkle_insert/Prover.toml b/tooling/nargo_cli/tests/execution_success/merkle_insert/Prover.toml index 3f69ad1cffb..0656908c063 100644 --- a/tooling/nargo_cli/tests/execution_success/merkle_insert/Prover.toml +++ b/tooling/nargo_cli/tests/execution_success/merkle_insert/Prover.toml @@ -1,11 +1,11 @@ -old_root = "0x200fbe381993186866de8eb5a9cc33845de6b084be3ff67f6e34d35b8a786157" -old_leaf = "0x1cdcf02431ba623767fe389337d011df1048dcc24b98ed81cec97627bab454a0" +old_root = "0x2131c74af6250d1246797588ff075b672e3d2e6805f9c6b313ade8f6b9e12802" +old_leaf = "0x2df8b940e5890e4e1377e05373fae69a1d754f6935e6a780b666947431f2cdcd" old_hash_path = [ - "0x1cdcf02431ba623767fe389337d011df1048dcc24b98ed81cec97627bab454a0", - "0x0b5e9666e7323ce925c28201a97ddf4144ac9d148448ed6f49f9008719c1b85b", - "0x22ec636f8ad30ef78c42b7fe2be4a4cacf5a445cfb5948224539f59a11d70775", + "0x03542cb720369f19a74fd05b4edfbedb27a78514ad3283f1b3270a1656cced8e", + "0x1278272f6e617666b18c52349c4bbe94249a8ab59add2ee0a142168a92b7ffc2", + "0x2547cfd7699ad1f331fb77b30a3445c6043a4c62b5b1215356b2924607bf937b", ] -new_root = "0x029ead881a6684995190589a67874f188f33a433211df82f56c1351c96530387" -leaf = "0x085ca53be9c9d95b57e6e5fc91c5d531ad9e63e85dd71af7e35562991774b435" +new_root = "0x25e2a8ee5b85e5b546ae27832b9b53f5fae5b371e3e7f8cddda839f41669fc68" +leaf = "0x23fe6c8f2426b793f0f156f57efbecbea52e951af761634a85e80cc1a9fb5003" index = "0" mimc_input = [12, 45, 78, 41] diff --git a/tooling/nargo_cli/tests/execution_success/merkle_insert/src/main.nr b/tooling/nargo_cli/tests/execution_success/merkle_insert/src/main.nr index 3de10520037..87b8533c274 100644 --- a/tooling/nargo_cli/tests/execution_success/merkle_insert/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/merkle_insert/src/main.nr @@ -1,4 +1,5 @@ use dep::std; +use dep::std::hash::mimc; fn main( old_root: Field, @@ -14,7 +15,7 @@ fn main( let calculated_root = std::merkle::compute_merkle_root(leaf, index, old_hash_path); assert(new_root == calculated_root); - let h = std::hash::mimc_bn254(mimc_input); + let h = mimc::mimc_bn254(mimc_input); // Regression test for PR #891 std::println(h); assert(h == 18226366069841799622585958305961373004333097209608110160936134895615261821931); diff --git a/tooling/nargo_cli/tests/execution_success/mock_oracle/Nargo.toml b/tooling/nargo_cli/tests/execution_success/mock_oracle/Nargo.toml index f626c2967cc..b2916487e8c 100644 --- a/tooling/nargo_cli/tests/execution_success/mock_oracle/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/mock_oracle/Nargo.toml @@ -2,6 +2,5 @@ name = "mock_oracle" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/mock_oracle/src/main.nr b/tooling/nargo_cli/tests/execution_success/mock_oracle/src/main.nr index 07553f05d6c..90fca7993cc 100644 --- a/tooling/nargo_cli/tests/execution_success/mock_oracle/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/mock_oracle/src/main.nr @@ -9,12 +9,9 @@ struct Point { unconstrained fn foo_oracle(_point: Point, _array: [Field; 4]) -> Field {} unconstrained fn main() { - let array = [1,2,3,4]; - let another_array = [4,3,2,1]; - let point = Point { - x: 14, - y: 27, - }; + let array = [1, 2, 3, 4]; + let another_array = [4, 3, 2, 1]; + let point = Point { x: 14, y: 27 }; OracleMock::mock("foo").returns(42).times(1); let mock = OracleMock::mock("foo").returns(0); diff --git a/tooling/nargo_cli/tests/execution_success/modules/Nargo.toml b/tooling/nargo_cli/tests/execution_success/modules/Nargo.toml index b4f9b469ea8..ab1d6e962d7 100644 --- a/tooling/nargo_cli/tests/execution_success/modules/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/modules/Nargo.toml @@ -2,6 +2,5 @@ name = "modules" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/modules_more/Nargo.toml b/tooling/nargo_cli/tests/execution_success/modules_more/Nargo.toml index 5acf61a71a7..bfcfe08fa79 100644 --- a/tooling/nargo_cli/tests/execution_success/modules_more/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/modules_more/Nargo.toml @@ -2,6 +2,5 @@ name = "modules_more" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/modulus/Nargo.toml b/tooling/nargo_cli/tests/execution_success/modulus/Nargo.toml index 5a1309a2a9d..256eeef058f 100644 --- a/tooling/nargo_cli/tests/execution_success/modulus/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/modulus/Nargo.toml @@ -2,6 +2,5 @@ name = "modulus" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/nested_array_dynamic/Nargo.toml b/tooling/nargo_cli/tests/execution_success/nested_array_dynamic/Nargo.toml index 5be06d0f8af..72642bebc15 100644 --- a/tooling/nargo_cli/tests/execution_success/nested_array_dynamic/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/nested_array_dynamic/Nargo.toml @@ -2,6 +2,5 @@ name = "nested_array_dynamic" type = "bin" authors = [""] -compiler_version = "0.11.1" [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/execution_success/nested_array_dynamic/src/main.nr b/tooling/nargo_cli/tests/execution_success/nested_array_dynamic/src/main.nr index 5538c08d778..cd10b5e7347 100644 --- a/tooling/nargo_cli/tests/execution_success/nested_array_dynamic/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/nested_array_dynamic/src/main.nr @@ -38,7 +38,7 @@ fn main(mut x : [Foo; 4], y : pub Field) { x[y - 1].b = [100, 101, 102]; } assert(x[2].b == [100, 101, 102]); - + assert(x[y - 3].bar.inner == [100, 101, 102]); assert(x[y - 2].bar.inner == [103, 104, 105]); assert(x[y - 1].bar.inner == [106, 107, 108]); @@ -52,7 +52,7 @@ fn main(mut x : [Foo; 4], y : pub Field) { assert(foo_parents[y - 3].foos[y - 2].b == [5, 6, 21]); assert(foo_parents[y - 3].foos[y - 1].b == [100, 101, 102]); assert(foo_parents[y - 3].foos[y].b == [11, 12, 23]); - + assert(foo_parents[y - 3].foos[y].a == 50); assert(foo_parents[1].foos[1].b == [5, 6, 21]); @@ -74,6 +74,5 @@ fn main(mut x : [Foo; 4], y : pub Field) { // Set a dynamic array value foo_parents[y - 2].foos[y - 3].b = foo_parents[y - 2].foos[y - 2].b; assert(foo_parents[1].foos[0].b == [20, 19, 5000]); - } diff --git a/tooling/nargo_cli/tests/execution_success/nested_arrays_from_brillig/Nargo.toml b/tooling/nargo_cli/tests/execution_success/nested_arrays_from_brillig/Nargo.toml index bd5dfb8bef4..02d2e6e6a4e 100644 --- a/tooling/nargo_cli/tests/execution_success/nested_arrays_from_brillig/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/nested_arrays_from_brillig/Nargo.toml @@ -2,6 +2,4 @@ name = "nested_arrays_from_brillig" type = "bin" authors = [""] -compiler_version = "0.6.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/nested_arrays_from_brillig/src/main.nr b/tooling/nargo_cli/tests/execution_success/nested_arrays_from_brillig/src/main.nr index 46c4ebe938e..1bcbd7d5421 100644 --- a/tooling/nargo_cli/tests/execution_success/nested_arrays_from_brillig/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/nested_arrays_from_brillig/src/main.nr @@ -13,9 +13,9 @@ fn access_nested(notes: [MyNote; 2]) -> Field { } unconstrained fn create_inside_brillig(values: [Field; 6]) -> [MyNote; 2] { - let header = Header { params: [values[0], values[1], values[2]]}; - let note0 = MyNote { array: [values[0], values[1]], plain : values[2], header }; - let note1 = MyNote { array: [values[3], values[4]], plain : values[5], header }; + let header = Header { params: [values[0], values[1], values[2]] }; + let note0 = MyNote { array: [values[0], values[1]], plain: values[2], header }; + let note1 = MyNote { array: [values[3], values[4]], plain: values[5], header }; [note0, note1] } diff --git a/tooling/nargo_cli/tests/execution_success/nested_slice_dynamic/Nargo.toml b/tooling/nargo_cli/tests/execution_success/nested_slice_dynamic/Nargo.toml index 00dfbffbe45..c8925ed97b4 100644 --- a/tooling/nargo_cli/tests/execution_success/nested_slice_dynamic/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/nested_slice_dynamic/Nargo.toml @@ -2,6 +2,4 @@ name = "nested_slice_dynamic" type = "bin" authors = [""] -compiler_version = "0.13.0" - [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/execution_success/nested_slice_dynamic/src/main.nr b/tooling/nargo_cli/tests/execution_success/nested_slice_dynamic/src/main.nr index a2de5141786..2d7c52da495 100644 --- a/tooling/nargo_cli/tests/execution_success/nested_slice_dynamic/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/nested_slice_dynamic/src/main.nr @@ -41,7 +41,7 @@ fn main(y : Field) { x[y - 1].b = [100, 101, 102]; } assert(x[2].b == [100, 101, 102]); - + assert(x[y - 3].bar.inner == [100, 101, 102]); assert(x[y - 2].bar.inner == [103, 104, 105]); assert(x[y - 1].bar.inner == [106, 107, 108]); diff --git a/tooling/nargo_cli/tests/execution_success/pedersen_check/Nargo.toml b/tooling/nargo_cli/tests/execution_success/pedersen_check/Nargo.toml index 3fc0bd9b79e..65fd3b5cf59 100644 --- a/tooling/nargo_cli/tests/execution_success/pedersen_check/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/pedersen_check/Nargo.toml @@ -2,6 +2,5 @@ name = "pedersen_check" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/pedersen_check/src/main.nr b/tooling/nargo_cli/tests/execution_success/pedersen_check/src/main.nr index 8d3460de98f..f25c1f68a18 100644 --- a/tooling/nargo_cli/tests/execution_success/pedersen_check/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/pedersen_check/src/main.nr @@ -1,21 +1,23 @@ use dep::std; fn main(x: Field, y: Field, salt: Field, out_x: Field, out_y: Field, out_hash: Field) { - let res = std::hash::pedersen([x, y]); - assert(res[0] == out_x); - assert(res[1] == out_y); + let res = std::hash::pedersen_commitment([x, y]); + assert(res.x == out_x); + assert(res.y == out_y); + let res_hash = std::hash::pedersen_hash_with_separator([x, y], 0); assert_eq(res_hash, out_hash); - assert(res_hash != res[0]); + assert(res_hash != res.x); + - let raw_data = [x,y]; + let raw_data = [x, y]; let mut state = 0; for i in 0..2 { state = state * 8 + raw_data[i]; } state += salt; - let hash = std::hash::pedersen([state]); - assert(std::hash::pedersen([43])[0] == hash[0]); + let hash = std::hash::pedersen_commitment([state]); + assert(std::hash::pedersen_commitment([43]).x == hash.x); } diff --git a/tooling/nargo_cli/tests/execution_success/poseidon_bn254_hash/Nargo.toml b/tooling/nargo_cli/tests/execution_success/poseidon_bn254_hash/Nargo.toml index d23bb7cb919..a8e2b3d5a2c 100644 --- a/tooling/nargo_cli/tests/execution_success/poseidon_bn254_hash/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/poseidon_bn254_hash/Nargo.toml @@ -3,6 +3,5 @@ name = "poseidon_bn254_hash" description = "Poseidon 254-bit permutation test on 3 elements with alpha = 5" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/poseidonsponge_x5_254/Nargo.toml b/tooling/nargo_cli/tests/execution_success/poseidonsponge_x5_254/Nargo.toml index df1da360206..de4b1a44668 100644 --- a/tooling/nargo_cli/tests/execution_success/poseidonsponge_x5_254/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/poseidonsponge_x5_254/Nargo.toml @@ -3,6 +3,5 @@ name = "poseidonsponge_x5_254" description = "Variable-length Poseidon-128 sponge test on 7 elements with alpha = 5" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/poseidonsponge_x5_254/src/main.nr b/tooling/nargo_cli/tests/execution_success/poseidonsponge_x5_254/src/main.nr index 6d75dcccc66..910a17c8c89 100644 --- a/tooling/nargo_cli/tests/execution_success/poseidonsponge_x5_254/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/poseidonsponge_x5_254/src/main.nr @@ -3,6 +3,6 @@ use dep::std::hash::poseidon; fn main(x: [Field; 7]) { // Test optimized sponge let result = poseidon::bn254::sponge(x); - + assert(result == 0x080ae1669d62f0197190573d4a325bfb8d8fc201ce3127cbac0c47a7ac81ac48); } diff --git a/tooling/nargo_cli/tests/execution_success/pred_eq/Nargo.toml b/tooling/nargo_cli/tests/execution_success/pred_eq/Nargo.toml index ee6f7a28e0f..b5b4a9fdf61 100644 --- a/tooling/nargo_cli/tests/execution_success/pred_eq/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/pred_eq/Nargo.toml @@ -2,6 +2,5 @@ name = "pred_eq" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/references/Nargo.toml b/tooling/nargo_cli/tests/execution_success/references/Nargo.toml index b52fdcf77f0..c4be4d4218d 100644 --- a/tooling/nargo_cli/tests/execution_success/references/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/references/Nargo.toml @@ -2,6 +2,5 @@ name = "references" type = "bin" authors = [""] -compiler_version = "0.5.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/references/src/main.nr b/tooling/nargo_cli/tests/execution_success/references/src/main.nr index 5265519f2a8..33fe69dc96e 100644 --- a/tooling/nargo_cli/tests/execution_success/references/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/references/src/main.nr @@ -22,12 +22,7 @@ fn main(mut x: Field) { assert(**nested_allocations.y == 1); // Test nested struct allocations with a mutable reference to an array. - let mut c = C { - foo: 0, - bar: &mut C2 { - array: &mut [1, 2], - }, - }; + let mut c = C { foo: 0, bar: &mut C2 { array: &mut [1, 2] } }; *c.bar.array = [3, 4]; assert(*c.bar.array == [3, 4]); @@ -135,15 +130,14 @@ fn regression_2218(x: Field, y: Field) -> Field { if x != 20 { *q1 = 10; *q2 = 2; // now we'd expect q1 == q2 == 2 - - assert(*q1 == 2); + assert(*q1 == 2); } else { *q2 = 15; assert(*q1 == 15); } } else { *q2 = 20; - assert(*q1 == 20); + assert(*q1 == 20); } // Have to assign value to return it let value = *q1; @@ -232,7 +226,7 @@ fn regression_2218_loop(x: Field, y: Field) { } } else { *q2 = 20; - assert(*q1 == 20); + assert(*q1 == 20); } assert(*q1 == 2); } diff --git a/tooling/nargo_cli/tests/execution_success/regression/Nargo.toml b/tooling/nargo_cli/tests/execution_success/regression/Nargo.toml index 91497e10342..0f6961c41d3 100644 --- a/tooling/nargo_cli/tests/execution_success/regression/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/regression/Nargo.toml @@ -2,6 +2,5 @@ name = "regression" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/regression/src/main.nr b/tooling/nargo_cli/tests/execution_success/regression/src/main.nr index 010468a450a..f8ac3823e08 100644 --- a/tooling/nargo_cli/tests/execution_success/regression/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/regression/src/main.nr @@ -1,7 +1,7 @@ global NIBBLE_LENGTH: Field = 16; fn compact_decode(input: [u8; N], length: Field) -> ([u4; NIBBLE_LENGTH], Field) { - assert(2*input.len() as u64 <= NIBBLE_LENGTH as u64); + assert(2 * input.len() as u64 <= NIBBLE_LENGTH as u64); assert(length as u64 <= input.len() as u64); let mut nibble = [0 as u4; NIBBLE_LENGTH]; @@ -9,8 +9,7 @@ fn compact_decode(input: [u8; N], length: Field) -> ([u4; NIBBLE_LENGTH], Fie let first_nibble = (input[0] >> 4) as u4; let parity = first_nibble as u1; - if parity == 1 - { + if parity == 1 { nibble[0] = (input[0] & 0x0f) as u4; for i in 1..input.len() { @@ -21,9 +20,7 @@ fn compact_decode(input: [u8; N], length: Field) -> ([u4; NIBBLE_LENGTH], Fie nibble[2*i] = (x & 0x0f) as u4; } } - } - else - { + } else { for i in 0..2 { if (i as u64) < length as u64 - 1 @@ -35,7 +32,7 @@ fn compact_decode(input: [u8; N], length: Field) -> ([u4; NIBBLE_LENGTH], Fie } } - let out = (nibble, 2*length + (parity as Field) - 2); + let out = (nibble, 2 * length + (parity as Field) - 2); out } @@ -43,30 +40,24 @@ fn compact_decode(input: [u8; N], length: Field) -> ([u4; NIBBLE_LENGTH], Fie fn enc(value: [u8; N], value_length: Field) -> ([u8; 32], Field) { assert(value.len() as u8 >= value_length as u8); let mut out_value = [0; 32]; - if value_length == 0 - { - let out = (out_value, value_length); - out - } - else { if value_length as u8 < 31 - { + if value_length == 0 { + let out = (out_value, value_length); + out + } else if value_length as u8 < 31 { out_value[0] = 0x80 + value_length as u8; for i in 1..value.len() { out_value[i] = value[i-1]; } - - let out = (out_value, value_length + 1); - out - } - else - { - let out = (out_value, 32); - out + let out = (out_value, value_length + 1); + + out + } else { + let out = (out_value, 32); + out } - } } fn bitshift_literal_0() -> u64 { @@ -90,17 +81,21 @@ fn bitshift_variable(idx: u64) -> u64 { fn main(x: [u8; 5], z: Field) { //Issue 1144 - let (nib, len) = compact_decode(x,z); - assert(len == 5); - assert([nib[0], nib[1], nib[2], nib[3], nib[4]] == [15, 1, 12, 11, 8]); + let (nib, len) = compact_decode(x, z); + assert(len == 5); + assert([nib[0], nib[1], nib[2], nib[3], nib[4]] == [15, 1, 12, 11, 8]); // Issue 1169 - let val1 = [0xb8,0x8f,0x61,0xe6,0xfb,0xda,0x83,0xfb,0xff,0xfa,0xbe,0x36,0x41,0x12,0x13,0x74,0x80,0x39,0x80,0x18,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00]; + let val1 = [0xb8, 0x8f, 0x61, 0xe6, 0xfb, 0xda, 0x83, 0xfb, 0xff, 0xfa, 0xbe, 0x36, 0x41, 0x12, 0x13, + 0x74, 0x80, 0x39, 0x80, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00]; let val1_length = 20; - let enc_val1 = enc(val1,val1_length); + let enc_val1 = enc(val1, val1_length); - assert(enc_val1.0 == [0x94,0xb8,0x8f,0x61,0xe6,0xfb,0xda,0x83,0xfb,0xff,0xfa,0xbe,0x36,0x41,0x12,0x13,0x74,0x80,0x39,0x80,0x18,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00]); + assert(enc_val1.0 == [0x94, 0xb8, 0x8f, 0x61, 0xe6, 0xfb, 0xda, 0x83, 0xfb, 0xff, 0xfa, 0xbe, 0x36, 0x41, 0x12, + 0x13, 0x74, 0x80, 0x39, 0x80, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00]); assert(enc_val1.1 == 21); // Issue 2399 diff --git a/tooling/nargo_cli/tests/execution_success/regression_2854/Nargo.toml b/tooling/nargo_cli/tests/execution_success/regression_2854/Nargo.toml index 33bd007d898..fb2b3c42fdd 100644 --- a/tooling/nargo_cli/tests/execution_success/regression_2854/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/regression_2854/Nargo.toml @@ -2,6 +2,5 @@ name = "regression_2854" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/regression_mem_op_predicate/Nargo.toml b/tooling/nargo_cli/tests/execution_success/regression_mem_op_predicate/Nargo.toml index 0361b28fd1e..93a0ba6f25a 100644 --- a/tooling/nargo_cli/tests/execution_success/regression_mem_op_predicate/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/regression_mem_op_predicate/Nargo.toml @@ -2,6 +2,5 @@ name = "regression_mem_op_predicate" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/regression_mem_op_predicate/src/main.nr b/tooling/nargo_cli/tests/execution_success/regression_mem_op_predicate/src/main.nr index 368ca50397f..2592d02ec2e 100644 --- a/tooling/nargo_cli/tests/execution_success/regression_mem_op_predicate/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/regression_mem_op_predicate/src/main.nr @@ -1,8 +1,8 @@ fn main(mut x: [u32; 5], idx: Field) { // We should not hit out of bounds here as we have a predicate // that should not be hit - if idx as u32 < 3 { + if idx as u32 < 3 { x[idx] = 10; - } - assert(x[4] == 111); + } + assert(x[4] == 111); } diff --git a/tooling/nargo_cli/tests/execution_success/regression_method_cannot_be_found/Nargo.toml b/tooling/nargo_cli/tests/execution_success/regression_method_cannot_be_found/Nargo.toml index 9d9bb35778d..aed6aa06714 100644 --- a/tooling/nargo_cli/tests/execution_success/regression_method_cannot_be_found/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/regression_method_cannot_be_found/Nargo.toml @@ -2,6 +2,5 @@ name = "regression_method_cannot_be_found" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/scalar_mul/Nargo.toml b/tooling/nargo_cli/tests/execution_success/scalar_mul/Nargo.toml index 55bf6395b34..926114ec374 100644 --- a/tooling/nargo_cli/tests/execution_success/scalar_mul/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/scalar_mul/Nargo.toml @@ -2,6 +2,5 @@ name = "scalar_mul" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/scalar_mul/src/main.nr b/tooling/nargo_cli/tests/execution_success/scalar_mul/src/main.nr index 87641b407d6..f62496d61d5 100644 --- a/tooling/nargo_cli/tests/execution_success/scalar_mul/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/scalar_mul/src/main.nr @@ -15,8 +15,8 @@ fn main( priv_key = b; pub_x = b_pub_x; pub_y = b_pub_y; - } + } let res = std::scalar_mul::fixed_base_embedded_curve(priv_key, 0); - assert(res[0] == pub_x); - assert(res[1] == pub_y); + assert(res[0] == pub_x); + assert(res[1] == pub_y); } diff --git a/tooling/nargo_cli/tests/execution_success/schnorr/Nargo.toml b/tooling/nargo_cli/tests/execution_success/schnorr/Nargo.toml index 3ba59b7010e..aa24a2f3caf 100644 --- a/tooling/nargo_cli/tests/execution_success/schnorr/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/schnorr/Nargo.toml @@ -2,6 +2,5 @@ name = "schnorr" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/schnorr/src/main.nr b/tooling/nargo_cli/tests/execution_success/schnorr/src/main.nr index 3c8881b2f39..f974027f1cf 100644 --- a/tooling/nargo_cli/tests/execution_success/schnorr/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/schnorr/src/main.nr @@ -12,10 +12,10 @@ fn main(message: [u8; 10], message_field: Field, pub_key_x: Field, pub_key_y: Fi // Is there ever a situation where someone would want // to ensure that a signature was invalid? // Check that passing a slice as the message is valid - let valid_signature = std::schnorr::verify_signature(pub_key_x,pub_key_y,signature, message_field_bytes); + let valid_signature = std::schnorr::verify_signature(pub_key_x, pub_key_y, signature, message_field_bytes); assert(valid_signature); // Check that passing an array as the message is valid - let valid_signature = std::schnorr::verify_signature(pub_key_x,pub_key_y,signature, message); + let valid_signature = std::schnorr::verify_signature(pub_key_x, pub_key_y, signature, message); assert(valid_signature); } diff --git a/tooling/nargo_cli/tests/execution_success/sha256/Nargo.toml b/tooling/nargo_cli/tests/execution_success/sha256/Nargo.toml index 97ca07f03d4..255d2156ef6 100644 --- a/tooling/nargo_cli/tests/execution_success/sha256/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/sha256/Nargo.toml @@ -2,6 +2,5 @@ name = "sha256" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/sha2_blocks/Prover.toml b/tooling/nargo_cli/tests/execution_success/sha2_blocks/Prover.toml deleted file mode 100644 index 3fe435ea07f..00000000000 --- a/tooling/nargo_cli/tests/execution_success/sha2_blocks/Prover.toml +++ /dev/null @@ -1,4 +0,0 @@ -# From https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Standards-and-Guidelines/documents/examples/SHA256.pdf and https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Standards-and-Guidelines/documents/examples/SHA512.pdf -x = [0x61, 0x62, 0x63] # "abc" -result256 = [0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad] -result512 = [0xdd, 0xaf, 0x35, 0xa1, 0x93, 0x61, 0x7a, 0xba, 0xcc, 0x41, 0x73, 0x49, 0xae, 0x20, 0x41, 0x31, 0x12, 0xe6, 0xfa, 0x4e, 0x89, 0xa9, 0x7e, 0xa2, 0x0a, 0x9e, 0xee, 0xe6, 0x4b, 0x55, 0xd3, 0x9a, 0x21, 0x92, 0x99, 0x2a, 0x27, 0x4f, 0xc1, 0xa8, 0x36, 0xba, 0x3c, 0x23, 0xa3, 0xfe, 0xeb, 0xbd, 0x45, 0x4d, 0x44, 0x23, 0x64, 0x3c, 0xe8, 0x0e, 0x2a, 0x9a, 0xc9, 0x4f, 0xa5, 0x4c, 0xa4, 0x9f] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/execution_success/sha2_blocks/src/main.nr b/tooling/nargo_cli/tests/execution_success/sha2_blocks/src/main.nr deleted file mode 100644 index 52891d18de2..00000000000 --- a/tooling/nargo_cli/tests/execution_success/sha2_blocks/src/main.nr +++ /dev/null @@ -1,21 +0,0 @@ -// Test Noir implementations of SHA256 and SHA512 on one- and two-block (padded) messages. -use dep::std; - -fn main(x: [u8; 3], result256: [u8; 32], result512: [u8; 64]) { - // One-block tests. - let mut digest256 = std::sha256::digest(x); - assert(digest256 == result256); - - let mut digest512 = std::sha512::digest(x); - assert(digest512 == result512); - - // Two-block SHA256 test. Taken from https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Standards-and-Guidelines/documents/examples/SHA256.pdf - let y: [u8; 56] = [97,98,99,100,98,99,100,101,99,100,101,102,100,101,102,103,101,102,103,104,102,103,104,105,103,104,105,106,104,105,106,107,105,106,107,108,106,107,108,109,107,108,109,110,108,109,110,111,109,110,111,112,110,111,112,113]; // "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" - digest256 = std::sha256::digest(y); - assert(digest256 == [36,141,106,97,210,6,56,184,229,192,38,147,12,62,96,57,163,60,228,89,100,255,33,103,246,236,237,212,25,219,6,193]); - - // Two-block SHA256 test. Taken from https://csrc.nist.gov/CSRC/media/Projects/Cryptographic-Standards-and-Guidelines/documents/examples/SHA512.pdf - let z: [u8; 112] = [97,98,99,100,101,102,103,104,98,99,100,101,102,103,104,105,99,100,101,102,103,104,105,106,100,101,102,103,104,105,106,107,101,102,103,104,105,106,107,108,102,103,104,105,106,107,108,109,103,104,105,106,107,108,109,110,104,105,106,107,108,109,110,111,105,106,107,108,109,110,111,112,106,107,108,109,110,111,112,113,107,108,109,110,111,112,113,114,108,109,110,111,112,113,114,115,109,110,111,112,113,114,115,116,110,111,112,113,114,115,116,117]; // "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu" - digest512 = std::sha512::digest(z); - assert(digest512 == [142,149,155,117,218,227,19,218,140,244,247,40,20,252,20,63,143,119,121,198,235,159,127,161,114,153,174,173,182,136,144,24,80,29,40,158,73,0,247,228,51,27,153,222,196,181,67,58,199,211,41,238,182,221,38,84,94,150,229,91,135,75,233,9]); -} diff --git a/tooling/nargo_cli/tests/execution_success/sha2_byte/Nargo.toml b/tooling/nargo_cli/tests/execution_success/sha2_byte/Nargo.toml index 849b6220db7..efd691fce58 100644 --- a/tooling/nargo_cli/tests/execution_success/sha2_byte/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/sha2_byte/Nargo.toml @@ -2,6 +2,5 @@ name = "sha2_byte" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/sha2_byte/src/main.nr b/tooling/nargo_cli/tests/execution_success/sha2_byte/src/main.nr index 6470ccd8379..fa8ddfbdf69 100644 --- a/tooling/nargo_cli/tests/execution_success/sha2_byte/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/sha2_byte/src/main.nr @@ -3,8 +3,8 @@ use dep::std; fn main(x: Field, result256: [u8; 32], result512: [u8; 64]) { let digest256 = std::sha256::digest([x as u8]); - assert(digest256 == result256); + assert(digest256 == result256); let digest512 = std::sha512::digest([x as u8]); - assert(digest512 == result512); + assert(digest512 == result512); } diff --git a/tooling/nargo_cli/tests/execution_success/signed_arithmetic/Nargo.toml b/tooling/nargo_cli/tests/execution_success/signed_arithmetic/Nargo.toml index 952e7d88a5a..47676a806e8 100644 --- a/tooling/nargo_cli/tests/execution_success/signed_arithmetic/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/signed_arithmetic/Nargo.toml @@ -2,6 +2,5 @@ name = "signed_arithmetic" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/signed_division/Nargo.toml b/tooling/nargo_cli/tests/execution_success/signed_division/Nargo.toml index c1dacecae02..0d631a00b05 100644 --- a/tooling/nargo_cli/tests/execution_success/signed_division/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/signed_division/Nargo.toml @@ -2,6 +2,5 @@ name = "signed_division" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/simple_2d_array/Nargo.toml b/tooling/nargo_cli/tests/execution_success/simple_2d_array/Nargo.toml index 033c9cf1c25..b6d22d82631 100644 --- a/tooling/nargo_cli/tests/execution_success/simple_2d_array/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/simple_2d_array/Nargo.toml @@ -2,6 +2,5 @@ name = "simple_2d_array" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/simple_2d_array/src/main.nr b/tooling/nargo_cli/tests/execution_success/simple_2d_array/src/main.nr index c098a679a3b..2ecdd4bc15f 100644 --- a/tooling/nargo_cli/tests/execution_success/simple_2d_array/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/simple_2d_array/src/main.nr @@ -3,6 +3,6 @@ fn main(x: Field, y: Field, array_input: [[Field; 2]; 2]) { assert(array_input[0][0] == x); assert(array_input[0][1] == y); - let arr: [[Field; 2]; 1] = [[3,3]]; + let arr: [[Field; 2]; 1] = [[3, 3]]; assert_eq(arr[0], array_input[1]); } diff --git a/tooling/nargo_cli/tests/execution_success/simple_add_and_ret_arr/Nargo.toml b/tooling/nargo_cli/tests/execution_success/simple_add_and_ret_arr/Nargo.toml index 9afb8c5fd5b..6c5b0e4ca9a 100644 --- a/tooling/nargo_cli/tests/execution_success/simple_add_and_ret_arr/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/simple_add_and_ret_arr/Nargo.toml @@ -2,6 +2,4 @@ name = "simple_add_and_ret_arr" type = "bin" authors = [""] -compiler_version = "0.6.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/simple_bitwise/Nargo.toml b/tooling/nargo_cli/tests/execution_success/simple_bitwise/Nargo.toml index c8fe1e06b4c..be425f22e5c 100644 --- a/tooling/nargo_cli/tests/execution_success/simple_bitwise/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/simple_bitwise/Nargo.toml @@ -2,6 +2,4 @@ name = "simple_bitwise" type = "bin" authors = [""] -compiler_version = "0.6.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/simple_comparison/Nargo.toml b/tooling/nargo_cli/tests/execution_success/simple_comparison/Nargo.toml index 840eb0a7e0b..06685628444 100644 --- a/tooling/nargo_cli/tests/execution_success/simple_comparison/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/simple_comparison/Nargo.toml @@ -2,6 +2,5 @@ name = "simple_comparison" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/simple_mut/Nargo.toml b/tooling/nargo_cli/tests/execution_success/simple_mut/Nargo.toml index b7b5c5d3dcc..c00e60bdbc0 100644 --- a/tooling/nargo_cli/tests/execution_success/simple_mut/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/simple_mut/Nargo.toml @@ -2,6 +2,4 @@ name = "simple_mut" type = "bin" authors = [""] -compiler_version = "0.6.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/simple_not/Nargo.toml b/tooling/nargo_cli/tests/execution_success/simple_not/Nargo.toml index 0ca112cf4b3..52c86b36efb 100644 --- a/tooling/nargo_cli/tests/execution_success/simple_not/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/simple_not/Nargo.toml @@ -2,6 +2,4 @@ name = "simple_not" type = "bin" authors = [""] -compiler_version = "0.6.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/simple_print/Nargo.toml b/tooling/nargo_cli/tests/execution_success/simple_print/Nargo.toml index d154fbc47f2..cd8422ac482 100644 --- a/tooling/nargo_cli/tests/execution_success/simple_print/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/simple_print/Nargo.toml @@ -2,6 +2,4 @@ name = "simple_print" type = "bin" authors = [""] -compiler_version = "0.6.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/simple_program_addition/Nargo.toml b/tooling/nargo_cli/tests/execution_success/simple_program_addition/Nargo.toml index 8cf28eb45a7..28967a28a55 100644 --- a/tooling/nargo_cli/tests/execution_success/simple_program_addition/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/simple_program_addition/Nargo.toml @@ -2,6 +2,5 @@ name = "simple_program_addition" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/simple_radix/Nargo.toml b/tooling/nargo_cli/tests/execution_success/simple_radix/Nargo.toml index 6c208c1645c..12cbc8da1d3 100644 --- a/tooling/nargo_cli/tests/execution_success/simple_radix/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/simple_radix/Nargo.toml @@ -2,6 +2,4 @@ name = "simple_radix" type = "bin" authors = [""] -compiler_version = "0.6.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/simple_shield/Nargo.toml b/tooling/nargo_cli/tests/execution_success/simple_shield/Nargo.toml index b710f38d826..7e9579b0af4 100644 --- a/tooling/nargo_cli/tests/execution_success/simple_shield/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/simple_shield/Nargo.toml @@ -2,6 +2,5 @@ name = "simple_shield" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/simple_shield/Prover.toml b/tooling/nargo_cli/tests/execution_success/simple_shield/Prover.toml index 55492a9bf6d..7878e4b8281 100644 --- a/tooling/nargo_cli/tests/execution_success/simple_shield/Prover.toml +++ b/tooling/nargo_cli/tests/execution_success/simple_shield/Prover.toml @@ -1,6 +1,6 @@ # Random test key priv_key = "0x000000000000000000000000000000000000000000000000000000616c696365" -note_root = "0x0f8cd7b45fbb4e08f63126f1673ce9e574cfbda70f36c2e5182f9e3dbe6524c0" +note_root = "0x02278fc806225cd696bd502049f7bb98624536de56d09343f8a26ac1876b23a0" index = "0" note_hash_path = [ "0x1cdcf02431ba623767fe389337d011df1048dcc24b98ed81cec97627bab454a0", diff --git a/tooling/nargo_cli/tests/execution_success/simple_shield/src/main.nr b/tooling/nargo_cli/tests/execution_success/simple_shield/src/main.nr index c26a53d56cd..f8fec2cb4d9 100644 --- a/tooling/nargo_cli/tests/execution_success/simple_shield/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/simple_shield/src/main.nr @@ -20,16 +20,16 @@ fn main( let pubkey_y = pubkey[1]; // Compute input note commitment - let note_commitment = std::hash::pedersen([pubkey_x, pubkey_y]); + let note_commitment = std::hash::pedersen_commitment([pubkey_x, pubkey_y]); // Compute input note nullifier - let nullifier = std::hash::pedersen([note_commitment[0], index, priv_key]); + let nullifier = std::hash::pedersen_commitment([note_commitment.x, index, priv_key]); // Compute output note nullifier - let receiver_note_commitment = std::hash::pedersen([to_pubkey_x, to_pubkey_y]); + let receiver_note_commitment = std::hash::pedersen_commitment([to_pubkey_x, to_pubkey_y]); // Check that the input note nullifier is in the root - assert(note_root == std::merkle::compute_merkle_root(note_commitment[0], index, note_hash_path)); + assert(note_root == std::merkle::compute_merkle_root(note_commitment.x, index, note_hash_path)); - [nullifier[0], receiver_note_commitment[0]] + [nullifier.x, receiver_note_commitment.x] } diff --git a/tooling/nargo_cli/tests/execution_success/simple_shift_left_right/Nargo.toml b/tooling/nargo_cli/tests/execution_success/simple_shift_left_right/Nargo.toml index 09eb46d547e..2e75d5feada 100644 --- a/tooling/nargo_cli/tests/execution_success/simple_shift_left_right/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/simple_shift_left_right/Nargo.toml @@ -2,6 +2,5 @@ name = "simple_shift_left_right" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/slice_dynamic_index/Nargo.toml b/tooling/nargo_cli/tests/execution_success/slice_dynamic_index/Nargo.toml index 08322784151..a02faeae27a 100644 --- a/tooling/nargo_cli/tests/execution_success/slice_dynamic_index/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/slice_dynamic_index/Nargo.toml @@ -2,6 +2,5 @@ name = "slice_dynamic_index" type = "bin" authors = [""] -compiler_version = "0.10.3" [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/execution_success/slices/Nargo.toml b/tooling/nargo_cli/tests/execution_success/slices/Nargo.toml index bc9dcc7729a..3eec413bc07 100644 --- a/tooling/nargo_cli/tests/execution_success/slices/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/slices/Nargo.toml @@ -2,6 +2,4 @@ name = "slices" type = "bin" authors = [""] -compiler_version = "0.6.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/slices/src/main.nr b/tooling/nargo_cli/tests/execution_success/slices/src/main.nr index 8d53e013f96..25c2ac27157 100644 --- a/tooling/nargo_cli/tests/execution_success/slices/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/slices/src/main.nr @@ -61,7 +61,6 @@ fn regression_2083() { let y = y.push_front((10, 11)); // [(10, 11), (1, 2), (3, 4), (5, 6)] let y = y.push_front((12, 13)); // [(12, 13), (10, 11), (1, 2), (3, 4), (5, 6)] - assert(y[1].0 == 10); let y = y.insert(1, (55, 56)); // [(12, 13), (55, 56), (10, 11), (1, 2), (3, 4), (5, 6)] @@ -149,15 +148,7 @@ fn merge_slices_else(x: Field) { // Test returning a merged slice without a mutation fn merge_slices_return(x: Field, y: Field) -> [Field] { let slice = [0; 2]; - if x != y { - if x != 20 { - slice.push_back(y) - } else { - slice - } - } else { - slice - } + if x != y { if x != 20 { slice.push_back(y) } else { slice } } else { slice } } // Test mutating a slice inside of an if statement diff --git a/tooling/nargo_cli/tests/execution_success/strings/Nargo.toml b/tooling/nargo_cli/tests/execution_success/strings/Nargo.toml index 30df1a2f27e..76a9beb6909 100644 --- a/tooling/nargo_cli/tests/execution_success/strings/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/strings/Nargo.toml @@ -2,6 +2,5 @@ name = "strings" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/strings/src/main.nr b/tooling/nargo_cli/tests/execution_success/strings/src/main.nr index 02e2fa678cd..e3b5a5e1197 100644 --- a/tooling/nargo_cli/tests/execution_success/strings/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/strings/src/main.nr @@ -23,9 +23,9 @@ fn main(message : pub str<11>, y : Field, hex_as_string : str<4>, hex_as_field : std::println(bad_message); assert(message != bad_message); - let hash = std::hash::pedersen([x]); + let hash = std::hash::pedersen_commitment([x]); std::println(hash); - + assert(hex_as_string == "0x41"); // assert(hex_as_string != 0x41); This will fail with a type mismatch between str[4] and Field assert(hex_as_field == 0x41); @@ -48,7 +48,7 @@ fn test_prints_array() { std::println(array); - let hash = std::hash::pedersen(array); + let hash = std::hash::pedersen_commitment(array); std::println(hash); } diff --git a/tooling/nargo_cli/tests/execution_success/struct/Nargo.toml b/tooling/nargo_cli/tests/execution_success/struct/Nargo.toml index 34c3d838538..6622edd0653 100644 --- a/tooling/nargo_cli/tests/execution_success/struct/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/struct/Nargo.toml @@ -2,6 +2,5 @@ name = "struct" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/struct/src/main.nr b/tooling/nargo_cli/tests/execution_success/struct/src/main.nr index 2bd5a1aec28..745815227d9 100644 --- a/tooling/nargo_cli/tests/execution_success/struct/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/struct/src/main.nr @@ -34,11 +34,7 @@ struct MyStruct { my_nest: Nested, } fn test_struct_in_tuple(a_bool : bool,x:Field, y:Field) -> (MyStruct, bool) { - let my_struct = MyStruct { - my_bool: a_bool, - my_int: 5, - my_nest: Nested{a:x,b:y}, - }; + let my_struct = MyStruct { my_bool: a_bool, my_int: 5, my_nest: Nested { a: x, b: y } }; (my_struct, a_bool) } @@ -57,7 +53,7 @@ struct Unit; fn main(x: Field, y: Field) { let unit = Unit {}; - let first = Foo::default(x,y); + let first = Foo::default(x, y); let p = Pair { first, second: 1 }; assert(p.bar() == x); @@ -65,7 +61,7 @@ fn main(x: Field, y: Field) { assert(p.first.array[0] != p.first.array[1]); // Nested structs - let (struct_from_tuple, a_bool) = test_struct_in_tuple(true,x,y); + let (struct_from_tuple, a_bool) = test_struct_in_tuple(true, x, y); assert(struct_from_tuple.my_bool == true); assert(a_bool == true); assert(struct_from_tuple.my_int == 5); diff --git a/tooling/nargo_cli/tests/execution_success/struct_array_inputs/Nargo.toml b/tooling/nargo_cli/tests/execution_success/struct_array_inputs/Nargo.toml index 7be5ccbb99f..40160fb397f 100644 --- a/tooling/nargo_cli/tests/execution_success/struct_array_inputs/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/struct_array_inputs/Nargo.toml @@ -2,6 +2,4 @@ name = "struct_array_inputs" type = "bin" authors = [""] -compiler_version = "0.6.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/struct_fields_ordering/Nargo.toml b/tooling/nargo_cli/tests/execution_success/struct_fields_ordering/Nargo.toml index 2e886f62689..767f51acda3 100644 --- a/tooling/nargo_cli/tests/execution_success/struct_fields_ordering/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/struct_fields_ordering/Nargo.toml @@ -2,6 +2,5 @@ name = "struct_fields_ordering" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/struct_inputs/Nargo.toml b/tooling/nargo_cli/tests/execution_success/struct_inputs/Nargo.toml index 455a7b28ddb..7dd6f78b750 100644 --- a/tooling/nargo_cli/tests/execution_success/struct_inputs/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/struct_inputs/Nargo.toml @@ -2,6 +2,5 @@ name = "struct_inputs" type = "bin" authors = [""] -compiler_version = "0.1" [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/submodules/Nargo.toml b/tooling/nargo_cli/tests/execution_success/submodules/Nargo.toml index a98eda3cd89..082afdf3f10 100644 --- a/tooling/nargo_cli/tests/execution_success/submodules/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/submodules/Nargo.toml @@ -2,6 +2,4 @@ name = "submodules" type = "bin" authors = [""] -compiler_version = "0.1" - [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/to_be_bytes/Nargo.toml b/tooling/nargo_cli/tests/execution_success/to_be_bytes/Nargo.toml index c0837a335f8..e9d2e30b4c4 100644 --- a/tooling/nargo_cli/tests/execution_success/to_be_bytes/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/to_be_bytes/Nargo.toml @@ -2,6 +2,4 @@ name = "to_be_bytes" type = "bin" authors = [""] -compiler_version = "0.1" - [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/to_be_bytes/src/main.nr b/tooling/nargo_cli/tests/execution_success/to_be_bytes/src/main.nr index 81b08ed1785..025738c42e6 100644 --- a/tooling/nargo_cli/tests/execution_success/to_be_bytes/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/to_be_bytes/src/main.nr @@ -5,8 +5,8 @@ fn main(x : Field) -> pub [u8; 31] { for i in 0..31 { bytes[i] = byte_array[i]; } - if ( bytes[30] != 60) | (bytes[29] != 33) | (bytes[28] != 31) { - assert(false); + if (bytes[30] != 60) | (bytes[29] != 33) | (bytes[28] != 31) { + assert(false); } bytes } diff --git a/tooling/nargo_cli/tests/execution_success/to_bytes_consistent/Nargo.toml b/tooling/nargo_cli/tests/execution_success/to_bytes_consistent/Nargo.toml index 65f95d159c8..1e117b83883 100644 --- a/tooling/nargo_cli/tests/execution_success/to_bytes_consistent/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/to_bytes_consistent/Nargo.toml @@ -2,6 +2,4 @@ name = "to_bytes_consistent" type = "bin" authors = [""] -compiler_version = "0.10.3" - [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/execution_success/to_bytes_integration/Nargo.toml b/tooling/nargo_cli/tests/execution_success/to_bytes_integration/Nargo.toml index fd1c714b123..c89c32eb06c 100644 --- a/tooling/nargo_cli/tests/execution_success/to_bytes_integration/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/to_bytes_integration/Nargo.toml @@ -2,6 +2,4 @@ name = "to_bytes_integration" type = "bin" authors = [""] -compiler_version = "0.1" - [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/to_bytes_integration/src/main.nr b/tooling/nargo_cli/tests/execution_success/to_bytes_integration/src/main.nr index 43a35f05488..6825d7f5562 100644 --- a/tooling/nargo_cli/tests/execution_success/to_bytes_integration/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/to_bytes_integration/src/main.nr @@ -4,7 +4,7 @@ fn main(x : Field, a: Field) { let y: Field = 2040124; let be_byte_array = y.to_be_bytes(31); let le_byte_array = x.to_le_bytes(31); - + assert(le_byte_array[0] == 60); assert(le_byte_array[0] == be_byte_array[30]); assert(le_byte_array[1] == be_byte_array[29]); diff --git a/tooling/nargo_cli/tests/execution_success/to_le_bytes/Nargo.toml b/tooling/nargo_cli/tests/execution_success/to_le_bytes/Nargo.toml index 34cf8a5afc7..3d02c3510fd 100644 --- a/tooling/nargo_cli/tests/execution_success/to_le_bytes/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/to_le_bytes/Nargo.toml @@ -2,6 +2,4 @@ name = "to_le_bytes" type = "bin" authors = [""] -compiler_version = "0.1" - [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/trait_as_return_type/Nargo.toml b/tooling/nargo_cli/tests/execution_success/trait_as_return_type/Nargo.toml index 1a7ef7ee8a2..afd89f0c3a1 100644 --- a/tooling/nargo_cli/tests/execution_success/trait_as_return_type/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/trait_as_return_type/Nargo.toml @@ -2,6 +2,4 @@ name = "trait_as_return_type" type = "bin" authors = [""] -compiler_version = "0.10.5" - [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/execution_success/trait_impl_base_type/Nargo.toml b/tooling/nargo_cli/tests/execution_success/trait_impl_base_type/Nargo.toml index dad2ca8fed2..845498737c1 100644 --- a/tooling/nargo_cli/tests/execution_success/trait_impl_base_type/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/trait_impl_base_type/Nargo.toml @@ -2,6 +2,4 @@ name = "trait_impl_base_type" type = "bin" authors = [""] -compiler_version = "0.10.5" - [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/execution_success/trait_impl_base_type/src/main.nr b/tooling/nargo_cli/tests/execution_success/trait_impl_base_type/src/main.nr index 47e919cf39c..e01e243a78f 100644 --- a/tooling/nargo_cli/tests/execution_success/trait_impl_base_type/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/trait_impl_base_type/src/main.nr @@ -81,26 +81,6 @@ fn some_func(x: u32) -> u32 { } -trait MutFieldable { - fn mut_to_field(self) -> Field; -} - -impl MutFieldable for &mut u64 { - fn mut_to_field(self) -> Field { - 1337 as Field - } -} - -fn a(y: &mut u64) -> Field { - y.mut_to_field() -} - -impl Fieldable for &mut u64 { - fn to_field(self) -> Field { - 777 as Field - } -} - impl Fieldable for u64 { fn to_field(self) -> Field { 66 as Field @@ -134,8 +114,5 @@ fn main(x: u32) { assert(some_func.to_field() == 17); let mut y = 0 as u64; - assert(a(&mut y) == 1337); - assert((&mut y).mut_to_field() == 1337); - assert((&mut y).to_field() == 777); assert(y.to_field() == 66); -} \ No newline at end of file +} diff --git a/tooling/nargo_cli/tests/execution_success/traits_in_crates_1/Nargo.toml b/tooling/nargo_cli/tests/execution_success/traits_in_crates_1/Nargo.toml index a13ed98b632..555c3b38b98 100644 --- a/tooling/nargo_cli/tests/execution_success/traits_in_crates_1/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/traits_in_crates_1/Nargo.toml @@ -2,8 +2,6 @@ name = "traits_in_crates_1" type = "bin" authors = [""] -compiler_version = "0.12.0" - [dependencies] crate1 = { path = "crate1" } crate2 = { path = "crate2" } diff --git a/tooling/nargo_cli/tests/execution_success/traits_in_crates_1/crate1/Nargo.toml b/tooling/nargo_cli/tests/execution_success/traits_in_crates_1/crate1/Nargo.toml index 0a94742b76a..f49603ba203 100644 --- a/tooling/nargo_cli/tests/execution_success/traits_in_crates_1/crate1/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/traits_in_crates_1/crate1/Nargo.toml @@ -2,7 +2,5 @@ name = "crate1" type = "lib" authors = [""] -compiler_version = "0.12.0" - [dependencies] crate2 = { path = "../crate2" } diff --git a/tooling/nargo_cli/tests/execution_success/traits_in_crates_1/crate2/Nargo.toml b/tooling/nargo_cli/tests/execution_success/traits_in_crates_1/crate2/Nargo.toml index a90a5dcceea..c86c5edf51a 100644 --- a/tooling/nargo_cli/tests/execution_success/traits_in_crates_1/crate2/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/traits_in_crates_1/crate2/Nargo.toml @@ -2,6 +2,4 @@ name = "crate2" type = "lib" authors = [""] -compiler_version = "0.12.0" - [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/execution_success/traits_in_crates_2/Nargo.toml b/tooling/nargo_cli/tests/execution_success/traits_in_crates_2/Nargo.toml index 8b5bc49e0bb..11a86a08402 100644 --- a/tooling/nargo_cli/tests/execution_success/traits_in_crates_2/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/traits_in_crates_2/Nargo.toml @@ -2,8 +2,6 @@ name = "traits_in_crates_2" type = "bin" authors = [""] -compiler_version = "0.12.0" - [dependencies] crate1 = { path = "crate1" } crate2 = { path = "crate2" } diff --git a/tooling/nargo_cli/tests/execution_success/traits_in_crates_2/crate1/Nargo.toml b/tooling/nargo_cli/tests/execution_success/traits_in_crates_2/crate1/Nargo.toml index b28e0e840c4..de1eddf2cf0 100644 --- a/tooling/nargo_cli/tests/execution_success/traits_in_crates_2/crate1/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/traits_in_crates_2/crate1/Nargo.toml @@ -2,6 +2,4 @@ name = "crate1" type = "lib" authors = [""] -compiler_version = "0.12.0" - [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/execution_success/traits_in_crates_2/crate2/Nargo.toml b/tooling/nargo_cli/tests/execution_success/traits_in_crates_2/crate2/Nargo.toml index 51c201372ee..885d41f0a27 100644 --- a/tooling/nargo_cli/tests/execution_success/traits_in_crates_2/crate2/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/traits_in_crates_2/crate2/Nargo.toml @@ -2,7 +2,5 @@ name = "crate2" type = "lib" authors = [""] -compiler_version = "0.12.0" - [dependencies] crate1 = { path = "../crate1" } diff --git a/tooling/nargo_cli/tests/execution_success/tuple_inputs/Nargo.toml b/tooling/nargo_cli/tests/execution_success/tuple_inputs/Nargo.toml index 7cc7bc85393..f4af6cfe6e3 100644 --- a/tooling/nargo_cli/tests/execution_success/tuple_inputs/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/tuple_inputs/Nargo.toml @@ -2,6 +2,4 @@ name = "tuple_inputs" type = "bin" authors = [""] -compiler_version = "0.14.1" - [dependencies] \ No newline at end of file diff --git a/tooling/nargo_cli/tests/execution_success/tuple_inputs/src/main.nr b/tooling/nargo_cli/tests/execution_success/tuple_inputs/src/main.nr index 2fc44a8fc75..64621411c84 100644 --- a/tooling/nargo_cli/tests/execution_success/tuple_inputs/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/tuple_inputs/src/main.nr @@ -27,6 +27,7 @@ fn main(pair : (Field, Field), x: [(u8, u8, u8); 2], struct_pair: (Foo, Bar)) -> } else { (pair.0 + 1, pair.0) }; + assert(u == pair.0 + 1); assert(v == pair.0); diff --git a/tooling/nargo_cli/tests/execution_success/tuples/Nargo.toml b/tooling/nargo_cli/tests/execution_success/tuples/Nargo.toml index 54603e9a96b..f6ed9f1e649 100644 --- a/tooling/nargo_cli/tests/execution_success/tuples/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/tuples/Nargo.toml @@ -2,6 +2,4 @@ name = "tuples" type = "bin" authors = [""] -compiler_version = "0.1" - [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/tuples/src/main.nr b/tooling/nargo_cli/tests/execution_success/tuples/src/main.nr index e836c66a0fa..b6f6d695f2c 100644 --- a/tooling/nargo_cli/tests/execution_success/tuples/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/tuples/src/main.nr @@ -7,12 +7,8 @@ fn main(x: Field, y: Field) { assert(a == 0); assert(b == 1); - let (u, v) = if x as u32 < 1 { - (x, x + 1) - } else { - (x + 1, x) - }; - assert(u == x+1); + let (u, v) = if x as u32 < 1 { (x, x + 1) } else { (x + 1, x) }; + assert(u == x + 1); assert(v == x); // Test mutating tuples diff --git a/tooling/nargo_cli/tests/execution_success/type_aliases/Nargo.toml b/tooling/nargo_cli/tests/execution_success/type_aliases/Nargo.toml index e828f6913e0..a12df601a91 100644 --- a/tooling/nargo_cli/tests/execution_success/type_aliases/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/type_aliases/Nargo.toml @@ -2,6 +2,4 @@ name = "type_aliases" type = "bin" authors = [""] -compiler_version = "0.1" - [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/type_aliases/src/main.nr b/tooling/nargo_cli/tests/execution_success/type_aliases/src/main.nr index 573a501367f..c9db6d81f90 100644 --- a/tooling/nargo_cli/tests/execution_success/type_aliases/src/main.nr +++ b/tooling/nargo_cli/tests/execution_success/type_aliases/src/main.nr @@ -22,9 +22,7 @@ fn main(x : [Field; 2]) { let e: Three = (c, d); assert(e.0 == 1); - let s = MyStruct { - foo: 10 - }; + let s = MyStruct { foo: 10 }; assert(s.foo == 10); let _regression2502: Regression2502Alias = Regression2502 {}; diff --git a/tooling/nargo_cli/tests/execution_success/workspace/crates/a/Nargo.toml b/tooling/nargo_cli/tests/execution_success/workspace/crates/a/Nargo.toml index 411f048a93b..8d0e1aca4a9 100644 --- a/tooling/nargo_cli/tests/execution_success/workspace/crates/a/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/workspace/crates/a/Nargo.toml @@ -2,6 +2,4 @@ name = "a" type = "bin" authors = [""] -compiler_version = "0.8.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/workspace/crates/b/Nargo.toml b/tooling/nargo_cli/tests/execution_success/workspace/crates/b/Nargo.toml index 1af8ef961cc..f316511340f 100644 --- a/tooling/nargo_cli/tests/execution_success/workspace/crates/b/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/workspace/crates/b/Nargo.toml @@ -2,6 +2,4 @@ name = "b" type = "bin" authors = [""] -compiler_version = "0.8.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/workspace_default_member/a/Nargo.toml b/tooling/nargo_cli/tests/execution_success/workspace_default_member/a/Nargo.toml index 411f048a93b..8d0e1aca4a9 100644 --- a/tooling/nargo_cli/tests/execution_success/workspace_default_member/a/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/workspace_default_member/a/Nargo.toml @@ -2,6 +2,4 @@ name = "a" type = "bin" authors = [""] -compiler_version = "0.8.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/workspace_default_member/b/Nargo.toml b/tooling/nargo_cli/tests/execution_success/workspace_default_member/b/Nargo.toml index 1af8ef961cc..f316511340f 100644 --- a/tooling/nargo_cli/tests/execution_success/workspace_default_member/b/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/workspace_default_member/b/Nargo.toml @@ -2,6 +2,4 @@ name = "b" type = "bin" authors = [""] -compiler_version = "0.8.0" - [dependencies] diff --git a/tooling/nargo_cli/tests/execution_success/xor/Nargo.toml b/tooling/nargo_cli/tests/execution_success/xor/Nargo.toml index ea15f5eb6c5..ddf3b6d86c5 100644 --- a/tooling/nargo_cli/tests/execution_success/xor/Nargo.toml +++ b/tooling/nargo_cli/tests/execution_success/xor/Nargo.toml @@ -2,6 +2,4 @@ name = "xor" type = "bin" authors = [""] -compiler_version = "0.1" - [dependencies] diff --git a/tooling/nargo_cli/tests/noir_test_failure/should_fail_mismatch/Nargo.toml b/tooling/nargo_cli/tests/noir_test_failure/should_fail_mismatch/Nargo.toml index dd56e682004..3d2cf2c6096 100644 --- a/tooling/nargo_cli/tests/noir_test_failure/should_fail_mismatch/Nargo.toml +++ b/tooling/nargo_cli/tests/noir_test_failure/should_fail_mismatch/Nargo.toml @@ -2,6 +2,4 @@ name = "should_fail_with_mismatch" type = "bin" authors = [""] -compiler_version = "0.1" - [dependencies] diff --git a/tooling/nargo_cli/tests/noir_test_failure/should_fail_mismatch/src/main.nr b/tooling/nargo_cli/tests/noir_test_failure/should_fail_mismatch/src/main.nr index b2672221c34..6c8dbda5149 100644 --- a/tooling/nargo_cli/tests/noir_test_failure/should_fail_mismatch/src/main.nr +++ b/tooling/nargo_cli/tests/noir_test_failure/should_fail_mismatch/src/main.nr @@ -1,4 +1,3 @@ - #[test(should_fail_with = "Not equal")] fn test_different_string() { assert_eq(0, 1, "Different string"); @@ -13,5 +12,5 @@ fn test_with_extra_space() { // The assert message has a space #[test(should_fail_with = "Not equal")] fn test_runtime_mismatch() { - assert_eq(dep::std::hash::pedersen([27])[0], 0, "Not equal "); -} \ No newline at end of file + assert_eq(dep::std::hash::pedersen_commitment([27])[0], 0, "Not equal "); +} diff --git a/tooling/nargo_cli/tests/noir_test_success/should_fail_with_matches/Nargo.toml b/tooling/nargo_cli/tests/noir_test_success/should_fail_with_matches/Nargo.toml index 78d98bc87a3..21bce3d2b2d 100644 --- a/tooling/nargo_cli/tests/noir_test_success/should_fail_with_matches/Nargo.toml +++ b/tooling/nargo_cli/tests/noir_test_success/should_fail_with_matches/Nargo.toml @@ -2,6 +2,4 @@ name = "should_fail_with_match" type = "bin" authors = [""] -compiler_version = "0.1" - [dependencies] diff --git a/tooling/nargo_cli/tests/noir_test_success/should_fail_with_matches/src/main.nr b/tooling/nargo_cli/tests/noir_test_success/should_fail_with_matches/src/main.nr index 8ae5e56a463..d2b7d155a32 100644 --- a/tooling/nargo_cli/tests/noir_test_success/should_fail_with_matches/src/main.nr +++ b/tooling/nargo_cli/tests/noir_test_success/should_fail_with_matches/src/main.nr @@ -10,10 +10,10 @@ fn test_should_fail_without_match() { #[test(should_fail_with = "Not equal")] fn test_should_fail_with_runtime_match() { - assert_eq(dep::std::hash::pedersen([27])[0], 0, "Not equal"); + assert_eq(dep::std::hash::pedersen_commitment([27]).x, 0, "Not equal"); } #[test(should_fail)] fn test_should_fail_without_runtime_match() { - assert_eq(dep::std::hash::pedersen([27])[0], 0); + assert_eq(dep::std::hash::pedersen_commitment([27]).x, 0); } diff --git a/tooling/nargo_cli/tests/rebuild.sh b/tooling/nargo_cli/tests/rebuild.sh index 9776745a1f7..d89402fb1cf 100755 --- a/tooling/nargo_cli/tests/rebuild.sh +++ b/tooling/nargo_cli/tests/rebuild.sh @@ -42,13 +42,14 @@ for dir in $base_path/*; do # Delete the JSON file after extracting bytecode field rm ./target/${dir_name}.json - # Delete the target directory in acir_artifacts if it exists + # Clear the target directory in acir_artifacts if [ -d "$current_dir/acir_artifacts/$dir_name/target" ]; then rm -r "$current_dir/acir_artifacts/$dir_name/target" fi + mkdir $current_dir/acir_artifacts/$dir_name/target - # Move the target directory to the corresponding directory in acir_artifacts - mv ./target/ $current_dir/acir_artifacts/$dir_name/ + # Move the artifacts from the target directory to the corresponding directory in acir_artifacts + mv ./target/*.gz $current_dir/acir_artifacts/$dir_name/target/ cd $base_path fi diff --git a/tooling/nargo_cli/tests/test_libraries/bad_impl/Nargo.toml b/tooling/nargo_cli/tests/test_libraries/bad_impl/Nargo.toml index ccb03576323..62ffe95922d 100644 --- a/tooling/nargo_cli/tests/test_libraries/bad_impl/Nargo.toml +++ b/tooling/nargo_cli/tests/test_libraries/bad_impl/Nargo.toml @@ -2,6 +2,4 @@ name = "bad_impl" type = "lib" authors = [""] -compiler_version = "0.7.1" - [dependencies] diff --git a/tooling/nargo_cli/tests/test_libraries/bad_name/Nargo.toml b/tooling/nargo_cli/tests/test_libraries/bad_name/Nargo.toml index 313e2411e83..74f6f66524d 100644 --- a/tooling/nargo_cli/tests/test_libraries/bad_name/Nargo.toml +++ b/tooling/nargo_cli/tests/test_libraries/bad_name/Nargo.toml @@ -2,6 +2,4 @@ name = "bad-name" type = "lib" authors = [""] -compiler_version = "0.7.1" - [dependencies] diff --git a/tooling/nargo_cli/tests/test_libraries/bin_dep/Nargo.toml b/tooling/nargo_cli/tests/test_libraries/bin_dep/Nargo.toml index aa7125bf5b5..7cc99c1c5c5 100644 --- a/tooling/nargo_cli/tests/test_libraries/bin_dep/Nargo.toml +++ b/tooling/nargo_cli/tests/test_libraries/bin_dep/Nargo.toml @@ -2,6 +2,4 @@ name = "bin_dep" type = "bin" authors = [""] -compiler_version = "0.7.1" - [dependencies] diff --git a/tooling/nargo_cli/tests/test_libraries/diamond_deps_1/Nargo.toml b/tooling/nargo_cli/tests/test_libraries/diamond_deps_1/Nargo.toml index 7069390334c..f7770e07469 100644 --- a/tooling/nargo_cli/tests/test_libraries/diamond_deps_1/Nargo.toml +++ b/tooling/nargo_cli/tests/test_libraries/diamond_deps_1/Nargo.toml @@ -2,7 +2,5 @@ name = "diamond_deps_1" type = "lib" authors = [""] -compiler_version = "0.7.1" - [dependencies] dep2 = { path = "../diamond_deps_2" } diff --git a/tooling/nargo_cli/tests/test_libraries/diamond_deps_2/Nargo.toml b/tooling/nargo_cli/tests/test_libraries/diamond_deps_2/Nargo.toml index 4b8ece297d3..2dbba1b7a9e 100644 --- a/tooling/nargo_cli/tests/test_libraries/diamond_deps_2/Nargo.toml +++ b/tooling/nargo_cli/tests/test_libraries/diamond_deps_2/Nargo.toml @@ -2,6 +2,4 @@ name = "diamond_deps_2" type = "lib" authors = [""] -compiler_version = "0.7.1" - [dependencies] diff --git a/tooling/nargo_cli/tests/test_libraries/diamond_deps_2/src/lib.nr b/tooling/nargo_cli/tests/test_libraries/diamond_deps_2/src/lib.nr index 7ee59d2bc9d..b0d09c70648 100644 --- a/tooling/nargo_cli/tests/test_libraries/diamond_deps_2/src/lib.nr +++ b/tooling/nargo_cli/tests/test_libraries/diamond_deps_2/src/lib.nr @@ -1,6 +1,5 @@ global RESOLVE_THIS = 3; - pub fn call_dep2(x : Field, y : Field) -> Field { x + y } diff --git a/tooling/nargo_fmt/build.rs b/tooling/nargo_fmt/build.rs index f2e23f9b8c1..3da07715e4e 100644 --- a/tooling/nargo_fmt/build.rs +++ b/tooling/nargo_fmt/build.rs @@ -40,6 +40,12 @@ fn generate_formatter_tests(test_file: &mut File, test_data_dir: &Path) { let input_source_path = file.path(); let input_source = std::fs::read_to_string(input_source_path).unwrap(); + let config = input_source + .lines() + .flat_map(|line| line.strip_prefix("//@")) + .collect::>() + .join("\n"); + let output_source_path = outputs_dir.join(file_name); let output_source = std::fs::read_to_string(output_source_path).unwrap(); @@ -55,7 +61,7 @@ fn format_{test_name}() {{ let (parsed_module, errors) = noirc_frontend::parse_program(&input); assert!(errors.is_empty()); - let config = nargo_fmt::Config::default(); + let config = nargo_fmt::Config::of("{config}").unwrap(); let fmt_text = nargo_fmt::format(&input, parsed_module, &config); diff --git a/tooling/nargo_fmt/src/config.rs b/tooling/nargo_fmt/src/config.rs index dd57778da92..c026b1576c6 100644 --- a/tooling/nargo_fmt/src/config.rs +++ b/tooling/nargo_fmt/src/config.rs @@ -45,23 +45,28 @@ config! { max_width: usize, 100, "Maximum width of each line"; tab_spaces: usize, 4, "Number of spaces per tab"; remove_nested_parens: bool, true, "Remove nested parens"; + error_on_lost_comment: bool, true, "Error if unable to get comments"; short_array_element_width_threshold: usize, 10, "Width threshold for an array element to be considered short"; array_width: usize, 100, "Maximum width of an array literal before falling back to vertical formatting"; - single_line_if_else_max_width: usize, 100, "Maximum line length for single line if-else expressions"; + single_line_if_else_max_width: usize, 50, "Maximum line length for single line if-else expressions"; } impl Config { pub fn read(path: &Path) -> Result { - let mut config = Self::default(); let config_path = path.join("noirfmt.toml"); - let raw_toml = match std::fs::read_to_string(&config_path) { - Ok(t) => t, - Err(err) if err.kind() == std::io::ErrorKind::NotFound => String::new(), + let input = match std::fs::read_to_string(&config_path) { + Ok(input) => input, + Err(cause) if cause.kind() == std::io::ErrorKind::NotFound => String::new(), Err(cause) => return Err(ConfigError::ReadFailed(config_path, cause)), }; - let toml = toml::from_str(&raw_toml).map_err(ConfigError::MalformedFile)?; + Self::of(&input) + } + + pub fn of(s: &str) -> Result { + let mut config = Self::default(); + let toml = toml::from_str(s).map_err(ConfigError::MalformedFile)?; config.fill_from_toml(toml); Ok(config) } diff --git a/tooling/nargo_fmt/src/lib.rs b/tooling/nargo_fmt/src/lib.rs index 3e8ee570c09..39e978aa306 100644 --- a/tooling/nargo_fmt/src/lib.rs +++ b/tooling/nargo_fmt/src/lib.rs @@ -30,6 +30,6 @@ pub use config::Config; pub fn format(source: &str, parsed_module: ParsedModule, config: &Config) -> String { let mut fmt = FmtVisitor::new(source, config); - fmt.visit_module(parsed_module); + fmt.visit_file(parsed_module); fmt.finish() } diff --git a/tooling/nargo_fmt/src/utils.rs b/tooling/nargo_fmt/src/utils.rs index 5b2cf2f3c47..7bb40956b2e 100644 --- a/tooling/nargo_fmt/src/utils.rs +++ b/tooling/nargo_fmt/src/utils.rs @@ -4,14 +4,6 @@ use noirc_frontend::lexer::Lexer; use noirc_frontend::token::Token; use noirc_frontend::{Expression, Ident}; -pub(crate) fn recover_comment_removed(original: &str, new: String) -> String { - if changed_comment_content(original, &new) { - original.to_string() - } else { - new - } -} - pub(crate) fn changed_comment_content(original: &str, new: &str) -> bool { comments(original).ne(comments(new)) } @@ -119,22 +111,19 @@ impl<'me, T> Exprs<'me, T> { } pub(crate) trait FindToken { - fn find_token(&self, token: Token) -> Option; + fn find_token(&self, token: Token) -> Option; fn find_token_with(&self, f: impl Fn(&Token) -> bool) -> Option; } impl FindToken for str { - fn find_token(&self, token: Token) -> Option { - Lexer::new(self) - .flatten() - .find_map(|it| (it.token() == &token).then(|| it.to_span().start())) + fn find_token(&self, token: Token) -> Option { + Lexer::new(self).flatten().find_map(|it| (it.token() == &token).then(|| it.to_span())) } fn find_token_with(&self, f: impl Fn(&Token) -> bool) -> Option { Lexer::new(self) .skip_comments(false) .flatten() - .into_iter() .find_map(|spanned| f(spanned.token()).then(|| spanned.to_span().end())) } } @@ -163,7 +152,9 @@ pub(crate) fn find_comment_end(slice: &str, is_last: bool) -> usize { } let newline_index = slice.find('\n'); - if let Some(separator_index) = slice.find_token(Token::Comma).map(|index| index as usize) { + if let Some(separator_index) = + slice.find_token(Token::Comma).map(|index| index.start() as usize) + { match (block_open_index, newline_index) { (Some(block), None) if block > separator_index => separator_index + 1, (Some(block), None) => { diff --git a/tooling/nargo_fmt/src/visitor.rs b/tooling/nargo_fmt/src/visitor.rs index bc769e3f298..fd156074ec3 100644 --- a/tooling/nargo_fmt/src/visitor.rs +++ b/tooling/nargo_fmt/src/visitor.rs @@ -2,7 +2,7 @@ mod expr; mod item; mod stmt; -use noirc_frontend::{hir::resolution::errors::Span, token::Token}; +use noirc_frontend::{hir::resolution::errors::Span, lexer::Lexer, token::Token}; use crate::{ config::Config, @@ -33,11 +33,20 @@ impl<'me> FmtVisitor<'me> { &self.source[span.start() as usize..span.end() as usize] } + fn span_after(&self, span: impl Into, token: Token) -> Span { + let span = span.into(); + + let slice = self.slice(span); + let offset = slice.find_token(token).unwrap().end(); + + (span.start() + offset..span.end()).into() + } + fn span_before(&self, span: impl Into, token: Token) -> Span { let span = span.into(); let slice = self.slice(span); - let offset = slice.find_token(token).unwrap(); + let offset = slice.find_token(token).unwrap().start(); (span.start() + offset..span.end()).into() } @@ -80,7 +89,15 @@ impl<'me> FmtVisitor<'me> { #[track_caller] fn push_rewrite(&mut self, rewrite: String, span: Span) { - let rewrite = utils::recover_comment_removed(self.slice(span), rewrite); + let original = self.slice(span); + let changed_comment_content = utils::changed_comment_content(original, &rewrite); + + if changed_comment_content && self.config.error_on_lost_comment { + panic!("not formatted because a comment would be lost: {rewrite:?}"); + } + + let rewrite = if changed_comment_content { original.to_string() } else { rewrite }; + self.format_missing_indent(span.start(), true); self.push_str(&rewrite); } @@ -127,8 +144,42 @@ impl<'me> FmtVisitor<'me> { self.push_vertical_spaces(slice); process_last_slice(self, "", slice); } else { - process_last_slice(self, slice, slice); + if !self.at_start() { + if self.buffer.ends_with('{') { + self.push_str("\n"); + } else { + self.push_vertical_spaces(slice); + } + } + + let (result, last_end) = self.format_comment_in_block(slice); + + if result.is_empty() { + process_last_slice(self, slice, slice); + } else { + self.push_str(result.trim_end()); + let subslice = &slice[last_end as usize..]; + process_last_slice(self, subslice, subslice); + } + } + } + + fn format_comment_in_block(&mut self, slice: &str) -> (String, u32) { + let mut result = String::new(); + let mut last_end = 0; + + for spanned in Lexer::new(slice).skip_comments(false).flatten() { + let span = spanned.to_span(); + last_end = span.end(); + + if let Token::LineComment(_, _) | Token::BlockComment(_, _) = spanned.token() { + result.push_str(&self.indent.to_string()); + result.push_str(&slice[span.start() as usize..span.end() as usize]); + result.push('\n'); + } } + + (result, last_end) } fn push_vertical_spaces(&mut self, slice: &str) { diff --git a/tooling/nargo_fmt/src/visitor/expr.rs b/tooling/nargo_fmt/src/visitor/expr.rs index 8f855cd6157..b7f59526701 100644 --- a/tooling/nargo_fmt/src/visitor/expr.rs +++ b/tooling/nargo_fmt/src/visitor/expr.rs @@ -13,10 +13,8 @@ use crate::{ impl FmtVisitor<'_> { pub(crate) fn visit_expr(&mut self, expr: Expression, expr_type: ExpressionType) { let span = expr.span; - let rewrite = self.format_expr(expr, expr_type); self.push_rewrite(rewrite, span); - self.last_position = span.end(); } @@ -32,7 +30,7 @@ impl FmtVisitor<'_> { match kind { ExpressionKind::Block(block) => { let mut visitor = self.fork(); - visitor.visit_block(block, span, true); + visitor.visit_block(block, span); visitor.buffer } ExpressionKind::Prefix(prefix) => { @@ -192,7 +190,7 @@ impl FmtVisitor<'_> { self.format_if(*if_expr) } - ExpressionKind::Variable(_) | ExpressionKind::Lambda(_) => self.slice(span).to_string(), + ExpressionKind::Lambda(_) | ExpressionKind::Variable(_) => self.slice(span).to_string(), ExpressionKind::Error => unreachable!(), } } @@ -281,14 +279,9 @@ impl FmtVisitor<'_> { format!("{type_name} {{{fields}}}") } - pub(crate) fn visit_block( - &mut self, - block: BlockExpression, - block_span: Span, - should_indent: bool, - ) { + pub(crate) fn visit_block(&mut self, block: BlockExpression, block_span: Span) { if block.is_empty() { - self.visit_empty_block(block_span, should_indent); + self.visit_empty_block(block_span); return; } @@ -306,10 +299,7 @@ impl FmtVisitor<'_> { self.last_position = block_span.end(); - self.push_str("\n"); - if should_indent { - self.push_str(&self.indent.to_string()); - } + self.push_str(&self.indent.to_string_with_newline()); self.push_str("}"); } @@ -322,19 +312,18 @@ impl FmtVisitor<'_> { } } - fn visit_empty_block(&mut self, block_span: Span, should_indent: bool) { + pub(crate) fn visit_empty_block(&mut self, block_span: Span) { let slice = self.slice(block_span); let comment_str = slice[1..slice.len() - 1].trim(); let block_str = if comment_str.is_empty() { "{}".to_string() } else { self.indent.block_indent(self.config); - let open_indent = self.indent.to_string(); + let (comment_str, _) = self.format_comment_in_block(comment_str); + let comment_str = comment_str.trim_matches('\n'); self.indent.block_unindent(self.config); - let close_indent = if should_indent { self.indent.to_string() } else { String::new() }; - - let ret = format!("{{\n{open_indent}{comment_str}\n{close_indent}}}"); - ret + let close_indent = self.indent.to_string(); + format!("{{\n{comment_str}\n{close_indent}}}") }; self.last_position = block_span.end(); self.push_str(&block_str); diff --git a/tooling/nargo_fmt/src/visitor/item.rs b/tooling/nargo_fmt/src/visitor/item.rs index 09031082fa3..96821fb4f9d 100644 --- a/tooling/nargo_fmt/src/visitor/item.rs +++ b/tooling/nargo_fmt/src/visitor/item.rs @@ -1,5 +1,6 @@ use noirc_frontend::{ parser::{Item, ItemKind}, + token::Token, NoirFunction, ParsedModule, }; @@ -10,24 +11,72 @@ impl super::FmtVisitor<'_> { (slice.trim_end().to_string(), force_brace_newline) } - pub(crate) fn visit_module(&mut self, module: ParsedModule) { + pub(crate) fn visit_file(&mut self, module: ParsedModule) { + self.visit_module(module); + self.format_missing_indent(self.source.len() as u32, false); + } + + fn visit_module(&mut self, module: ParsedModule) { for Item { kind, span } in module.items { match kind { ItemKind::Function(func) => { let (fn_before_block, force_brace_newline) = self.format_fn_before_block(func.clone(), span.start()); - self.format_missing_indent(span.start(), false); + self.format_missing_indent(span.start(), true); self.push_str(&fn_before_block); self.push_str(if force_brace_newline { "\n" } else { " " }); - self.visit_block(func.def.body, func.def.span, false); + self.visit_block(func.def.body, func.def.span); + } + ItemKind::Submodules(module) => { + let name = module.name; + + self.format_missing(span.start()); + + let after_brace = self.span_after(span, Token::LeftBrace).start(); + self.last_position = after_brace; + + let keyword = if module.is_contract { "contract" } else { "mod" }; + + let indent = if self.at_start() + || self.buffer.ends_with(|ch: char| ch.is_whitespace()) + { + self.indent.to_string() + } else { + self.indent.to_string_with_newline() + }; + self.push_str(&format!("{indent}{keyword} {name} ")); + + if module.contents.items.is_empty() { + self.visit_empty_block((after_brace - 1..span.end()).into()); + } else { + self.push_str("{"); + let indent = self.with_indent(|this| { + this.visit_module(module.contents); + + let mut indent = this.indent; + indent.block_unindent(self.config); + indent.to_string_with_newline() + }); + self.push_str(&format!("{indent}}}")); + } + + self.last_position = span.end(); + } + ItemKind::Import(_) + | ItemKind::Struct(_) + | ItemKind::Trait(_) + | ItemKind::TraitImpl(_) + | ItemKind::Impl(_) + | ItemKind::TypeAlias(_) + | ItemKind::Global(_) + | ItemKind::ModuleDecl(_) => { + self.push_rewrite(self.slice(span).to_string(), span); + self.last_position = span.end(); } - _ => self.format_missing(span.end()), } } - - self.format_missing_indent(self.source.len() as u32, false); } } diff --git a/tooling/nargo_fmt/src/visitor/stmt.rs b/tooling/nargo_fmt/src/visitor/stmt.rs index 0a814ebd136..b6dd67323fa 100644 --- a/tooling/nargo_fmt/src/visitor/stmt.rs +++ b/tooling/nargo_fmt/src/visitor/stmt.rs @@ -1,6 +1,8 @@ use std::iter::zip; -use noirc_frontend::{ConstrainKind, ConstrainStatement, ExpressionKind, Statement, StatementKind}; +use noirc_frontend::{ + ConstrainKind, ConstrainStatement, ExpressionKind, ForRange, Statement, StatementKind, +}; use super::ExpressionType; @@ -55,7 +57,24 @@ impl super::FmtVisitor<'_> { self.push_rewrite(constrain, span); } - StatementKind::Assign(_) | StatementKind::For(_) => self.format_missing(span.end()), + StatementKind::For(for_stmt) => { + let identifier = self.slice(for_stmt.identifier.span()); + let range = match for_stmt.range { + ForRange::Range(start, end) => format!( + "{}..{}", + self.format_sub_expr(start), + self.format_sub_expr(end) + ), + ForRange::Array(array) => self.format_sub_expr(array), + }; + let block = self.format_sub_expr(for_stmt.block); + + let result = format!("for {identifier} in {range} {block}"); + self.push_rewrite(result, span); + } + StatementKind::Assign(_) => { + self.push_rewrite(self.slice(span).to_string(), span); + } StatementKind::Error => unreachable!(), } diff --git a/tooling/nargo_fmt/tests/expected/contract.nr b/tooling/nargo_fmt/tests/expected/contract.nr new file mode 100644 index 00000000000..54fe6ff1419 --- /dev/null +++ b/tooling/nargo_fmt/tests/expected/contract.nr @@ -0,0 +1,73 @@ +// 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. +contract Benchmarking { + use dep::value_note::{ + utils::{increment, decrement}, + value_note::{VALUE_NOTE_LEN, ValueNote, ValueNoteMethods}, + }; + + use dep::aztec::{ + context::{Context}, + note::{utils as note_utils, note_getter_options::NoteGetterOptions, note_header::NoteHeader}, + selector::compute_selector, + log::emit_unencrypted_log, + state_vars::{map::Map, public_state::PublicState, set::Set}, + types::type_serialization::field_serialization::{FieldSerializationMethods, FIELD_SERIALIZED_LEN}, + types::address::{AztecAddress}, + }; + + struct Storage { + notes: Map>, + balances: Map>, + } + + impl Storage { + fn init(context: Context) -> pub Self { + Storage { + notes: Map::new(context, 1, |context, slot| { Set::new(context, slot, ValueNoteMethods) }), + balances: Map::new(context, 2, |context, slot| { PublicState::new(context, slot, FieldSerializationMethods) }), + } + } + } + + #[aztec(private)] + fn constructor() {} + + // Nec tincidunt praesent semper feugiat nibh sed pulvinar. Nibh nisl condimentum id venenatis a. + #[aztec(private)] + fn create_note(owner: Field, value: Field) { + increment(storage.notes.at(owner), value, owner); + } + + // Diam quam nulla porttitor massa id. Elit ullamcorper dignissim cras tincidunt lobortis feugiat. + #[aztec(private)] + fn recreate_note(owner: Field, index: u32) { + let owner_notes = storage.notes.at(owner); + let getter_options = NoteGetterOptions::new().set_limit(1).set_offset(index); + let notes = owner_notes.get_notes(getter_options); + let note = notes[0].unwrap_unchecked(); + owner_notes.remove(note); + increment(owner_notes, note.value, owner); + } + + // Ultrices in iaculis nunc sed augue lacus. + #[aztec(public)] + fn increment_balance(owner: Field, value: Field) { + let current = storage.balances.at(owner).read(); + storage.balances.at(owner).write(current + value); + let _callStackItem1 = context.call_public_function(context.this_address(), compute_selector("broadcast(Field)"), [owner]); + } + + // Est ultricies integer quis auctor elit sed. In nibh mauris cursus mattis molestie a iaculis. + #[aztec(public)] + fn broadcast(owner: Field) { + emit_unencrypted_log(&mut context, storage.balances.at(owner).read()); + } + + unconstrained fn compute_note_hash_and_nullifier(contract_address: Field, nonce: Field, storage_slot: Field, preimage: [Field; VALUE_NOTE_LEN]) -> [Field; 4] { + let note_header = NoteHeader::new(contract_address, nonce, storage_slot); + note_utils::compute_note_hash_and_nullifier(ValueNoteMethods, note_header, preimage) + } +} diff --git a/tooling/nargo_fmt/tests/expected/expr.nr b/tooling/nargo_fmt/tests/expected/expr.nr index 20eb6ad547d..c0047e90175 100644 --- a/tooling/nargo_fmt/tests/expected/expr.nr +++ b/tooling/nargo_fmt/tests/expected/expr.nr @@ -50,7 +50,7 @@ fn only_comment() { fn only_comments() { // Keep this here -// Keep this here + // Keep this here } fn only_comments() { diff --git a/tooling/nargo_fmt/tests/expected/for.nr b/tooling/nargo_fmt/tests/expected/for.nr new file mode 100644 index 00000000000..98dff672bef --- /dev/null +++ b/tooling/nargo_fmt/tests/expected/for.nr @@ -0,0 +1,21 @@ +fn for_stmt() { + for elem in self { + ret &= predicate(elem); + } +} + +fn for_stmt() { + for i in 0..(C1 - 1) { + for _j in 1..(C1 - i - 1) { + b *= b; + } + + z *= if b == 1 { 1 } else { c }; + + c *= c; + + t *= if b == 1 { 1 } else { c }; + + b = t; + } +} diff --git a/tooling/nargo_fmt/tests/expected/if.nr b/tooling/nargo_fmt/tests/expected/if.nr index 9893239750c..39ad7d18cdd 100644 --- a/tooling/nargo_fmt/tests/expected/if.nr +++ b/tooling/nargo_fmt/tests/expected/if.nr @@ -1,4 +1,17 @@ +//@error_on_lost_comment=false fn main() { + let (x,y) = if is_square(gx1) { + (x1, sqrt(gx1)) + } else { + (x2, sqrt(gx2)) + }; + + let n = if x != y { + if x != 20 { slice.push_back(y) } else { slice } + } else { + slice + }; + if false { (); (); diff --git a/tooling/nargo_fmt/tests/expected/infix.nr b/tooling/nargo_fmt/tests/expected/infix.nr index f930f79ebcb..0688781ba48 100644 --- a/tooling/nargo_fmt/tests/expected/infix.nr +++ b/tooling/nargo_fmt/tests/expected/infix.nr @@ -1,3 +1,4 @@ +//@error_on_lost_comment=false fn foo() { 40 + 2; !40 + 2; diff --git a/tooling/nargo_fmt/tests/expected/let.nr b/tooling/nargo_fmt/tests/expected/let.nr index dccdb76328c..1c7afc8df5f 100644 --- a/tooling/nargo_fmt/tests/expected/let.nr +++ b/tooling/nargo_fmt/tests/expected/let.nr @@ -1,3 +1,4 @@ +//@error_on_lost_comment=false fn let_() { let fn_call = my_function(some_function(10, "arg1", another_function()), another_func(20, some_function(), 30)); let array = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]], [[13, 14, 15], [16, 17, 18]]]; diff --git a/tooling/nargo_fmt/tests/expected/literals.nr b/tooling/nargo_fmt/tests/expected/literals.nr index abe14c14965..5a9a735337f 100644 --- a/tooling/nargo_fmt/tests/expected/literals.nr +++ b/tooling/nargo_fmt/tests/expected/literals.nr @@ -1,3 +1,4 @@ +//@error_on_lost_comment=false fn main() { [1, 2, 3, 4, 5]; diff --git a/tooling/nargo_fmt/tests/expected/nested_parens.nr b/tooling/nargo_fmt/tests/expected/nested_parens.nr new file mode 100644 index 00000000000..53eaa63c279 --- /dev/null +++ b/tooling/nargo_fmt/tests/expected/nested_parens.nr @@ -0,0 +1,5 @@ +//@remove_nested_parens=false +fn main() { + ((())); + ((((((((())))))))); +} diff --git a/tooling/nargo_fmt/tests/expected/submodule.nr b/tooling/nargo_fmt/tests/expected/submodule.nr new file mode 100644 index 00000000000..88e005b7ac2 --- /dev/null +++ b/tooling/nargo_fmt/tests/expected/submodule.nr @@ -0,0 +1,30 @@ +mod a { + // hello +} + +mod a { + // hello + mod b { + // hello + } +} + +mod a { + mod b { + mod c {} + } +} + +mod a { + // 1 + // 2 + // 3 + /*test*/ +} + +mod a { + /**/ + mod b { + mod c {} + } +} diff --git a/tooling/nargo_fmt/tests/expected/tuple.nr b/tooling/nargo_fmt/tests/expected/tuple.nr index b190a5f7c55..c3b32904f15 100644 --- a/tooling/nargo_fmt/tests/expected/tuple.nr +++ b/tooling/nargo_fmt/tests/expected/tuple.nr @@ -23,7 +23,7 @@ fn main() { (/*1*/ 1, /*2*/ 2); -// FIXME: + // FIXME: (((//2 1,),),); (/*a*/ diff --git a/tooling/nargo_fmt/tests/expected/unary_operators.nr b/tooling/nargo_fmt/tests/expected/unary_operators.nr index 1dd5e4ab945..ffea1713c06 100644 --- a/tooling/nargo_fmt/tests/expected/unary_operators.nr +++ b/tooling/nargo_fmt/tests/expected/unary_operators.nr @@ -1,3 +1,4 @@ +//@error_on_lost_comment=false fn main() { -1; -/*test*/1; diff --git a/tooling/nargo_fmt/tests/input/contract.nr b/tooling/nargo_fmt/tests/input/contract.nr new file mode 100644 index 00000000000..54fe6ff1419 --- /dev/null +++ b/tooling/nargo_fmt/tests/input/contract.nr @@ -0,0 +1,73 @@ +// 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. +contract Benchmarking { + use dep::value_note::{ + utils::{increment, decrement}, + value_note::{VALUE_NOTE_LEN, ValueNote, ValueNoteMethods}, + }; + + use dep::aztec::{ + context::{Context}, + note::{utils as note_utils, note_getter_options::NoteGetterOptions, note_header::NoteHeader}, + selector::compute_selector, + log::emit_unencrypted_log, + state_vars::{map::Map, public_state::PublicState, set::Set}, + types::type_serialization::field_serialization::{FieldSerializationMethods, FIELD_SERIALIZED_LEN}, + types::address::{AztecAddress}, + }; + + struct Storage { + notes: Map>, + balances: Map>, + } + + impl Storage { + fn init(context: Context) -> pub Self { + Storage { + notes: Map::new(context, 1, |context, slot| { Set::new(context, slot, ValueNoteMethods) }), + balances: Map::new(context, 2, |context, slot| { PublicState::new(context, slot, FieldSerializationMethods) }), + } + } + } + + #[aztec(private)] + fn constructor() {} + + // Nec tincidunt praesent semper feugiat nibh sed pulvinar. Nibh nisl condimentum id venenatis a. + #[aztec(private)] + fn create_note(owner: Field, value: Field) { + increment(storage.notes.at(owner), value, owner); + } + + // Diam quam nulla porttitor massa id. Elit ullamcorper dignissim cras tincidunt lobortis feugiat. + #[aztec(private)] + fn recreate_note(owner: Field, index: u32) { + let owner_notes = storage.notes.at(owner); + let getter_options = NoteGetterOptions::new().set_limit(1).set_offset(index); + let notes = owner_notes.get_notes(getter_options); + let note = notes[0].unwrap_unchecked(); + owner_notes.remove(note); + increment(owner_notes, note.value, owner); + } + + // Ultrices in iaculis nunc sed augue lacus. + #[aztec(public)] + fn increment_balance(owner: Field, value: Field) { + let current = storage.balances.at(owner).read(); + storage.balances.at(owner).write(current + value); + let _callStackItem1 = context.call_public_function(context.this_address(), compute_selector("broadcast(Field)"), [owner]); + } + + // Est ultricies integer quis auctor elit sed. In nibh mauris cursus mattis molestie a iaculis. + #[aztec(public)] + fn broadcast(owner: Field) { + emit_unencrypted_log(&mut context, storage.balances.at(owner).read()); + } + + unconstrained fn compute_note_hash_and_nullifier(contract_address: Field, nonce: Field, storage_slot: Field, preimage: [Field; VALUE_NOTE_LEN]) -> [Field; 4] { + let note_header = NoteHeader::new(contract_address, nonce, storage_slot); + note_utils::compute_note_hash_and_nullifier(ValueNoteMethods, note_header, preimage) + } +} diff --git a/tooling/nargo_fmt/tests/input/for.nr b/tooling/nargo_fmt/tests/input/for.nr new file mode 100644 index 00000000000..99b796df820 --- /dev/null +++ b/tooling/nargo_fmt/tests/input/for.nr @@ -0,0 +1,24 @@ +fn for_stmt() { + for elem in self { + ret &= predicate(elem); + } +} + +fn for_stmt() { + for i in 0..(C1-1) { + + for _j in 1..(C1-i-1) { + + b *= b; + + } + + z *= if b == 1 { 1 } else { c }; + + c *= c; + + t *= if b == 1 { 1 } else { c }; + + b = t; + } +} diff --git a/tooling/nargo_fmt/tests/input/if.nr b/tooling/nargo_fmt/tests/input/if.nr index 0985928396d..be72eb79a18 100644 --- a/tooling/nargo_fmt/tests/input/if.nr +++ b/tooling/nargo_fmt/tests/input/if.nr @@ -1,4 +1,9 @@ +//@error_on_lost_comment=false fn main() { + let (x,y) = if is_square(gx1) {(x1, sqrt(gx1))} else {(x2, sqrt(gx2))}; + + let n = if x != y { if x != 20 { slice.push_back(y) } else { slice } } else { slice }; + if false { (); diff --git a/tooling/nargo_fmt/tests/input/infix.nr b/tooling/nargo_fmt/tests/input/infix.nr index df57f956097..b16ccd02982 100644 --- a/tooling/nargo_fmt/tests/input/infix.nr +++ b/tooling/nargo_fmt/tests/input/infix.nr @@ -1,3 +1,4 @@ +//@error_on_lost_comment=false fn foo() { 40 + 2; !40+2; diff --git a/tooling/nargo_fmt/tests/input/let.nr b/tooling/nargo_fmt/tests/input/let.nr index ae23f0150d9..67c4ab8bd52 100644 --- a/tooling/nargo_fmt/tests/input/let.nr +++ b/tooling/nargo_fmt/tests/input/let.nr @@ -1,3 +1,4 @@ +//@error_on_lost_comment=false fn let_() { let fn_call = my_function(some_function( 10, "arg1", another_function() ),another_func (20, some_function() , 30 )); let array = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]], [[13, 14, 15], [16, 17, 18]]]; diff --git a/tooling/nargo_fmt/tests/input/literals.nr b/tooling/nargo_fmt/tests/input/literals.nr index 3490c1e7d0d..fbdc7676845 100644 --- a/tooling/nargo_fmt/tests/input/literals.nr +++ b/tooling/nargo_fmt/tests/input/literals.nr @@ -1,4 +1,4 @@ - +//@error_on_lost_comment=false fn main() { [1,2,3,4,5]; diff --git a/tooling/nargo_fmt/tests/input/nested_parens.nr b/tooling/nargo_fmt/tests/input/nested_parens.nr new file mode 100644 index 00000000000..53eaa63c279 --- /dev/null +++ b/tooling/nargo_fmt/tests/input/nested_parens.nr @@ -0,0 +1,5 @@ +//@remove_nested_parens=false +fn main() { + ((())); + ((((((((())))))))); +} diff --git a/tooling/nargo_fmt/tests/input/submodule.nr b/tooling/nargo_fmt/tests/input/submodule.nr new file mode 100644 index 00000000000..d5b162fd28d --- /dev/null +++ b/tooling/nargo_fmt/tests/input/submodule.nr @@ -0,0 +1,25 @@ +mod a { +// hello +} + +mod a { +// hello + mod b { +// hello + } +} + +mod a {mod b {mod c {}}} + +mod a { +// 1 +// 2 +// 3 +/*test*/ +} + +mod a { + /**/ mod b { + mod c {} + } +} diff --git a/tooling/nargo_fmt/tests/input/unary_operators.nr b/tooling/nargo_fmt/tests/input/unary_operators.nr index e6d42456ef2..4324b8045cc 100644 --- a/tooling/nargo_fmt/tests/input/unary_operators.nr +++ b/tooling/nargo_fmt/tests/input/unary_operators.nr @@ -1,3 +1,4 @@ +//@error_on_lost_comment=false fn main() { -1; -/*test*/1; diff --git a/tooling/nargo_toml/Cargo.toml b/tooling/nargo_toml/Cargo.toml index d3767a0b038..c835ddd936c 100644 --- a/tooling/nargo_toml/Cargo.toml +++ b/tooling/nargo_toml/Cargo.toml @@ -17,5 +17,6 @@ serde.workspace = true thiserror.workspace = true toml.workspace = true url.workspace = true +semver = "1.0.20" [dev-dependencies] diff --git a/tooling/nargo_toml/src/errors.rs b/tooling/nargo_toml/src/errors.rs index 9abeab97b61..fdbdc317bf9 100644 --- a/tooling/nargo_toml/src/errors.rs +++ b/tooling/nargo_toml/src/errors.rs @@ -4,7 +4,8 @@ use nargo::package::PackageType; use noirc_frontend::graph::CrateName; use thiserror::Error; -/// Errors covering situations where a package is either missing or malformed. +/// Errors covering situations where a package is either missing, malformed or does not pass semver +/// validation checks. #[derive(Debug, Error)] pub enum ManifestError { /// Package doesn't have a manifest file @@ -65,4 +66,19 @@ pub enum ManifestError { #[error("No common ancestor between {root} and {current}")] NoCommonAncestor { root: PathBuf, current: PathBuf }, + + #[error(transparent)] + SemverError(SemverError), +} + +#[derive(Error, Debug, PartialEq, Eq, Clone)] +pub enum SemverError { + #[error("Incompatible compiler version in package {package_name}. Required compiler version is {required_compiler_version} but the compiler version is {compiler_version_found}.\n Update the compiler_version field in Nargo.toml to >={compiler_version_found} or compile this project with version {compiler_version_found}")] + IncompatibleVersion { + package_name: CrateName, + required_compiler_version: String, + compiler_version_found: String, + }, + #[error("Could not parse the required compiler version for package {package_name} in Nargo.toml. Error: {error}")] + CouldNotParseRequiredVersion { package_name: String, error: String }, } diff --git a/tooling/nargo_toml/src/lib.rs b/tooling/nargo_toml/src/lib.rs index 5d12c09a81e..223ed2da081 100644 --- a/tooling/nargo_toml/src/lib.rs +++ b/tooling/nargo_toml/src/lib.rs @@ -18,6 +18,7 @@ use serde::Deserialize; mod errors; mod git; +mod semver; pub use errors::ManifestError; use git::clone_git_repo; @@ -163,6 +164,7 @@ impl PackageConfig { }; Ok(Package { + compiler_required_version: self.package.compiler_version.clone(), root_dir: root_dir.to_path_buf(), entry_path, package_type, @@ -228,7 +230,7 @@ struct PackageMetadata { entry: Option, description: Option, authors: Option>, - // If not compiler version is supplied, the latest is used + // If no compiler version is supplied, the latest is used // For now, we state that all packages must be compiled under the same // compiler version. // We also state that ACIR and the compiler will upgrade in lockstep. @@ -391,10 +393,14 @@ pub enum PackageSelection { pub fn resolve_workspace_from_toml( toml_path: &Path, package_selection: PackageSelection, + current_compiler_version: Option, ) -> Result { let nargo_toml = read_toml(toml_path)?; - - toml_to_workspace(nargo_toml, package_selection) + let workspace = toml_to_workspace(nargo_toml, package_selection)?; + if let Some(current_compiler_version) = current_compiler_version { + semver::semver_check_workspace(workspace.clone(), current_compiler_version)?; + } + Ok(workspace) } #[test] @@ -404,7 +410,7 @@ fn parse_standard_toml() { [package] name = "test" authors = ["kev", "foo"] - compiler_version = "0.1" + compiler_version = "*" [dependencies] rand = { tag = "next", git = "https://github.com/rust-lang-nursery/rand"} @@ -422,7 +428,7 @@ fn parse_package_toml_no_deps() { [package] name = "test" authors = ["kev", "foo"] - compiler_version = "0.1" + compiler_version = "*" "#; assert!(Config::try_from(String::from(src)).is_ok()); diff --git a/tooling/nargo_toml/src/semver.rs b/tooling/nargo_toml/src/semver.rs new file mode 100644 index 00000000000..de722f06bd8 --- /dev/null +++ b/tooling/nargo_toml/src/semver.rs @@ -0,0 +1,196 @@ +use crate::{errors::SemverError, ManifestError}; +use nargo::{ + package::{Dependency, Package}, + workspace::Workspace, +}; +use semver::{Version, VersionReq}; + +// Check that all of the packages in the workspace are compatible with the current compiler version +pub(crate) fn semver_check_workspace( + workspace: Workspace, + current_compiler_version: String, +) -> Result<(), ManifestError> { + let version = Version::parse(¤t_compiler_version) + .expect("The compiler version is not a valid semver version"); + for package in &workspace.members { + semver_check_package(package, &version).map_err(ManifestError::SemverError)?; + } + + Ok(()) +} + +// Check that a package and all of its dependencies are compatible with the current compiler version +pub(crate) fn semver_check_package( + package: &Package, + compiler_version: &Version, +) -> Result<(), SemverError> { + // Check that this package's compiler version requirements are satisfied + if let Some(version) = &package.compiler_required_version { + let version_req = match VersionReq::parse(version) { + Ok(version_req) => version_req, + Err(err) => { + return Err(SemverError::CouldNotParseRequiredVersion { + package_name: package.name.clone().into(), + error: err.to_string(), + }) + } + }; + if !version_req.matches(compiler_version) { + return Err(SemverError::IncompatibleVersion { + package_name: package.name.clone(), + required_compiler_version: version.clone(), + compiler_version_found: strip_build_meta_data(compiler_version), + }); + }; + } + + // Check that all of this package's dependencies' compiler version requirements are satisfied + for dep in package.dependencies.values() { + match dep { + Dependency::Local { package } | Dependency::Remote { package } => { + semver_check_package(package, compiler_version)?; + } + } + } + + Ok(()) +} + +// Strip the build meta data from the version string since it is ignored by semver. +fn strip_build_meta_data(version: &Version) -> String { + let version_string = version.to_string(); + let mut split = version_string.split('+'); + split.next().expect("split was called on an empty string").to_string() +} + +#[cfg(test)] +mod tests { + use std::{collections::BTreeMap, path::PathBuf, str::FromStr}; + + use nargo::package::PackageType; + use noirc_frontend::graph::CrateName; + + use super::*; + + #[test] + fn test_semver_check_smoke() { + let compiler_version = Version::parse("0.1.0").unwrap(); + + let mut package = Package { + compiler_required_version: Some("0.1.0".to_string()), + root_dir: PathBuf::new(), + package_type: PackageType::Library, + entry_path: PathBuf::new(), + name: CrateName::from_str("test").unwrap(), + dependencies: BTreeMap::new(), + }; + if let Err(err) = semver_check_package(&package, &compiler_version) { + panic!("semver check should have passed. compiler version is 0.1.0 and required version from the package is 0.1.0\n error: {err:?}") + }; + + package.compiler_required_version = Some("0.2.0".to_string()); + let got_err = match semver_check_package(&package, &compiler_version) { + Ok(_) => panic!("semver check should have failed. compiler version is 0.1.0 and required version from the package is 0.2.0"), + Err(err) => err, + }; + + let expected_version_error = SemverError::IncompatibleVersion { + package_name: CrateName::from_str("test").unwrap(), + required_compiler_version: "0.2.0".to_string(), + compiler_version_found: "0.1.0".to_string(), + }; + assert_eq!(got_err, expected_version_error); + } + + #[test] + fn test_semver_dependency_check_smoke() { + let compiler_version = Version::parse("0.1.0").unwrap(); + + let mut package = Package { + compiler_required_version: Some("0.1.0".to_string()), + root_dir: PathBuf::new(), + package_type: PackageType::Library, + entry_path: PathBuf::new(), + name: CrateName::from_str("test").unwrap(), + dependencies: BTreeMap::new(), + }; + + let valid_dependency = Package { + compiler_required_version: Some("0.1.0".to_string()), + root_dir: PathBuf::new(), + package_type: PackageType::Library, + entry_path: PathBuf::new(), + name: CrateName::from_str("good_dependency").unwrap(), + dependencies: BTreeMap::new(), + }; + let invalid_dependency = Package { + compiler_required_version: Some("0.2.0".to_string()), + root_dir: PathBuf::new(), + package_type: PackageType::Library, + entry_path: PathBuf::new(), + name: CrateName::from_str("bad_dependency").unwrap(), + dependencies: BTreeMap::new(), + }; + + package.dependencies.insert( + CrateName::from_str("test_dep_valid").unwrap(), + Dependency::Local { package: valid_dependency.clone() }, + ); + + if let Err(err) = semver_check_package(&package, &compiler_version) { + panic!("semver check should have passed. compiler version is 0.1.0 and required version from the package is 0.1.0\n error: {err:?}") + }; + + package.dependencies.insert( + CrateName::from_str("test_dep_invalid").unwrap(), + Dependency::Local { package: invalid_dependency.clone() }, + ); + let got_err = match semver_check_package(&package,&compiler_version) { + Ok(_) => panic!("semver check should have failed. compiler version is 0.1.0 and required version from the package is 0.2.0"), + Err(err) => err, + }; + + let expected_version_error = SemverError::IncompatibleVersion { + package_name: CrateName::from_str("bad_dependency").unwrap(), + required_compiler_version: "0.2.0".to_string(), + compiler_version_found: "0.1.0".to_string(), + }; + assert_eq!(got_err, expected_version_error); + } + + #[test] + fn test_semver_carrot() { + let compiler_version = Version::parse("0.2.0").unwrap(); + + let package = Package { + compiler_required_version: Some(">=0.1.0".to_string()), + root_dir: PathBuf::new(), + package_type: PackageType::Library, + entry_path: PathBuf::new(), + name: CrateName::from_str("test").unwrap(), + dependencies: BTreeMap::new(), + }; + + if let Err(err) = semver_check_package(&package, &compiler_version) { + panic!("semver check should have passed. compiler version is 0.2.0 and required version from the package is >=0.1.0\n error: {err:?}") + }; + } + + #[test] + fn test_semver_build_data() { + let compiler_version = Version::parse("0.1.0+this-is-ignored-by-semver").unwrap(); + + let package = Package { + compiler_required_version: Some("0.1.0".to_string()), + root_dir: PathBuf::new(), + package_type: PackageType::Library, + entry_path: PathBuf::new(), + name: CrateName::from_str("test").unwrap(), + dependencies: BTreeMap::new(), + }; + + if let Err(err) = semver_check_package(&package, &compiler_version) { + panic!("semver check should have passed. compiler version is 0.1.0+build_data and required version from the package is 0.1.0\n The build data should be ignored\n error: {err:?}") + }; + } +} diff --git a/tooling/noir_js/src/index.ts b/tooling/noir_js/src/index.ts index 3d424ca0dea..35a3e716b6b 100644 --- a/tooling/noir_js/src/index.ts +++ b/tooling/noir_js/src/index.ts @@ -1,8 +1,16 @@ import * as acvm from '@noir-lang/acvm_js'; import * as abi from '@noir-lang/noirc_abi'; - export { acvm, abi }; -export { WitnessMap } from '@noir-lang/acvm_js'; +export { + ecdsa_secp256r1_verify, + ecdsa_secp256k1_verify, + keccak256, + blake2s256, + sha256, + xor, + and, +} from '@noir-lang/acvm_js'; +export { WitnessMap, ForeignCallHandler, ForeignCallInput, ForeignCallOutput } from '@noir-lang/acvm_js'; export { Noir } from './program.js'; diff --git a/tooling/noir_js/src/program.ts b/tooling/noir_js/src/program.ts index bf48e15fcad..cfd7a715dfe 100644 --- a/tooling/noir_js/src/program.ts +++ b/tooling/noir_js/src/program.ts @@ -2,7 +2,7 @@ import { Backend, CompiledCircuit, ProofData } from '@noir-lang/types'; import { generateWitness } from './witness_generation.js'; import initAbi, { abiDecode, InputMap, InputValue } from '@noir-lang/noirc_abi'; -import initACVM, { compressWitness } from '@noir-lang/acvm_js'; +import initACVM, { compressWitness, ForeignCallHandler } from '@noir-lang/acvm_js'; export class Noir { constructor( @@ -29,9 +29,12 @@ export class Noir { } // Initial inputs to your program - async execute(inputs: InputMap): Promise<{ witness: Uint8Array; returnValue: InputValue }> { + async execute( + inputs: InputMap, + foreignCallHandler?: ForeignCallHandler, + ): Promise<{ witness: Uint8Array; returnValue: InputValue }> { await this.init(); - const witness = await generateWitness(this.circuit, inputs); + const witness = await generateWitness(this.circuit, inputs, foreignCallHandler); const { return_value: returnValue } = abiDecode(this.circuit.abi, witness); return { witness: compressWitness(witness), returnValue }; } diff --git a/tooling/noir_js/src/witness_generation.ts b/tooling/noir_js/src/witness_generation.ts index f96cddb0eca..e3ddb1a2a21 100644 --- a/tooling/noir_js/src/witness_generation.ts +++ b/tooling/noir_js/src/witness_generation.ts @@ -1,19 +1,25 @@ import { abiEncode, InputMap } from '@noir-lang/noirc_abi'; import { base64Decode } from './base64_decode.js'; -import { executeCircuit, WitnessMap } from '@noir-lang/acvm_js'; +import { executeCircuit, WitnessMap, ForeignCallHandler, ForeignCallInput } from '@noir-lang/acvm_js'; import { CompiledCircuit } from '@noir-lang/types'; +const defaultForeignCallHandler: ForeignCallHandler = (name: string, args: ForeignCallInput[]) => { + throw Error(`Unexpected oracle during execution: ${name}(${args.join(', ')})`); +}; + // Generates the witnesses needed to feed into the chosen proving system -export async function generateWitness(compiledProgram: CompiledCircuit, inputs: InputMap): Promise { +export async function generateWitness( + compiledProgram: CompiledCircuit, + inputs: InputMap, + foreignCallHandler: ForeignCallHandler = defaultForeignCallHandler, +): Promise { // Throws on ABI encoding error const witnessMap = abiEncode(compiledProgram.abi, inputs); // Execute the circuit to generate the rest of the witnesses and serialize // them into a Uint8Array. try { - const solvedWitness = await executeCircuit(base64Decode(compiledProgram.bytecode), witnessMap, () => { - throw Error('unexpected oracle during execution'); - }); + const solvedWitness = await executeCircuit(base64Decode(compiledProgram.bytecode), witnessMap, foreignCallHandler); return solvedWitness; } catch (err) { throw new Error(`Circuit execution failed: ${err}`); diff --git a/tooling/noir_js/test/noir_compiled_examples/assert_lt/Nargo.toml b/tooling/noir_js/test/noir_compiled_examples/assert_lt/Nargo.toml index 742f100681f..f32ec18cae7 100644 --- a/tooling/noir_js/test/noir_compiled_examples/assert_lt/Nargo.toml +++ b/tooling/noir_js/test/noir_compiled_examples/assert_lt/Nargo.toml @@ -2,6 +2,4 @@ name = "assert_lt" type = "bin" authors = [""] -compiler_version = "0.1" - [dependencies] diff --git a/tooling/noir_js/test/noir_compiled_examples/assert_lt/src/main.nr b/tooling/noir_js/test/noir_compiled_examples/assert_lt/src/main.nr index 8deda68c051..67b8c84bdcd 100644 --- a/tooling/noir_js/test/noir_compiled_examples/assert_lt/src/main.nr +++ b/tooling/noir_js/test/noir_compiled_examples/assert_lt/src/main.nr @@ -1,4 +1,4 @@ fn main(x : u64, y : pub u64) -> pub u64 { - assert(x < y); - x + y + assert(x < y); + x + y } diff --git a/tooling/noir_js_backend_barretenberg/package.json b/tooling/noir_js_backend_barretenberg/package.json index 3dbfb52a7f8..fda43583629 100644 --- a/tooling/noir_js_backend_barretenberg/package.json +++ b/tooling/noir_js_backend_barretenberg/package.json @@ -32,7 +32,7 @@ "lint": "NODE_NO_WARNINGS=1 eslint . --ext .ts --ignore-path ./.eslintignore --max-warnings 0" }, "dependencies": { - "@aztec/bb.js": "0.11.0", + "@aztec/bb.js": "0.12.0", "@noir-lang/types": "workspace:*", "fflate": "^0.8.0" }, diff --git a/tooling/noirc_abi_wasm/Cargo.toml b/tooling/noirc_abi_wasm/Cargo.toml index 130f022dd1f..c78c3ead0c3 100644 --- a/tooling/noirc_abi_wasm/Cargo.toml +++ b/tooling/noirc_abi_wasm/Cargo.toml @@ -18,17 +18,16 @@ iter-extended.workspace = true wasm-bindgen.workspace = true serde.workspace = true js-sys.workspace = true - -console_error_panic_hook = "0.1.7" -gloo-utils = { version = "0.1", features = ["serde"] } +console_error_panic_hook.workspace = true +gloo-utils.workspace = true # This is an unused dependency, we are adding it # so that we can enable the js feature in getrandom. -getrandom = { version = "*", features = ["js"] } +getrandom = { workspace = true, features = ["js"] } [build-dependencies] -build-data = "0.1.3" +build-data.workspace = true [dev-dependencies] -wasm-bindgen-test = "0.3.36" +wasm-bindgen-test.workspace = true diff --git a/yarn.lock b/yarn.lock index fa4a28d9988..2efc4eabfec 100644 --- a/yarn.lock +++ b/yarn.lock @@ -221,9 +221,9 @@ __metadata: languageName: node linkType: hard -"@aztec/bb.js@npm:0.11.0": - version: 0.11.0 - resolution: "@aztec/bb.js@npm:0.11.0" +"@aztec/bb.js@npm:0.12.0": + version: 0.12.0 + resolution: "@aztec/bb.js@npm:0.12.0" dependencies: comlink: ^4.4.1 commander: ^10.0.1 @@ -231,7 +231,7 @@ __metadata: tslib: ^2.4.0 bin: bb.js: dest/node/main.js - checksum: fff6813458dfa654210859dbf32abcb6c520ef8b3c4896535afa1bbc4a1a6dc77fd5626051fe0017de2f4b03d09bd9629fa1a144df2af3270a2e00faa779362d + checksum: d9d57b893b9b1c61949cb9bd911d4b7e1ece34965ccb9e122b39cd4e2edac9f06858abbe05c23f66141c9a74ff4861a354bfc5d62e5dcf772cfe8d1c783e2562 languageName: node linkType: hard @@ -3434,7 +3434,7 @@ __metadata: version: 0.0.0-use.local resolution: "@noir-lang/backend_barretenberg@workspace:tooling/noir_js_backend_barretenberg" dependencies: - "@aztec/bb.js": 0.11.0 + "@aztec/bb.js": 0.12.0 "@noir-lang/types": "workspace:*" "@types/node": ^20.6.2 "@types/prettier": ^3